package cn.iocoder.yudao.module.app.controller;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.common.SystemEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.app.vo.WxLoginBody;
import cn.iocoder.yudao.module.wechat.service.WechatService;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import cn.iocoder.yudao.util.AESUtil;
import cn.iocoder.yudao.util.WechatPayConfig;
import com.alibaba.fastjson.JSONObject;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@Slf4j
@RequestMapping("/userClient/repair")
public class LoginController {
    @Resource
    private AdminAuthService loginService;
    @Resource
    private WechatPayConfig wxConfig;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SecurityProperties securityProperties;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private AESUtil aesUtil;

    /**
     * 微信授权登录
     * @author vinjor-M
     * @date 17:43 2024/10/10
     * @param wxLoginBody 请求体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
    **/
    @PostMapping("/wxLogin")
    @TenantIgnore
    public CommonResult<?> wxLogin(@RequestBody WxLoginBody wxLoginBody) {
        String code = wxLoginBody.getCode();
        //秘钥
        String encryptedIv = wxLoginBody.getEncryptedIv();
        //加密数据
        String encryptedData = wxLoginBody.getEncryptedData();
        //想微信服务器发送请求获取用户信息
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + wxConfig.getRepairAppId() + "&secret=" + wxConfig.getRepairAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        String res = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSONObject.parseObject(res);
        //获取session_key和openid
        String sessionKey = jsonObject.getString("session_key");
        String openId = jsonObject.getString("openid");
        //解密
        String decryptResult = "";
        try {
            //如果没有绑定微信开放平台，解析结果是没有unionid的。
            decryptResult = aesUtil.decrypt(sessionKey, encryptedIv, encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return error(500, "微信登录失败！");
        }
        if (StringUtils.hasText(decryptResult)) {
            //如果解析成功,获取token
            //查用户（未注册的话自动注册）
            AdminUserDO adminUserDO = wechatService.wechatLogin(SystemEnum.REPAIR.getCode(),decryptResult,openId,wxLoginBody.getInviteId());
            //登录生成token
            AuthLoginRespVO loginVO = loginService.wxLoginByUserId(adminUserDO.getId(),adminUserDO.getUsername());
            Map<String, Object> map = new HashMap<>();
            map.put("token", loginVO.getAccessToken());
            map.put("userinfo", adminUserDO);
            return success(map);
        } else {
            return error(500, "微信登录失败！");
        }
    }

    @PostMapping("/logout")
    @Operation(summary = "登出系统")
    public CommonResult<Boolean> logout(HttpServletRequest request) {
        String token = SecurityFrameworkUtils.obtainAuthorization(request,
                securityProperties.getTokenHeader(), securityProperties.getTokenParameter());
        if (StrUtil.isNotBlank(token)) {
            loginService.logout(token,1);
        }
        return success(true);
    }
}
