package com.bonus.sgzb.auth.service;

import com.alibaba.fastjson.JSON;
import com.bonus.sgzb.auth.form.*;
import com.bonus.sgzb.auth.utils.HttpUtils;
import com.bonus.sgzb.common.core.constant.SecurityConstants;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.system.api.RemoteUserService;
import com.bonus.sgzb.system.api.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author：梁超
 * @date：2024/1/26 - 13:25
 */
@Slf4j
@Component
public class NwUserLoginService {


    @Resource
    private RemoteUserService userService;

    @Autowired
    private TokenService tokenService;

    /**
     * 调用微服务平台认证接口
     *
     * @return 登录信息
     */
    public R<?> onlineApprove(AuthenticationLoginFrom loginForm) throws Exception {
        String code = loginForm.getCode();
        String redirectUrl = loginForm.getRedirectUrl();
        String grantType = loginForm.getType();
        // 微服务平台认证接口
        MultiValueMap<String, String> reqMap = new LinkedMultiValueMap<>();
        if (StringUtils.isBlank(redirectUrl)) {
            return R.fail("参数redirectUrl不能为空");
        }
        if (StringUtils.isBlank(code)) {
            return R.fail("参数code不能为空");
        }

        LoginResultForm loginResultForm = new LoginResultForm();
        loginResultForm.setReturnUrl(redirectUrl);
        loginResultForm.setAccountType(null);

        reqMap.set(NwLoginConstants.REDIRECT_URI, redirectUrl);
        reqMap.set(NwLoginConstants.CODE, code);
        reqMap.set(NwLoginConstants.GRANT_TYPE, grantType);
        reqMap.set(NwLoginConstants.SCOPE, NwLoginConstants.SCOPE_ALL);
        OnlineApprove onlineApprove = new OnlineApprove();
        onlineApprove.setCode(3);
        onlineApprove.setAppId(NwLoginConstants.wechatAppId);
        onlineApprove.setAppsecret(NwLoginConstants.wechatAppsecret);
        Map<String, Object> resultMap = HttpUtils.postFormForOauth2(NwLoginConstants.onlineApprove, reqMap, null, onlineApprove);
        log.info("微服务平台认证, 调用南网用户中心, result: {}", JSON.toJSONString(resultMap));
        if (StringUtils.isNotEmpty((String) resultMap.get(NwLoginConstants.CODE))) {
            String Code = resultMap.get(NwLoginConstants.CODE).toString();
            String Message = resultMap.get(NwLoginConstants.MESSAGE).toString();
            String Data = resultMap.get(NwLoginConstants.DATA).toString();
            return R.fail(Code + Message + Data);
        }

        //查询登陆用户详细信息 不脱敏查询
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("cancelDesensitization", "true");
        RespLoginData<LoginUserInfoRespDTO> loginUserInfoRespData = HttpUtils.postForm(NwLoginConstants.getNowPersonDetailData, null, (String) resultMap.get("access_token"), LoginUserInfoRespDTO.class, requestMap, onlineApprove);
        log.info("查询登陆用户详细信息, 调用南网用户中心, result: {}", JSON.toJSONString(loginUserInfoRespData));
        if (!NwLoginConstants.HTTP_RESPONSE_CODE_200.equals(loginUserInfoRespData.getCode())) {
            return R.fail(loginUserInfoRespData.getCode() + loginUserInfoRespData.getMessage() + loginResultForm);
        }
        LoginUserInfoRespDTO loginUserInfoRespDTO = loginUserInfoRespData.getData();
        String mobilePhone = loginUserInfoRespDTO.getMobilePhone();
        String userName = loginUserInfoRespDTO.getUserName();
       /* String nickName = loginUserInfoRespDTO.getNickName();
        String email = loginUserInfoRespDTO.getEmail();
        String sex = loginUserInfoRespDTO.getSex();
        String headPortrait = loginUserInfoRespDTO.getHeadPortrait();
        String psCode = loginUserInfoRespDTO.getPsCode();
        String status = loginUserInfoRespDTO.getStatus();
        String loginIp = loginUserInfoRespDTO.getLoginIp();
        String loginTime = loginUserInfoRespDTO.getLoginTime().toString();
        String createUserName = loginUserInfoRespDTO.getCreateUserName();
        String createTime = loginUserInfoRespDTO.getCreateTime();
        String updateUserName = loginUserInfoRespDTO.getUpdateUserName();
        String updateTime = loginUserInfoRespDTO.getUpdateTime();*/
        //根据用户名查询用户
        R<LoginUser> userInfo = userService.getUserInfo(userName, SecurityConstants.INNER);
        if (null == userInfo.getData()) {
            return R.fail(NwLoginConstants.LOGIN_ERROR_CODE,NwLoginConstants.LOGIN_ERROR_MESSAGE);
            //未找到该用户，新增该用户
           /* SysUser user = new SysUser();
            user.setUserName(userName);
            user.setNickName(nickName);
            user.setEmail(email);
            user.setPhonenumber(mobilePhone);
            user.setSex(sex);
            user.setAvatar(headPortrait);
            user.setPassword(psCode);
            if ("ENABLE".equals(status)){
                user.setStatus("0");
            }else {
                user.setStatus("1");
            }
            user.setLoginIp(loginIp);
            user.setLoginDate(DateUtil.parse(loginTime,"yyyy-MM-dd HH:mm:ss"));
            user.setCreateBy(createUserName);
            user.setCreateTime(DateUtil.parse(createTime,"yyyy-MM-dd HH:mm:ss"));
            user.setUpdateBy(updateUserName);
            user.setUpdateTime(DateUtil.parse(updateTime,"yyyy-MM-dd HH:mm:ss"));*/
        }
//        return R.ok(userInfo);
        LoginUser data = userInfo.getData();
        return R.ok(tokenService.createToken(data));
    }
}
