package com.kxs.user.biz.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.common.security.util.SecurityUtils;
import com.kxs.user.api.dto.kxsapp.IntegralStatDTO;
import com.kxs.user.api.emun.ShdGradingEnum;
import com.kxs.user.api.model.KxsShdScore;
import com.kxs.user.api.model.KxsUser;
import com.kxs.user.api.vo.kxsapp.shareholder.ShareholderGetMyStandardsAllVO;
import com.kxs.user.api.vo.kxsapp.shareholder.ShareholderGetMyStandardsVO;
import com.kxs.user.api.vo.kxsapp.subGetShareholderUserList.UserScoreListVO;
import com.kxs.user.biz.mapper.KxsShdScoreMapper;
import com.kxs.user.biz.mapper.KxsUserMapper;
import com.kxs.user.biz.mapper.KxsUserRealLevelMapper;
import com.kxs.user.biz.service.KxsShdScoreService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 股东大盘分红用户积分表(KxsShdScore)表服务实现类
 *
 * @author 系统
 * @since 2024-05-07 09:11:27
 */
@Service("kxsShdScoreService")
@RequiredArgsConstructor
@Slf4j
public class KxsShdScoreServiceImpl extends ServiceImpl<KxsShdScoreMapper, KxsShdScore> implements KxsShdScoreService {
    private final KxsShdScoreMapper kxsShdScoreMapper;
    private final KxsUserMapper kxsUserMapper;
    private final KxsUserRealLevelMapper kxsUserRealLevelMapper;

    @Override
    public Object getMyStandards(String month) {
        month = month.split("-")[0] + month.split("-")[1];
        Long id = SecurityUtils.getUser().getId();
        KxsUser kxsUser = kxsUserMapper.selectById(id);
        //获取个人积分
        ShareholderGetMyStandardsVO shareholderGetMyStandardsVO = kxsShdScoreMapper.getMyStandards(month, kxsUser.getUserCode());
        if (shareholderGetMyStandardsVO == null) {
            shareholderGetMyStandardsVO = new ShareholderGetMyStandardsVO();
        }
        //获取全国积分
        ShareholderGetMyStandardsAllVO allVO = kxsShdScoreMapper.getMyStandardsAll(month);
        if (allVO != null) {
            shareholderGetMyStandardsVO.setCenterScoreAll(allVO.getCenterScoreAll());
            shareholderGetMyStandardsVO.setFirstScoreAll(allVO.getFirstScoreAll());
            shareholderGetMyStandardsVO.setHighScoreAll(allVO.getHighScoreAll());
        }
        return shareholderGetMyStandardsVO;




    }

    @Override
    public Object getShareholderUserList(Page<UserScoreListVO> page, String month, Integer type) {
        month = month.split("-")[0] + month.split("-")[1];

        return kxsShdScoreMapper.getShareholderHighScoreUserList(page, month, type);
    }

    @Override
    public void integralStat(List<IntegralStatDTO> integralStatDTOS) {
        LocalDateTime now = LocalDateTime.now();
        for (IntegralStatDTO integralStatDTO : integralStatDTOS) {
            String month = String.valueOf(integralStatDTO.getTradeMonth());
            if (StrUtil.isBlank(month)){
                month = LocalDateTimeUtil.format(LocalDate.now(), DatePattern.SIMPLE_MONTH_PATTERN);
            }
            KxsUser sonKxsUser = kxsUserMapper.selectById(integralStatDTO.getUserId());
            if(sonKxsUser == null || sonKxsUser.getStatus() != 1){
                continue;
            }
            //获取上级用户
            KxsUser kxsUser = kxsUserMapper.getParenUser(integralStatDTO.getUserId());
            List<Integer> exclude = Arrays.asList(605,608,15600);
            if(kxsUser == null || exclude.contains(kxsUser.getId())){
                continue;
            }
            //查询记录
            KxsShdScore kxsShdScore = kxsShdScoreMapper.selectOne(Wrappers.<KxsShdScore>query().lambda().eq(KxsShdScore::getUserId, kxsUser.getId()).eq(KxsShdScore::getMonth, month));
            //版本号对比
            if (kxsShdScore == null || !kxsShdScore.getVersion().equals(integralStatDTO.getVersion())){
                //记录不存在则构造数据
                if (kxsShdScore == null){
                    kxsShdScore = new KxsShdScore();
                }
                kxsShdScore.setCreateTime(now);
                kxsShdScore.setDelFlag("0");
                kxsShdScore.setUserId(Long.valueOf(kxsUser.getId()));
                kxsShdScore.setUsername(kxsUser.getUsername());
                kxsShdScore.setUserCode(kxsUser.getUserCode());
                kxsShdScore.setVersion(integralStatDTO.getVersion());//版本号
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_FRIST.getTransactions()) >= 0){
                    kxsShdScore.setFirstScore(1);
                }else {
                    kxsShdScore.setFirstScore(0);
                }
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_CENTER.getTransactions()) >= 0){
                    kxsShdScore.setCenterScore(1);
                }else {
                    kxsShdScore.setCenterScore(0);
                }
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_HIGH.getTransactions()) >= 0){
                    kxsShdScore.setHighScore(1);
                }else {
                    kxsShdScore.setHighScore(0);
                }

                kxsShdScore.setMonth(month);
                if(kxsShdScore.getId() == null){
                    kxsShdScoreMapper.insert(kxsShdScore);
                }else{
                    kxsShdScoreMapper.updateById(kxsShdScore);
                }
                log.info("创客:{},给他上级:{},增加创客积分,原始数据:{}", integralStatDTO.getUserId(), kxsUser.getId(), JSON.toJSONString(kxsShdScore));
            }else {

                //存在数据则根据条件增加
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_FRIST.getTransactions()) >= 0){

                    kxsShdScore.setFirstScore(kxsShdScore.getFirstScore() + 1);
                }
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_CENTER.getTransactions()) >= 0){
                    kxsShdScore.setCenterScore(kxsShdScore.getCenterScore() + 1);
                }
                if (integralStatDTO.getTotalAmount().compareTo(ShdGradingEnum.LEVEL_HIGH.getTransactions()) >= 0){
                    kxsShdScore.setHighScore(kxsShdScore.getHighScore() + 1);
                }
                kxsShdScore.setUpdateTime(now);
                kxsShdScore.setVersion(integralStatDTO.getVersion());
                kxsShdScoreMapper.updateById(kxsShdScore);
                log.info("创客:{},给他上级:{},增加创客积分,积分数据:{}", integralStatDTO.getUserId(), kxsUser.getId(), JSON.toJSONString(kxsShdScore));
            }
        }
//        //初级积分
//        //获取职级 > K3 的全部用户
//        List<KxsUserRealLevel> kxsUserRealLevels = kxsUserRealLevelMapper.selectList(Wrappers.<KxsUserRealLevel>query().lambda().gt(KxsUserRealLevel::getLevel, 3));
//        //构造月份
//
//        for (KxsUserRealLevel kxsUserRealLevel : kxsUserRealLevels) {
//            //查询全部直属用户
//            List<KxsUserRealLevel> kxsUserRealLevelList = kxsUserRealLevelMapper.selectList(Wrappers.<KxsUserRealLevel>query().lambda().eq(KxsUserRealLevel::getPid, kxsUserRealLevel.getUserId()));
//            //当直属用户大于3时才进行积分计算
//            if (kxsUserRealLevelList.size() > 3) {
//                //初级积分基数
//                int firstScoreCardinal = 0;
//                //中级积分基数
//                int centerScoreCardinal = 0;
//                //高级积分基数
//                int highScoreCardinal = 0;
//                for (KxsUserRealLevel kxsUserRealLevelSon : kxsUserRealLevelList) {
//                    int level = Integer.parseInt(kxsUserRealLevelSon.getLevel());
//                    //校验用户职级
//                    if (level > 2) {
//                        ++firstScoreCardinal;
//                    }
//                    if (level > 3) {
//                        ++centerScoreCardinal;
//                    }
//                    if (level > 4) {
//                        ++highScoreCardinal;
//                    }
//                }
//                //用户实际获得积分
//                int firstScore = firstScoreCardinal / 3;
//                int centerScore = centerScoreCardinal / 3;
//                int highScore = highScoreCardinal / 3;
//                if (firstScore != 0 || centerScore != 0 || highScore != 0) {
//                    KxsShdScore kxsShdScore = kxsShdScoreMapper.selectOne(Wrappers.<KxsShdScore>query().lambda().eq(KxsShdScore::getUserId, kxsUserRealLevel.getUserId()).eq(KxsShdScore::getMonth, month));
//                    if (kxsShdScore == null) {
//                        kxsShdScore = new KxsShdScore();
//                        kxsShdScore.setCreateTime(now);
//                        kxsShdScore.setDelFlag("0");
//                        kxsShdScore.setUserId(kxsUserRealLevel.getUserId());
//                        kxsShdScore.setFirstScore(firstScore);
//                        kxsShdScore.setCenterScore(centerScore);
//                        kxsShdScore.setHighScore(highScore);
//                        kxsShdScore.setMonth(month);
//                        kxsShdScoreMapper.insert(kxsShdScore);
//                    } else {
//                        //存在记录只需修改积分
//                        kxsShdScore.setFirstScore(firstScore);
//                        kxsShdScore.setCenterScore(centerScore);
//                        kxsShdScore.setHighScore(highScore);
//                        kxsShdScore.setUpdateTime(now);
//                        kxsShdScoreMapper.updateById(kxsShdScore);
//                    }
//                }
//            }
//        }

    }


}

