package com.ytpm.question.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.app.enums.AppTypeEnums;
import com.ytpm.app.enums.LoginType;
import com.ytpm.app.model.YtDyzLoginRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.LoginParam;
import com.ytpm.app.param.WxLoginParam;
import com.ytpm.app.view.WxDefaultConfig;
import com.ytpm.app.view.WxLoginResult;
import com.ytpm.app.view.WxUserInfo;
import com.ytpm.constant.StrConstant;
import com.ytpm.feign.RiskFeign;
import com.ytpm.general.Result;
import com.ytpm.handle.AbstractLoginService;
import com.ytpm.handle.CommonException;
import com.ytpm.question.dao.AppUserMapper;
import com.ytpm.question.dao.LoginRecordMapper;
import com.ytpm.question.dao.QuestionMapper;
import com.ytpm.question.redis.RedisService;
import com.ytpm.question.service.AppUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 微信登陆 回调实现类
 *
 * @author lih
 * @date 2025/9/4
 */
@Slf4j
@Component
public class WxLoginServiceImpl extends AbstractLoginService {
    private final static String GRANT_TYPE = "authorization_code";
    @Resource
    private AppUserMapper appUserMapper;
    @Resource
    private LoginRecordMapper loginRecordMapper;
    @Resource
    private RiskFeign riskFeign;
    @Resource
    private AppUserService appUserService;
    @Resource
    private RedisService redisService;
    @Resource
    private QuestionMapper questionMapper;

    @Override
    protected WxDefaultConfig getLoginConfig(Integer appType) {
        return appUserMapper.getDefaultConfig(appType);
    }

    @Override
    protected LoginType getLoginType() {
        return LoginType.WX;
    }

    @Override
    protected void updateUserStatus(YtDyzUser ytDyzUser, UserStatusEnum statusEnum, String reason) {

    }

    @Override
    protected void validateParams(LoginParam loginParam, HttpServletRequest request) {

    }

    @Override
    protected Map<String, Object> setThirdPartyLoginInfo(LoginParam loginParam, WxDefaultConfig defaultConfig, HttpServletRequest request) {
        WxLoginParam param = (WxLoginParam) loginParam;
        WxLoginResult loginResult = getWechatLoginInfo(param.getWxCode(), param.getAppType(), defaultConfig.getAppId(), defaultConfig.getSecret());
        if (Objects.isNull(loginResult) || StrUtil.isBlank(loginResult.getOpenid())) {
            throw new CommonException("微信登录失败，请刷新授权码！");
        }
        WxUserInfo wxUserInfo = getWechatUserInfo(loginResult.getAccess_token(), loginResult.getOpenid());
        if (Objects.isNull(wxUserInfo)) {
            throw new CommonException("微信用户登录失败");
        }
        Map<String, Object> stringObjectMap = super.setThirdPartyLoginInfo(loginParam, defaultConfig, request);
        stringObjectMap.put("loginResult", loginResult);
        stringObjectMap.put("wxUserInfo", wxUserInfo);
        return stringObjectMap;
    }

    /**
     * 微信登录
     */
    private WxLoginResult getWechatLoginInfo(String wxCode, int appType, String appId, String secret) {

        String wxLoginUrl;
        if (AppTypeEnums.QNJZ.getCode() == appType) {
            wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + appId + "&secret=" + secret + "&code=" + wxCode + "&grant_type=" + GRANT_TYPE;
        } else {
            wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId
                    + "&secret=" + secret + "&code=" + wxCode + "&grant_type=" + GRANT_TYPE;
        }
        //拿到授权码 请求微信登录返回access_token
        String result = HttpUtil.get(wxLoginUrl);
        WxLoginResult loginResult = JSON.parseObject(result, WxLoginResult.class);
        log.error("授权码获取的登录结果:{}", loginResult);
        return loginResult;
    }

    /**
     * 获取微信用户信息
     */
    private WxUserInfo getWechatUserInfo(String accessToken, String openid) {
        // 根据token和openid 获取用户信息
        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
        String curUser = HttpUtil.get(userInfoUrl);
        WxUserInfo wxUserInfo = JSON.parseObject(curUser, WxUserInfo.class);
        log.error("获取的用户信息:{}", wxUserInfo);
        return wxUserInfo;
    }


    @Override
    protected YtDyzUser queryUserByDeviceAndDitch(String deviceId, Long ditchId) {
        return null;
    }


    @Override
    protected List<YtDyzUser> queryDyzUserByParam(LoginParam loginParam, Map<String, Object> thirdPartyLoginInfo) {
        WxLoginParam param = (WxLoginParam) loginParam;
        WxLoginResult loginResult = (WxLoginResult) thirdPartyLoginInfo.get("loginResult");
        WxUserInfo wxUserInfo = (WxUserInfo) thirdPartyLoginInfo.get("wxUserInfo");
        YtDyzUser ytDyzUser = appUserService.crudForNewTrans(param, wxUserInfo, loginResult);
        return ytDyzUser == null ? Collections.emptyList() : Collections.singletonList(ytDyzUser);
    }

    @Override
    protected YtDyzUser registryUser(LoginParam param, YtDyzUser old, Map<String, Object> paramMap) {
        WxLoginResult loginResult = (WxLoginResult) paramMap.get("loginResult");
        WxUserInfo wxUserInfo = (WxUserInfo) paramMap.get("wxUserInfo");
        old.setUserId(redisService.getAppUserId());
        old.setPhone(param.getPhone());
        old.setDeviceId(param.getDeviceId());
        old.setNickName(wxUserInfo.getNickname());
        old.setLastLoginTime(new Date());
        old.setRegistryTime(new Date());
        old.setLastLoginIp(param.getLoginIp());
        old.setLoginDays(1);
        old.setPower(0);
        old.setTotalVideo(0);
        old.setTotalIncome(BigDecimal.ZERO);
        old.setRedPacketAmount(BigDecimal.ZERO);
        old.setRedPacketBalance(BigDecimal.ZERO);
        old.setPointsBalance(BigDecimal.ZERO);
        old.setPointsTotal(BigDecimal.ZERO);
        old.setWithdrawTotal(BigDecimal.ZERO);
        old.setDitchId(param.getDitchId());
        old.setSignDays(0);
        old.setAppId(param.getAppId());
        old.setUserStatus(UserStatusEnum.NORMAL.getCode());
        old.setWxOpenId(loginResult.getOpenid());
        old.setHeadImg(wxUserInfo.getHeadimgurl());
        old.setPhoneJson(param.getPhoneJson());
        //根据设备ID获取平台ID 获取不到再生成平台ID
        String platformId = appUserMapper.getByDeviceId(param.getDeviceId(), wxUserInfo.getOpenid());
        old.setPlatformId(StrUtil.isBlank(platformId) ?
                (StrConstant.PLATFORM_ID_PREFIX + IdUtil.getSnowflakeNextIdStr()) : platformId);
        appUserMapper.addOne(old);
        return null;
    }

    @Override
    protected void deadWithUserCrud(LoginParam param, YtDyzUser old, Map<String, Object> paramMap) {
        WxLoginResult loginResult = (WxLoginResult) paramMap.get("loginResult");
        WxUserInfo wxUserInfo = (WxUserInfo) paramMap.get("wxUserInfo");

        YtDyzUser newUser = new YtDyzUser();
        newUser.setUserId(old.getUserId());
        newUser.setNickName(wxUserInfo.getNickname());
        newUser.setHeadImg(wxUserInfo.getHeadimgurl());
        newUser.setLastLoginTime(new Date());
        newUser.setLastLoginIp(param.getLoginIp());
        newUser.setPhone(param.getPhone());
        newUser.setDeviceId(param.getDeviceId());
        YtDyzLoginRecord wxLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 0);
        YtDyzLoginRecord visitorLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 1);
        if (wxLoginRecord == null && visitorLoginRecord == null
                || wxLoginRecord != null && wxLoginRecord.getLoginTime() != null
                && DateUtil.compare(wxLoginRecord.getLoginTime(), newUser.getLastLoginTime(), "yyyy-MM-dd") < 0) {
            newUser.setLoginDays(old.getLoginDays() + 1);
        }
        newUser.setPhoneJson(param.getPhoneJson());
        appUserMapper.updateUser(newUser);
    }

    @Override
    protected void saveLoginRecord(YtDyzLoginRecord loginRecord) {
        loginRecordMapper.insertOne(loginRecord);
    }

    @Override
    protected Result<?> remoteCheckLoginRisk(YtDyzUser ytDyzUser) {
        ytDyzUser.setRiskCode("313");
        return riskFeign.checkRisk(ytDyzUser);
    }

    @Override
    protected Result<?> remoteCheckRegRisk(YtDyzUser user) {
        return null;
    }

    @Override
    protected void setExtInfo(YtDyzUser old, Map<String, Object> paramMap) {
        WxUserInfo wxUserInfo = (WxUserInfo) paramMap.get("wxUserInfo");
        old.setHeadImg(wxUserInfo.getHeadimgurl());
        old.setLastQuestionId(questionMapper.getLastQuestionId(old.getUserId()));
        old.setTodayAnswerCount(questionMapper.getAnswerCount(old.getUserId(), 1));
        old.setHistoryAnswerCount(questionMapper.getAnswerCount(old.getUserId(), 2));
        old.setAnswerRecordList(questionMapper.getAnswerRecords(old.getUserId()));
        old.setLoginRecordList(loginRecordMapper.getLoginRecords(old.getUserId()));
    }


}
