package com.tuoheng.admin.service.third.oidc;

import com.tuoheng.admin.constant.OidcUrlConstant;
import com.tuoheng.admin.entity.domain.User;
import com.tuoheng.admin.entity.request.oidc.OidcUpdateUserPasswordRequest;
import com.tuoheng.common.core.config.common.CommonConfig;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.SecurityUserUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Service
public class EditOidcUserPasswordService {

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    public JsonResult editUserPassword(User user, String password) {
        OidcUpdateUserPasswordRequest oidcUpdateUserPasswordRequest = new OidcUpdateUserPasswordRequest();
        oidcUpdateUserPasswordRequest.setUsername(user.getUsername());

        //  重置密码
        oidcUpdateUserPasswordRequest.setPassword(password);

        //设置请求头
        org.springframework.http.HttpHeaders resultRequestHeader = new HttpHeaders();
        resultRequestHeader.add("Authorization", "Bearer " + SecurityUserUtils.token());
      
        HttpEntity httpEntity = new HttpEntity(oidcUpdateUserPasswordRequest, resultRequestHeader);
        //设置地址，飞手小程序 经过网关
        String url = CommonConfig.oidcUrl + OidcUrlConstant.USER_UPDATEPASS;
        ResponseEntity<JsonResult> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, JsonResult.class);
        } catch (Exception e) {
            log.error("oidc修改用户密码失败");
            return JsonResult.error("oidc修改用户密码失败");
        }
        if (null == response || !response.hasBody()) {
            log.error("oidc修改用户密码响应失败");
            return JsonResult.error("oidc修改用户密码失败");
        }
        if (response.getBody().getCode() != JsonResult.SUCCESS) {
            log.error("oidc修改用户密码失败" + response.getBody());
            return JsonResult.error(response.getBody().getMsg());
        }
        return JsonResult.success(null,"用户密码修改成功");
    }

}
