package com.backendsys.modules.sdk.wechat.miniprogram.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.backendsys.exception.CustException;
import com.backendsys.modules.app.dao.AppUserDao;
import com.backendsys.modules.app.entity.AppUser;
import com.backendsys.modules.common.config.redis.utils.RedisUtil;
import com.backendsys.modules.common.config.security.entity.SecurityAppUserInfo;
import com.backendsys.modules.common.config.security.utils.HttpRequestUtil;
import com.backendsys.modules.common.config.security.utils.JwtUtil;
import com.backendsys.modules.common.config.security.utils.TokenUtil;
import com.backendsys.modules.sdk.wechat.miniprogram.entity.WechatAuth;
import com.backendsys.modules.sdk.wechat.miniprogram.service.WechatAuthService;
import com.backendsys.modules.sdk.wechat.miniprogram.utils.WechatUtil;
import com.backendsys.modules.system.entity.TokenCatch;
import com.backendsys.modules.system.service.SysCommonService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class WechatAuthServiceImpl implements WechatAuthService {

    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private WechatUtil wechatUtil;
    @Autowired
    private HttpRequestUtil httpRequestUtil;

    @Value("${REDIS_LOGIN_TOKEN_PREFIX}")
    private String REDIS_LOGIN_TOKEN_PREFIX;

    @Autowired
    private SysCommonService sysCommonService;
    @Autowired
    private AppUserDao appUserDao;


    // [方法] 登录成功
    private AppUser loginSuccess(AppUser appUser) {

        // 删除旧的登录缓存
        tokenUtil.deleteRedisLoginToken(appUser.getLast_login_uuid());

        // 判断用户是否启用
        Integer status = appUser.getStatus();
        if (status != null && status.equals(-1)) throw new CustException("该用户已被禁用，请与客服联系");

        // 判断用户是否已删除
        Integer del_flag = appUser.getDel_flag();
        if (del_flag != null && del_flag.equals(1)) throw new CustException("当前用户不可用，请与客服联系");

        // [系统配置] 微信用户默认登录过期时间(小时)
        Integer APP_USER_LOGIN_DURATION_DEFAULT = Convert.toInt(sysCommonService.getCommonByTag("APP_USER_LOGIN_DURATION_DEFAULT"));
        // 将小时转换为毫秒
        Long DEFAULT_MILLISECONDS = APP_USER_LOGIN_DURATION_DEFAULT * DateUnit.HOUR.getMillis();
        Integer token_duration_hours = Convert.toInt(DEFAULT_MILLISECONDS / 3600000L);

        Date token_expiration = new Date((new Date()).getTime() + DEFAULT_MILLISECONDS);
        appUser.setToken_expiration(DateUtil.format(token_expiration, "yyyy-MM-dd HH:mm:ss"));
        appUser.setRole("APP_USER");

        // 生成 Token
        SecurityAppUserInfo securityUserInfo = JSONUtil.toBean(JSONUtil.parseObj(appUser), SecurityAppUserInfo.class);

        String token = jwtUtil.createAppJwtToken(securityUserInfo);
        String token_redis_key = REDIS_LOGIN_TOKEN_PREFIX + appUser.getLast_login_uuid();
        appUser.setToken(token);

        // [Redis] 将 Token 存入缓存
        TokenCatch tokenCatch = new TokenCatch(token, null);
        redisUtil.setCacheObject(token_redis_key, JSONUtil.toJsonStr(tokenCatch), token_duration_hours, TimeUnit.HOURS);

        return appUser;
    }

    /**
     * 微信小程序用户登录
     */
    @Override
    public AppUser loginWithWechatMiniprogram(WechatAuth wechatAuth) {

        String code = wechatAuth.getCode();
        JSONObject response = wechatUtil.getCode2Session(code);
        // [失败] 返回值：{"errcode":40164,"errmsg":"invalid ip 116.31.165.86 ipv6 ::ffff:116.31.165.86, not in whitelist, rid: 67d15951-5b3f2778-79d6f047"}
        // [成功] 返回值：{"session_key":"uQAcry2PC1Lx/Krp+6rr0g==","openid":"oSB9r7T7kN1bC7PabJ7RmTUiaJmo"}

        // - errcode: 错误码，请求失败时返回
        if (!response.containsKey("errcode")) {

            String openid = response.getStr("openid");
            String session_key = response.getStr("session_key");

            String uuid = Convert.toStr(UUID.randomUUID());
            String last_login_ip = httpRequestUtil.getIpAddr();
            String last_login_time = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");

            // [Get] 判断用户是否存在 (openid)
            AppUser appUser = appUserDao.selectOne(new LambdaQueryWrapper<AppUser>().eq(AppUser::getWechat_open_id, openid));
            if (appUser == null) {
                // [Insert] 不存在，则创建
                appUser = new AppUser();
                appUser.setWechat_open_id(openid);
                appUser.setNickname("微信用户" + RandomUtil.randomStringUpper(4));
                //
                appUser.setLast_login_uuid(uuid);
                appUser.setLast_login_ip(last_login_ip);
                appUser.setLast_login_time(last_login_time);
                appUserDao.insert(appUser);
            } else {
                // [Update] 更新时间
                appUser.setLast_login_uuid(uuid);
                appUser.setLast_login_ip(last_login_ip);
                appUser.setLast_login_time(last_login_time);
                appUserDao.updateById(appUser);
            }
            appUser.setUser_id(appUser.getId());
            appUser.setSession_key(session_key);

            // 登录成功
            return loginSuccess(appUser);
        } else {
            throw new CustException(response.getStr("errmsg"));
        }

    }

}
