package org.jeecg.modules.oauth2_server.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.encryption.EncryptedString;
import org.jeecg.modules.oauth2_server.util.AesUtil;
import org.jeecg.modules.system.constant.SendChangeMsgConstant;
import org.jeecg.modules.system.entity.*;
import org.jeecg.modules.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author liushuai
 * @date 2022-05-27 16:07
 */
@Slf4j
@Api(tags="oauth2_other_server")
@RestController
public class SaOauth2OtherServeController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysAreaService sysAreaService;
    @Resource
    private ISysDepartService sysDepartService;
   // @Resource
   // private INationApiService nationApiService;
    @Autowired
    private ISysTenantService tenantService;

    @Autowired
    private GtChangeUserService gtChangeUserService;
    @Autowired
    private ISysUserDepartService userDepartService;

    /**
     * 调用国家隐形登录
     * @return
     */
//    @RequestMapping("/oauth2/nationLogin")
//    public Result<?> nationLogin(HttpServletResponse resp){
//        Object loginId = StpUtil.getLoginId();
//        if (loginId == null) {
//            return Result.error("获取用户信息错误");
//        }
//
//        SysUser user = sysUserService.getUserById(loginId.toString());
//        if (user == null) {
//            return Result.error("获取用户详细信息错误");
//        }
//        //通过user重定向到国家
//        try {
//            String nationAuthCodeUrl = nationApiService.getNationAuthCodeUrl(user.getUsername(),StpUtil.getTokenValue());
//            return Result.OK(nationAuthCodeUrl);
////			resp.setStatus(302);
////			resp.setHeader("location",nationAuthCodeUrl);
//        } catch (TacsException e) {
//            e.printStackTrace();
//            Result.error(e.getMessage());
//        } catch (Exception e) {
//            e.printStackTrace();
//            Result.error(e.getMessage());
//        }
//
//        return Result.OK();
//    }
//
//    /**
//     * 调用国家隐形登录
//     * @return
//     */
//    @RequestMapping("/oauth2/nationLoginOut")
//    public Result<?> nationLoginOut(){
//        Object loginId = StpUtil.getLoginId();
//        String saToken = StpUtil.getTokenValue();
//        if (loginId == null) {
//            return Result.error("获取用户信息错误");
//        }
//        //通过user重定向到国家
//        try {
//            //调用国家退出接口
//            String nationAuthCodeUrl = nationApiService.getNationLoginOutUrl(saToken);
//            //退出当前登录
//            StpUtil.kickoutByTokenValue(saToken);
//            return Result.OK(nationAuthCodeUrl);
//        } catch (TacsException e) {
//            e.printStackTrace();
//            Result.OK();
//        }
//
//        return Result.OK();
//    }

    @RequestMapping(value = "/oauth2/test2")
    public void Ts2(@RequestBody JSONObject jsonObject) {
        System.out.println(jsonObject);
    }
    @RequestMapping(value = "/oauth2/testRaw", method = RequestMethod.POST)
    @Transactional
    public Result<?> add(@RequestBody JSONObject jsonObject) {
        Result<Object> result = new Result<>();
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        log.info(username);
        log.info(password);
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        result.setResult(map);
        return result;
    }
    @GetMapping("/oauth2/testRedis")
    public  Result<?> testRedis(){
        redisUtil.set("testRedis","testRedis",60000);
        Object redis = redisUtil.get("testRedis");
        return Result.OK(redis);
    }
    @GetMapping("/oauth2/respwd")
    public  Result<?> restPwd(){
        List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>().eq("user_description", "10010"));
        for (SysUser sysUser : sysUserList) {
            sysUserService.resetPassword(sysUser);
        }
        return Result.OK("重置密码成功");
    }

    @RequestMapping(value = "/oauth2/testFrom", method = RequestMethod.POST)
    public Result<?> from(String username,String password) {
        Result<Object> result = new Result<>();
        Map<String, Object> map = new HashMap<>();
        map.put("username",username);
        map.put("password",password);
        result.setResult(map);
        return result;
    }


    @RequestMapping("/oauth2/test")
    public Object test(){
        SysUser id = sysUserService.getOne(new QueryWrapper<SysUser>().likeLeft("username", "M").last("limit 1"));
        System.out.println(id);
        return id;
    }

    @RequestMapping("/oauth2/changephone")
    public void changePhone(){
        List<SysUser> phone = sysUserService.list(new QueryWrapper<SysUser>().likeLeft("phone", "="));
        for (SysUser sysUser : phone) {
            String encrypt1 = null;
            try {
                encrypt1 = AesUtil.decrypt(sysUser.getPhone(), EncryptedString.key,EncryptedString.iv);
                sysUser.setPhone(encrypt1);
//                sysUser.setUserDescription("10086");
                sysUserService.updateById(sysUser);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @RequestMapping("/oauth2/sendUserMsg")
    public Object sendUserMsg(){
        List<SysUser> memo = sysUserService.list(new QueryWrapper<SysUser>().eq("user_description", "10086"));
        for (SysUser user : memo) {
            SysDepart dept = sysDepartService.getDeptByUserId(user.getId());
            tenantService.sendUserMsg(user, dept, SendChangeMsgConstant.UPDATE);
        }
        return "推送用户成功";
    }

    @RequestMapping("/oauth2/sendAreaMsg")
    public Object sendAreaMsg() {
        List<SysArea> sysAreas = sysAreaService.list(new QueryWrapper<SysArea>().eq("description", "10086"));
        for (SysArea sysArea : sysAreas) {
            tenantService.sendAreaMsg(sysArea, SendChangeMsgConstant.UPDATE);
        }
        return "推送区划成功";
    }
//    @RequestMapping("/oauth2/sendRolePermission")
//    public  Object sendRolePermissionMsg(){
//
//        SysChangeMsg sysChangeMsg = new SysChangeMsg();
//        sysChangeMsg.setTenantId("5");
//        sysChangeMsg.setUrl("http://59.225.206.13:8471/user-service-center/uia/messageNotice");
//        sysChangeMsg.setData(data);
//        sysChangeMsg.setOprateType("I");
//        sysChangeMsg.setType(5);
//        sysChangeMsg.setFlag(0);
//        sysChangeMsg.setDelFlag(0);
//         sysChangeMsgService.saveChangeMsg(sysChangeMsg);
//        return "推送角色菜单信息";
//    }

    @RequestMapping("/oauth2/sendUpdateDeptMsg")
    public Object sendUpdateDeptMsg(){
        List<SysDepart> memo = sysDepartService.list(new QueryWrapper<SysDepart>().eq("memo", "10086"));
        for (SysDepart sysDepart : memo) {
            tenantService.sendDeptMsg(sysDepart,SendChangeMsgConstant.UPDATE);
        }
        return "推送部门成功";
    }

    @RequestMapping("/oauth2/sendAddDeptMsg")
    public Object sendInsertDeptMsg(){
        List<SysDepart> memo = sysDepartService.list(new QueryWrapper<SysDepart>().eq("memo", "10086"));
        for (SysDepart sysDepart : memo) {
            tenantService.sendDeptMsg(sysDepart,SendChangeMsgConstant.INSERT);
        }
        return "推送新增部门成功";
    }
    @RequestMapping("/oauth2/changeDepartUser")
    public Object changeDepartUser(){
        List<GtChangeUser> list = gtChangeUserService.list();
        for (GtChangeUser gtChangeUser : list) {
            String beforeid = gtChangeUser.getBeforeid();
            SysDepart sysDepart = sysDepartService.getById(beforeid);
            sysDepart.setStatus("0");
            sysDepartService.updateById(sysDepart);
            tenantService.sendDeptMsg(sysDepart,SendChangeMsgConstant.UPDATE);
            String afterid = gtChangeUser.getAfterid();
            List<SysUserDepart> userDepartList = userDepartService.list(new QueryWrapper<SysUserDepart>().eq("dep_id", beforeid));
            for (SysUserDepart userDepart : userDepartList) {
                userDepart.setDepId(afterid);
                userDepartService.updateById(userDepart);
                SysUser user = sysUserService.getUserById(userDepart.getUserId());
                SysDepart dept = sysDepartService.getDeptByUserId(userDepart.getUserId());
                tenantService.sendUserMsg(user, dept, SendChangeMsgConstant.UPDATE);
            }
        }
        return "交换部门用户成功";
    }

    /**  割接用户重置密码
     */
    @ApiOperation(value="sys_user-割接用户重置密码", notes="sys_user-割接用户重置密码")
    @AutoLog(value = "sys_user-割接用户重置密码")
    @RequestMapping(value = "/oauth2/cutOverRestPassword", method = RequestMethod.GET)
    public Result<?> restPassword() {
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().isNull("password"));
        list.forEach(sysUser1 ->
                sysUserService.resetPassword(sysUser1)
        );
        return Result.OK("用户密码重置成功");
    }

    /**  割接用户身份证加密
     */
    @ApiOperation(value="sys_user-割接用户身份证加密", notes="sys_user-割接用户身份证加密")
    @AutoLog(value = "sys_user-割接用户身份证加密")
    @RequestMapping(value = "/oauth2/cutOverEncryptIdCard", method = RequestMethod.GET)
    public Result<?> encryptIdCard() {
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().isNotNull("id_card").isNull("id_card_check").ne("id_card","无").ne("id_card","-1").ne("id_card","1"));
        list.forEach(sysUser ->
                sysUserService.encryptIdCard(sysUser)
        );
        return Result.OK("用户身份证加密");
    }

    @ApiOperation(value="sys_user-割接用户身份证解密", notes="sys_user-割接用户身份证解密")
    @AutoLog(value = "sys_user-割接用户身份证解密")
    @RequestMapping(value = "/oauth2/cutOverDecryptIdCard", method = RequestMethod.GET)
    public Result<?> decryptIdCard() {
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().isNotNull("id_card").isNull("clear_card"));
        list.forEach(sysUser ->
                sysUserService.decryptIdCard(sysUser)
        );
        return Result.OK("用户身份证解密");
    }

    @GetMapping(value = "/oauth2/spaceRestPassword")
    public Result<?> spaceRestPassword(){
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().eq("user_description",
                "10086"));
        list.forEach(sysUser1 ->
                sysUserService.resetPassword(sysUser1)
        );
        return Result.OK("用户密码重置成功");
    }

    @RequestMapping("/oauth2/getEEEE")
    public Object oauth1Code()  {
        String encrypt = "2eAchfeCrPmB3t+IgAx85A==";
		try {
			encrypt = AesUtil.encrypt("18980737594",EncryptedString.key,EncryptedString.iv);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		System.out.println(encrypt);
        String encrypt1 = null;
        try {
            encrypt1 = AesUtil.decrypt(encrypt, EncryptedString.key,EncryptedString.iv);
        } catch (Exception e) {
            e.printStackTrace();
        }
//		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		int i = Integer.parseInt(loginUser.getId());
//		System.out.println(i);
        return encrypt1;
    }
}
