package com.ytpm.lemonios.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.ytpm.agent.enums.UserStatusEnum;
import com.ytpm.agent.model.YtDitch;
import com.ytpm.app.model.YtAppDefaultConfig;
import com.ytpm.app.model.YtDyzAdRecord;
import com.ytpm.app.model.YtDyzAnswerRecord;
import com.ytpm.app.model.YtDyzLoginRecord;
import com.ytpm.app.model.YtDyzUser;
import com.ytpm.app.param.IosLoginParam;
import com.ytpm.app.param.WxLoginParam;
import com.ytpm.app.view.IosUserInfo;
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.general.RepMessage;
import com.ytpm.general.Result;
import com.ytpm.handle.CustomerException;
import com.ytpm.lemonios.dao.AppUserMapper;
import com.ytpm.lemonios.dao.DitchMapper;
import com.ytpm.lemonios.dao.LoginRecordMapper;
import com.ytpm.lemonios.dao.QuestionMapper;
import com.ytpm.lemonios.redis.RedisService;
import com.ytpm.lemonios.service.AppUserService;
import com.ytpm.risk.view.RiskConfigView;
import com.ytpm.risk.view.RiskTemplateView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RefreshScope
public class AppUserServiceImpl implements AppUserService {

    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private LoginRecordMapper loginRecordMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private RedisService redisService;
    @Value("${risk.config.banned.tips}")
    private String tips;
    @Autowired
    private DitchMapper ditchMapper;

    /**
     * openid查询用户信息
     */
    @Override
    public YtDyzUser selectByOpenid(String openid,Long ditchId) {
        return appUserMapper.getYtAppUser(openid,ditchId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public YtDyzUser crudForNewTrans(WxLoginParam param, WxUserInfo wxUserInfo, WxLoginResult loginResult) {
        //处理用户注册或登录更新信息
        YtDyzUser old = appUserMapper.getYtAppUser(loginResult.getOpenid(), param.getDitchId());
        if(Objects.isNull(old)) {
            old = new YtDyzUser();
            registryUser(param,wxUserInfo,loginResult, old);
        }else{
            deadWithUserCrud(old,wxUserInfo,param);
        }
        //设置最后一次答题问题ID、今日答题数、历史答题数
        setExtInfo(old,wxUserInfo.getHeadimgurl());
        // 添加用户登录记录
        addLoginRecord(param,old.getUserId());
        return old;
    }

    @Override
    public YtDyzUser crudForNewTransIos(IosLoginParam param, IosUserInfo userInfo) {
        YtDyzUser old = appUserMapper.getYtAppUserForIos(param.getIosId(), param.getDitchId());
        if(Objects.isNull(old)) {
            old = new YtDyzUser();
            registryUserForIos(param,userInfo, old);
        }else{
            deadWithUserCrudForIos(old,userInfo,param);
        }
        //设置最后一次答题问题ID、今日答题数、历史答题数
        setExtInfoForIos(old, userInfo.getHeadimgurl());
        // 添加用户登录记录
        addLoginRecordForIos(param,old.getUserId());
        return old;
    }

    @Override
    public Result<?> addDefaultConfig(YtDitch param) {
        ditchMapper.insertOne(param);
        WxDefaultConfig lastOne = appUserMapper.getLastOne(param.getAppId());
        YtAppDefaultConfig appDefaultConfig = new YtAppDefaultConfig();
        appDefaultConfig.setConfigName(param.getDitchName());
        appDefaultConfig.setDitchId(param.getDitchId().toString());
        appDefaultConfig.setOpenId("");
        appDefaultConfig.setSecret(lastOne.getSecret());
        appDefaultConfig.setAppKey("");
        appDefaultConfig.setAppType(lastOne.getAppType());
        appDefaultConfig.setAppId(lastOne.getAppId());
        appDefaultConfig.setCanUseRoot(lastOne.getCanUseRoot());
        appDefaultConfig.setCanUseAdb(lastOne.getCanUseAdb());
        appDefaultConfig.setCanAccumulation(lastOne.getCanAccumulation());
        appDefaultConfig.setCanSimulator(lastOne.getCanSimulator());
        appDefaultConfig.setPowerWaitTime(lastOne.getPowerWaitTime());
        appDefaultConfig.setInterstitialIntervalTime(lastOne.getInterstitialIntervalTime());
        appUserMapper.saveAppConfig(appDefaultConfig);
        return Result.resultOk(RepMessage.ADD_SUCCESS);
    }

    /**
     * 设置扩展信息
     */
    private void setExtInfo(YtDyzUser old, String headimgurl) {
        old.setHeadImg(headimgurl);
            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()));
    }

    /**
     * 设置扩展信息
     */
    private void setExtInfoForIos(YtDyzUser old, String headimgurl) {
        old.setHeadImg(headimgurl);
        old.setLastQuestionId(questionMapper.getLastQuestionId(old.getUserId()));
        old.setTodayAnswerCount(questionMapper.getAnswerCount(old.getUserId(),1));
        old.setHistoryAnswerCount(questionMapper.getAnswerCount(old.getUserId(),2));
        List<YtDyzAnswerRecord> recordList = questionMapper.getAnswerRecords(old.getUserId());
        List<String> viewList  = new ArrayList<>();
        int count = recordList.size();
        for (YtDyzAnswerRecord ytDyzAnswerRecord : recordList) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String timeStr = count + ":" + sdf.format(ytDyzAnswerRecord.getAnswerTime());
            count--;
            viewList.add(timeStr);
        }
        old.setAnswerRecordTimeList(viewList);
        old.setAnswerRecordList(questionMapper.getAnswerRecords(old.getUserId()));
        old.setLoginRecordList(loginRecordMapper.getLoginRecords(old.getUserId()));
    }

    /**
     * 增加用户登录记录
     */
    private void addLoginRecord(WxLoginParam param,String userId) {
        YtDyzLoginRecord loginRecord = new YtDyzLoginRecord();
        loginRecord.setRecordId(IdUtil.fastSimpleUUID());
        loginRecord.setUserId(userId);
        loginRecord.setLoginTime(new Date());
        loginRecord.setDeviceBrand(param.getBrand());
        loginRecord.setDeviceModel(param.getModel());
        loginRecord.setLoginIp(param.getLoginIp());
        loginRecord.setOperator(param.getIpOperator());
        loginRecord.setIpAddr(param.getIpLocation());
        loginRecord.setPhoneJson(param.getPhoneJson());
        loginRecordMapper.insertOne(loginRecord);
    }

    /**
     * 增加用户登录记录
     */
    private void addLoginRecordForIos(IosLoginParam param,String userId) {
        YtDyzLoginRecord loginRecord = new YtDyzLoginRecord();
        loginRecord.setRecordId(IdUtil.fastSimpleUUID());
        loginRecord.setUserId(userId);
        loginRecord.setLoginTime(new Date());
        loginRecord.setDeviceBrand(param.getBrand());
        loginRecord.setDeviceModel(param.getModel());
        loginRecord.setLoginIp(param.getLoginIp());
        loginRecord.setOperator(param.getIpOperator());
        loginRecord.setIpAddr(param.getIpLocation());
        loginRecord.setPhoneJson(param.getPhoneJson());
        loginRecordMapper.insertOne(loginRecord);
    }

    private String getTipsMsg(){
        String[] split = tips.split(",");
        return split[RandomUtil.randomInt(split.length)];
    }
    /**
     * 处理用户数据
     */
    private void deadWithUserCrud(YtDyzUser old, WxUserInfo wxUserInfo, WxLoginParam param) {
        //处于风控状态的用户不允许登录
        if(!old.getUserStatus().equals(UserStatusEnum.NORMAL.getCode())){
            throw new CustomerException(getTipsMsg());
        }
        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());
        newUser.setLoginDays(old.getLoginDays()+1);
        appUserMapper.updateUser(newUser);
    }

    /**
     * 处理用户数据
     */
    private void deadWithUserCrudForIos(YtDyzUser old, IosUserInfo userInfo, IosLoginParam param) {
        //处于风控状态的用户不允许登录
        if(!old.getUserStatus().equals(UserStatusEnum.NORMAL.getCode())){
            throw new CustomerException(getTipsMsg());
        }
        YtDyzUser newUser = new YtDyzUser();
        newUser.setUserId(old.getUserId());
        newUser.setNickName(userInfo.getNickname());
        newUser.setHeadImg(userInfo.getHeadimgurl());
        newUser.setLastLoginTime(new Date());
        newUser.setLastLoginIp(param.getLoginIp());
        newUser.setPhone(param.getPhone());
        newUser.setDeviceId(param.getDeviceId());
        newUser.setLoginDays(old.getLoginDays()+1);
        appUserMapper.updateUser(newUser);
    }

    /**
     * 注册用户
     */
    private void registryUser(WxLoginParam param,WxUserInfo wxUserInfo,WxLoginResult loginResult, YtDyzUser old) {
        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());
        //根据设备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);
    }

    /**
     * 注册用户
     */
    private void registryUserForIos(IosLoginParam param,IosUserInfo userInfo, YtDyzUser old) {
        old.setUserId(redisService.getAppUserId());
        old.setPhone(param.getPhone());
        old.setDeviceId(param.getDeviceId());
        old.setNickName(userInfo.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.setIosId(param.getIosId());
        old.setHeadImg(userInfo.getHeadimgurl());
        //根据设备ID获取平台ID 获取不到再生成平台ID
        String platformId = appUserMapper.getByDeviceId(param.getDeviceId(),userInfo.getOpenid());
        old.setPlatformId(StrUtil.isBlank(platformId)?
                (StrConstant.PLATFORM_ID_PREFIX + IdUtil.getSnowflakeNextIdStr()):platformId);
        appUserMapper.addOne(old);
    }
}
