package com.mcwl.web.controller.system;

import com.mcwl.common.annotation.Anonymous;
import com.mcwl.common.constant.CacheConstants;
import com.mcwl.common.core.domain.AjaxResult;
import com.mcwl.common.core.domain.entity.SysUser;
import com.mcwl.common.core.domain.model.LoginUser;
import com.mcwl.common.core.redis.RedisCache;
import com.mcwl.common.utils.StringUtils;
import com.mcwl.common.utils.uuid.IdUtils;
import com.mcwl.framework.web.service.SysPermissionService;
import com.mcwl.framework.web.service.TokenService;
import com.mcwl.system.domain.SysUserThirdAccount;
import com.mcwl.system.service.ISysUserService;
import com.mcwl.system.service.ISysUserThirdAccountService;
import com.mcwl.system.service.IWXService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 对接微信扫码登录
 *
 * @author DaiZibo
 * @date 2024/12/30
 * @apiNote
 */

@Slf4j
@RestController
@RequestMapping("/wx")
public class WXController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ISysUserService iSysUserService;

    @Resource
    private ISysUserThirdAccountService iSysUserThirdAccountService;

    @Resource
    private IWXService iwxService;

    @Resource
    private TokenService tokenService;

    @Resource
    private SysPermissionService permissionService;


    /**
     * 扫码登录用uuid生成
     */
    @Anonymous
    @GetMapping("/uuid/get")
    public AjaxResult getUUID() throws IOException {
        AjaxResult ajax = AjaxResult.success();
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.WX_OPENID_KEY + uuid;
        redisCache.setCacheObject(verifyKey, null, 1, TimeUnit.MINUTES);
        ajax.put("uuid", uuid);
        return ajax;
    }

    /**
     * uuid绑定openid
     */
    @Anonymous
    @GetMapping("/uuid/bind/openid")
    public AjaxResult bindOpenid(@RequestParam("code") String code, @RequestParam("uuid") String uuid) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        SysUserThirdAccount user = iwxService.getOpenid(code);
        String openid = user.getOpenid();
        String wxNickName = user.getOpenName();
        String verifyKey = CacheConstants.WX_OPENID_KEY + uuid;
        long expire = redisCache.getExpire(verifyKey);
        redisCache.setCacheObject(verifyKey, openid);
        if (expire > 0) {
            redisCache.expire(verifyKey, expire, TimeUnit.SECONDS);
        }
        ajax.put("openid", openid);
        ajax.put("wxNickName", wxNickName);
        return ajax;
    }

    /**
     * uuid登录
     */
    @Anonymous
    @GetMapping("/uuid/login")
    public AjaxResult loginByOpenId(@RequestParam("uuid") String uuid) throws IOException {

        AjaxResult ajax = AjaxResult.success();
        String verifyKey = CacheConstants.WX_OPENID_KEY + uuid;
//        String openid = redisCache.getCacheObject(verifyKey);
        String openid = redisTemplate.opsForValue().get(verifyKey);
        ajax.put("status", 0);
        System.out.println("openid：{}" + openid);

        if (!StringUtils.isEmpty(openid)) {
            String openid1 = openid.substring(1, openid.length() - 1);
            redisTemplate.delete(verifyKey);
            SysUser user = iSysUserThirdAccountService.selectUserByOpenId(openid1);
            System.out.println("用户：{}" + user);
            if (user.getUserId() == null) {

                iSysUserService.addUser(openid1,CacheConstants.WE_CHAT,null);
                user = iSysUserThirdAccountService.selectUserByOpenId(openid1);
            }
            LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
            log.info("生成token的数据user:{}",user);
            // 生成token
            String token = tokenService.createToken(loginUser);
            ajax.put("token", token);
            ajax.put("status", 1);
            redisCache.deleteObject(verifyKey);
        }

        return ajax;
    }

}
