package com.ruoyi.business.service.impl;

import java.util.List;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.WxMaUserService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.ruoyi.business.constants.CacheConstants;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.utils.security.Md5Utils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.AiUserinfoMapper;
import com.ruoyi.business.domain.AiUserinfo;
import com.ruoyi.business.service.IAiUserinfoService;
import com.ruoyi.common.core.text.Convert;

import javax.annotation.Resource;

/**
 * 用户信息Service业务层处理
 *
 * @author max
 * @date 2023-05-14
 */
@Slf4j
@Service
public class AiUserinfoServiceImpl implements IAiUserinfoService {
    @Autowired
    private AiUserinfoMapper aiUserinfoMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Resource
    private WxMaService maService;


    @Value("${wx.appid}")
    private String appid;

    @Value("${wx.baseUrl}")
    private String baseUrl;

    @Value("${wx.secret}")
    private String secret;

    /**
     * 查询用户信息
     *
     * @param id 用户信息主键
     * @return 用户信息
     */
    @Override
    public AiUserinfo selectAiUserinfoById(Long id) {
        return aiUserinfoMapper.selectAiUserinfoById(id);
    }

    /**
     * 查询用户信息列表
     *
     * @param aiUserinfo 用户信息
     * @return 用户信息
     */
    @Override
    public List<AiUserinfo> selectAiUserinfoList(AiUserinfo aiUserinfo) {
        return aiUserinfoMapper.selectAiUserinfoList(aiUserinfo);
    }

    /**
     * 新增用户信息
     *
     * @param aiUserinfo 用户信息
     * @return 结果
     */
    @Override
    public int insertAiUserinfo(AiUserinfo aiUserinfo) {
        aiUserinfo.setCreateTime(DateUtils.getNowDate());
        return aiUserinfoMapper.insertAiUserinfo(aiUserinfo);
    }

    /**
     * 修改用户信息
     *
     * @param aiUserinfo 用户信息
     * @return 结果
     */
    @Override
    public int updateAiUserinfo(AiUserinfo aiUserinfo) {
        return aiUserinfoMapper.updateAiUserinfo(aiUserinfo);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的用户信息主键
     * @return 结果
     */
    @Override
    public int deleteAiUserinfoByIds(String ids) {
        return aiUserinfoMapper.deleteAiUserinfoByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除用户信息信息
     *
     * @param id 用户信息主键
     * @return 结果
     */
    @Override
    public int deleteAiUserinfoById(Long id) {
        return aiUserinfoMapper.deleteAiUserinfoById(id);
    }

    @Override
    public String handleCode(String appid, String code) {
        try {
            if (maService.switchover(appid)) {
                WxMaJscode2SessionResult sessionInfo = maService.getUserService().getSessionInfo(code);
                String key = Md5Utils.hash(sessionInfo.getOpenid());
                redisUtils.set(Md5Utils.hash(key), sessionInfo, CacheConstants.cacheSessionKeyTime);
                return key;
            }
            throw new BaseException("appid不存在");
        } catch (WxErrorException e) {
            log.error("用户code获取session失败");
            throw new BaseException("用户code获取session失败");
        }
    }


    public void getUserInfo(String sessionKey, String appid, String encryptedData, String ivStr) {
        if (maService.switchover(appid)) {
            WxMaJscode2SessionResult result = (WxMaJscode2SessionResult) redisUtils.get(Md5Utils.hash(sessionKey));
            if(result == null){
                throw new BaseException("会话凭证失效");
            }
            WxMaUserInfo userInfo = maService.getUserService().getUserInfo(result.getSessionKey(), encryptedData, ivStr);
            //TODO 注册成功
        }
    }
}
