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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.common.CommonErrorCodeConstants;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.config.SecurityProperties;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.util.RedisCache;
import cn.iocoder.yudao.module.rescue.domain.DriverInfo;
import cn.iocoder.yudao.module.rescue.domain.LoginBody;
import cn.iocoder.yudao.module.rescue.domain.WxLoginBody;
import cn.iocoder.yudao.module.rescue.service.IDriverInfoService;
import cn.iocoder.yudao.module.rescue.utils.RescueSysLoginService;
import cn.iocoder.yudao.util.SendSmsUtil;
import cn.iocoder.yudao.module.rescue.vo.RegisterVO;
import cn.iocoder.yudao.module.shop.entity.ShopConfig;
import cn.iocoder.yudao.module.shop.entity.UserBalance;
import cn.iocoder.yudao.module.shop.service.IShopConfigService;
import cn.iocoder.yudao.module.shop.service.IUserBalanceService;
import cn.iocoder.yudao.module.system.controller.admin.user.vo.user.UserSaveReqVO;
import cn.iocoder.yudao.util.WechatPayConfig;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.permission.PermissionApi;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.permission.dto.RoleReqDTO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginReqVO;
import cn.iocoder.yudao.module.system.controller.admin.auth.vo.AuthLoginRespVO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.MenuDO;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import cn.iocoder.yudao.module.system.service.permission.MenuService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.*;
import static cn.iocoder.yudao.module.rescue.utils.RescueSysLoginService.generateVerificationCode;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@Slf4j
@RequestMapping("/rescue")
public class SysLoginController {
    @Resource
    private AdminAuthService loginService;

    @Resource
    private MenuService menuService;

    @Resource
    private AdminUserService userService;

    @Resource
    private PermissionApi permissionApi;

    @Resource
    private RoleApi roleApi;

    @Resource
    private DictDataApi dataApi;

    @Resource
    private RedisCache redisCache2;

    @Resource
    private RescueSysLoginService rescueSysLoginService;

    @Resource
    private WechatPayConfig wxConfig;

    @Resource
    private RoleService roleService;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private SecurityProperties securityProperties;

    @Resource
    private IUserBalanceService balanceService;
//    @Autowired
//    private IShopMallPartnersService partnersService;
//    @Autowired
//    private IPartnerWorkerService jcWorkerService;
    @Resource
    private IShopConfigService configService;
    @Resource
    private IDriverInfoService driverInfoService;
//    @Autowired
//    private IDriveSchoolInfoService driveSchoolInfoService;
//

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public CommonResult login(@RequestBody LoginBody loginBody) {
        // 生成令牌
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());
        return success(loginService.login(authLoginReqVO));
    }

    @GetMapping("/dict/data/type/{type}")
    public CommonResult getDictDataByType(@PathVariable("type") String type){
        return success(dataApi.getDictDataList(type));
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginApp")
    @TenantIgnore
    public CommonResult loginApp(@RequestBody LoginBody loginBody) throws Exception {
        String userName = loginBody.getUsername();
        AdminUserDO user = userService.getUserByUsername(userName);
        if (ObjectUtil.isEmpty(user)) {
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
        // 获取登录用户的角色信息
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        if (ObjectUtil.isEmpty(roleIdsByUserId) || roleIdsByUserId.size() == 0) {
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<String> roleNames = roleList.stream().filter(item -> roleIdsByUserId.contains(item.getId())).map(item -> item.getName()).collect(Collectors.toList());
        Boolean flag = (loginBody.getType().equals("0") && roleNames.contains("调度中心")) || (loginBody.getType().equals("0") && roleNames.contains("交警大队"));
        // 角色认证登录
        if (!flag) {
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());
        return success(loginService.login(authLoginReqVO));
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginJcApp")
    @TenantIgnore
    public CommonResult loginJcApp(@RequestBody LoginBody loginBody) throws Exception {
        String userName = loginBody.getUsername();
        AdminUserDO user = userService.getUserByUsername(userName);
        if (ObjectUtil.isEmpty(user)) {
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());
        return success(loginService.login(authLoginReqVO));
    }


    /**
     * 汽修小程序登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginQx")
    @TenantIgnore
    public CommonResult loginQx(@RequestBody LoginBody loginBody) throws Exception {
        String userName = loginBody.getUsername();
        AdminUserDO user = userService.getUserByUsername(userName);
        if (ObjectUtil.isEmpty(user)) {
            return error(CommonErrorCodeConstants.LOGIN_ACCOUNT_NOT_EXIST);
        }
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());

        AuthLoginRespVO login = loginService.login(authLoginReqVO);
        Map<String,Object> map = new HashMap<>();
        map.put("accessToken",login.getAccessToken());
        map.put("expiresTime",login.getExpiresTime());
        map.put("refreshToken",login.getRefreshToken());
        map.put("userId",login.getUserId());
        if(org.apache.commons.lang3.StringUtils.isEmpty(user.getMobile())){
            map.put("needMobile","1");
        }else{
            map.put("needMobile","0");
        }
        return success(map);
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @GetMapping("/sendSmsQx")
    @TenantIgnore
    public CommonResult sendSmsQx(@RequestParam("phone") String phone) {
        String msgCode = generateVerificationCode();
        redisCache2.setCacheObject(phone+"-registerCode",msgCode,300, TimeUnit.SECONDS);
        SendSmsUtil.sendMsg(msgCode,phone,"1400852709","机动车管家小程序","1917285");
        return ok();
    }

    /**
     * 汽修小程序更新用户手机号方法
     *
     * @param registerVO 登录信息
     * @return 结果
     */
    @PostMapping("/updateUserQx")
    public CommonResult registerQx(@RequestBody RegisterVO registerVO){
        if(org.apache.commons.lang3.StringUtils.isEmpty(registerVO.getPhone())){
            return error(500,"手机号不能为空");
        }
        if(org.apache.commons.lang3.StringUtils.isEmpty(registerVO.getCode())){
            return error(500,"验证码不能为空");
        }
        Object registerCode = redisCache2.getCacheObject(registerVO.getPhone() + "-registerCode");
        if(null==registerCode || !registerCode.equals(registerVO.getCode())){
            return error(500,"验证码错误");
        }
        redisCache2.deleteObject(registerVO.getPhone() + "-registerCode");


        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        userSaveReqVO.setId(loginUser.getId());
        userSaveReqVO.setMobile(registerVO.getPhone());
        userService.updateUser(userSaveReqVO);
        return success("成功");
    }


    /**
     * 司机登录方法
     *
     * @param loginBody 司机登录方法
     * @return 结果
     */
    @PostMapping("/driverLogin")
    @TenantIgnore
    public CommonResult driverLogin(@RequestBody LoginBody loginBody) throws Exception {
        // 生成令牌
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());
        AuthLoginRespVO login = loginService.login(authLoginReqVO);
        return success(login);
    }
    /**
     * 登录获取验证码
     *
     * @return 结果
     */
    @PostMapping("/loginSmsCode")
    public CommonResult loginSmsCode(String phone) {
        return rescueSysLoginService.loginSmsCode(phone);
    }
    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/loginJx")
    public CommonResult loginJx(@RequestBody LoginBody loginBody) throws Exception {
        // 生成令牌
        AuthLoginReqVO authLoginReqVO = new AuthLoginReqVO();
        authLoginReqVO.setUsername(loginBody.getUsername());
        authLoginReqVO.setPassword(loginBody.getPassword());
        AuthLoginRespVO login = loginService.login(authLoginReqVO);
        return success(login);
    }
//    @PostMapping("/loginSmsCodeJx")
//    public AjaxResult loginSmsCodeJx(String phone) {
//        return loginService.loginSmsCodeJx(phone);
//    }
    /**
     * 忘记密码获取验证码
     *
     * @return 结果
     */
    @PostMapping("/pwdSmsCode")
    public CommonResult pwdSmsCode(String phone) {
        return rescueSysLoginService.pwdSmsCode(phone);
    }
//    /**
//     * 更新密码
//     *
//     * @return 结果
//     */
//    @PostMapping("/updatePwd")
//    public CommonResult<Object> updatePwd(String phone, String msgCode, String password) {
//        if (!redisCache2.hasKey(phone+"-pwdCode")||!redisCache2.getCacheObject(phone+"-pwdCode").equals(msgCode)){
//            return error(500, "验证码错误");
//        }
//        AdminUserRespDTO sysUser = userService.getUserByMobile(phone);
//        if (userService.resetPassword(sysUser.getId(), SecurityFrameworkUtils.encryptPassword(password)); > 0)
//        {
//            // 更新缓存用户密码
//            sysUser.setPassword(SecurityUtils.encryptPassword(password));
//            userService.updateUser(sysUser);
//            return success();
//        }
//        return error("修改密码异常，请联系管理员");
//    }




    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public CommonResult getInfo() {
        HashMap<String, Object> map = new HashMap<>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        map.put("user", user);
        // 角色集合
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(loginUser.getId());
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<RoleReqDTO> role = roleList.stream().filter(item -> roleIdsByUserId.contains(item.getId())).collect(Collectors.toList());
        map.put("role", role);
        // 权限集合
        List<MenuDO> menuList = menuService.getMenuList();
//        Set<String> permissions = permissionService.getMenuPermission(user);
//        ajax.put("permissions", permissions);
        return success(map);
    }

//
//    @Resource
//    private DriveSchoolCoachMapper driveSchoolCoachMapper;

//    @Resource
//    private SysUserMapper sysUserMapper;

//    /**
//     * 获取
//     *
//     * @return 用户信息
//     */
//    @GetMapping("getJxInfo")
//    public CommonResult getJxInfo()
//    {
//        LoginUser user = SecurityFrameworkUtils.getLoginUser();
//        // 角色集合
//        Set<String> roles = permissionService.getRolePermission(user);
//        //获取驾校的
//        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
//        Long userId = loginUser.getId();
//        SysUser sysUser = sysUserMapper.selectUserById(userId);
//        String phonenumber = sysUser.getPhonenumber();
//        DriveSchoolCoach driveSchoolCoach = driveSchoolCoachMapper.selectByPhonenumber(phonenumber);
//
//        if (ObjectUtils.isNotEmpty(driveSchoolCoach)){
//            user.setAvatar(driveSchoolCoach.getImage());
//        }
//        DriveSchoolInfo driveSchoolInfo = driveSchoolInfoService.getSchoolInfoByDeptId();
//
//        AjaxResult ajax = success();
//        ajax.put("user", user);
//        ajax.put("roles", roles);
//        ajax.put("schoolInfo", driveSchoolInfo);
//        return ajax;
//    }
    /**
     * 获取App用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getAppInfo")
    @TenantIgnore
    public CommonResult getAppInfo()
    {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(roleIdsByUserId);
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("role", roleList);
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        if (StringUtils.isEmpty(shopConfig.getOpenRz())||shopConfig.getOpenRz().equals("0")){
            ajax.put("openRz", "0");
        }else {
            ajax.put("openRz", "0");
        }
        return CommonResult.success(ajax);
    }

    /**
     * 获取App用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getJcAppInfo")
    @TenantIgnore
    public CommonResult getJcAppInfo()
    {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        List<RoleDO> roleList = roleService.getRoleList(roleIdsByUserId);
        // 角色集合
        UserSaveReqVO userSaveReqVO = new UserSaveReqVO();
        UserBalance userBalance = balanceService.selectShopUserBalanceByUserId(loginUser.getId());
        if (ObjectUtil.isNotEmpty(userBalance)) {
            userSaveReqVO.setBalance(userBalance.getBalance());
        } else {
            //新增用户积分表信息
            userBalance=new UserBalance();
            userBalance.setUserId(loginUser.getId());
            userBalance.setAllBalance(0L);
            userBalance.setBalance(0L);
            userBalance.setFrozenBalance(0L);
            balanceService.insertShopUserBalance(userBalance);
            userSaveReqVO.setBalance(0L);
        }
        userService.updateUser(userSaveReqVO);
        Map<String,Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("role", roleList);
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        if (StringUtils.isEmpty(shopConfig.getOpenRz())||shopConfig.getOpenRz().equals("0")){
            ajax.put("openRz", "0");
        }else {
        ajax.put("openRz", "0");
        }
        return CommonResult.success(ajax);
    }



    /**
     * 获取App用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getJcgfInfo")
    public CommonResult getJcgfInfo() throws Exception {
        Map<String, Object> map = new HashMap<>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        // 角色集合
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        List<RoleReqDTO> role = roleList.stream().filter(item -> roleIdsByUserId.contains(item.getId())).collect(Collectors.toList());
        map.put("user", user);
        map.put("role", role);
        if (CollectionUtil.isNotEmpty(role)){
            AtomicBoolean flag = new AtomicBoolean(false);
            role.forEach(it->{
                if (it.getCode().equals("jcgf")){
                    flag.set(true);
                }
            });
            if (!flag.get()){
                throw exception(CommonErrorCodeConstants.MISTAKEN_IDENTITY);
            }
        }else {
            throw exception(CommonErrorCodeConstants.MISTAKEN_IDENTITY);
        }

        return success(map);
    }
    //获取交警的信息
    @GetMapping("/getJjInfo")
    public CommonResult getJjInfo() throws Exception {
        Map<String, Object> map = new HashMap<>();
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        // 角色集合
        List<RoleReqDTO> roleList = roleApi.getRoleList();
        List<Long> roleIdsByUserId = permissionApi.getRoleIdsByUserId(user.getId());
        List<RoleReqDTO> role = roleList.stream().filter(item -> roleIdsByUserId.contains(item.getId())).collect(Collectors.toList());
        map.put("user", user);
        map.put("role", role);
        if (CollectionUtil.isNotEmpty(role)){
            AtomicBoolean flag = new AtomicBoolean(false);
            role.forEach(it->{
                if (it.getCode().equals("jjdd")){
                    flag.set(true);
                }
            });
            if (!flag.get()){
                throw exception(CommonErrorCodeConstants.MISTAKEN_IDENTITY);
            }
        }else {
            throw exception(CommonErrorCodeConstants.MISTAKEN_IDENTITY);
        }

        return success(map);
    }
//    /**
//     * 获取App用户信息
//     *
//     * @return 用户信息
//     */
//    @GetMapping("/getJcPartnerInfo")
//    public AjaxResult getJcPartnerInfo()
//    {
//        LambdaQueryWrapper<ShopMallPartners> queryWrapper =new LambdaQueryWrapper<>();
//        SysUser user = SecurityUtils.getLoginUser().getUser();
//        queryWrapper.eq(ShopMallPartners::getUserId,user.getUserId()).eq(ShopMallPartners::getType,"jc").eq(ShopMallPartners::getIsBanned,"0");
//        ShopMallPartners partner = partnersService.getOne(queryWrapper);
//        if (ObjectUtil.isEmpty(partner)){
//            return error("信息有误");
//        }
//        SysUser sysUser = userService.selectUserById(user.getUserId());
//        AjaxResult ajax = success();
//        ajax.put("user", sysUser);
//        return ajax;
//    }
//
    /**
     * 获取救援司机用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getRescueDriverInfo")
    public CommonResult getRescueDriverInfo()
    {
        LambdaQueryWrapper<DriverInfo> queryWrapper =new LambdaQueryWrapper<>();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        queryWrapper.eq(DriverInfo::getUserId, userId);
        DriverInfo driverInfo = driverInfoService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(driverInfo)){
            return error(500, "信息有误");
        }
        AdminUserDO user = userService.getUser(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("driverInfo", driverInfo);
        return success(map);
    }


    /**
     * 获取检测工用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getJcWorkerInfo")
    public CommonResult getJcWorkerInfo()
    {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Map<String, Object> map = new HashMap<>();
        map.put("partnerId", user.getTenantId());
        map.put("user", user);
        return CommonResult.success(map);
    }


    @PostMapping("/wxLogin")
    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.getJxAppId() + "&secret=" + wxConfig.getJxAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        System.out.println(url);
        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 = decrypt(sessionKey, encryptedIv, encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return error(500, "微信登录失败！");
        }

        if (StringUtils.hasText(decryptResult)) {
            //如果解析成功,获取token
            AuthLoginRespVO loginVO = loginService.wxLogin(decryptResult,openId,wxLoginBody.getInviteId());
            Map<String, Object> map = new HashMap<>();
            map.put("token", loginVO.getAccessToken());
            return success(map);
        } else {
            return error(500, "微信登录失败！");
        }
    }

    @PostMapping("/wxLoginJc")
    public CommonResult wxLoginJc(@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.getJcAppId() + "&secret=" + wxConfig.getJcAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        System.out.println(url);
        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");

        System.out.println(sessionKey);
        System.out.println(openId);
        //解密
        String decryptResult = "";
        try {
            //如果没有绑定微信开放平台，解析结果是没有unionid的。
            decryptResult = decrypt(sessionKey, encryptedIv, encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.error(500,"微信登录失败！");
        }

        if (StringUtils.hasText(decryptResult)) {
            // TODO 待完成
//            //如果解析成功,获取token
            AuthLoginRespVO authLoginRespVO = loginService.wxLoginJc(decryptResult, openId, wxLoginBody.getInviteId());
            return success(authLoginRespVO);
        } else {
            return error(500, "微信登录失败！");
        }
    }
//
    @PostMapping("/wxLoginRescue")
    public CommonResult wxLoginRescue(@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.getAppId() + "&secret=" + wxConfig.getAppSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        System.out.println(url);
        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");

        System.out.println(sessionKey);
        System.out.println(openId);
        //解密
        String decryptResult = "";
        try {
            //如果没有绑定微信开放平台，解析结果是没有unionid的。
            decryptResult = decrypt(sessionKey, encryptedIv, encryptedData);
        } catch (Exception e) {
            e.printStackTrace();
            return error(500, "微信登录失败！");
        }

        if (StringUtils.hasText(decryptResult)) {
            // TODO 待完成
//            //如果解析成功,获取token
            AuthLoginRespVO authLoginRespVO = loginService.wxLoginRescue(decryptResult, openId, wxLoginBody.getInviteId());
            return success(authLoginRespVO);
        } else {
            return error(500, "微信登录失败！");
        }
    }
//
    /**
     * AES解密
     */
    private String decrypt(String sessionKey,String encryptedIv,String encryptedData) throws Exception{
        // 转化为字节数组
        byte[] key = Base64.decode(sessionKey);
        byte[] iv = Base64.decode(encryptedIv);
        byte[] encData = Base64.decode(encryptedData);
        // 如果密钥不足16位，那么就补足
        int base =16;
        if (key.length % base !=0) {
            int groups = key.length / base +(key.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp,(byte) 0);
            System.arraycopy(key,0,temp,0,key.length);
            key = temp;
        }
        // 如果初始向量不足16位，也补足
        if (iv.length % base !=0) {
            int groups = iv.length / base +(iv.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp,(byte) 0);
            System.arraycopy(iv,0,temp,0,iv.length);
            iv = temp;
        }

        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
        String resultStr = null;

        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec keySpec = new SecretKeySpec(key,"AES");
            cipher.init(Cipher.DECRYPT_MODE,keySpec,ivSpec);
            resultStr = new String(cipher.doFinal(encData),"UTF-8");
        } catch (Exception e){
//            logger.info("解析错误");
            e.printStackTrace();
        }

        // 解析加密后的字符串
        return resultStr;
    }

    /**
     * 同步数据
     * @author 小李
     * @date 14:51 2024/8/24
     * @param
     **/
    @GetMapping("/sync")
    @Operation(summary = "同步数据")
    public CommonResult syncData(){
        driverInfoService.syncData();
        return CommonResult.ok();
    }


    @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);
    }

}
