package cn.pluss.platform.user.impl;

import cn.pluss.platform.entity.ExtraLevelBenefit;
import cn.pluss.platform.entity.UserApp;
import cn.pluss.platform.entity.UserLevel;
import cn.pluss.platform.entity.UserProfit;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.level.ExtraLevelBenefitService;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.mapper.UserProfitMapper;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.user.UserLevelService;
import cn.pluss.platform.user.UserProfitService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.vo.UserAppVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bzg
 * @since 2022-01-14
 */
@Service
@Slf4j
public class UserProfitServiceImpl extends ServiceImpl<UserProfitMapper, UserProfit> implements UserProfitService {

    @Resource
    private UserAppService userAppService;

    @Resource
    private UserAppMapper userAppMapper;

    @Resource
    private UserLevelService userLevelService;

    @Resource
    private MerchantOrderService merchantOrderService;

    @Resource
    private ExtraLevelBenefitService extraLevelBenefitService;

    public static final int MAX_LEVEL_AMT = 1000000;

    @Override
    public void createProfitV2(String date) {
        if(StringUtil.isEmpty(date)){
            date = DateUtils.formatDateDefault(DateUtils.add(Calendar.DAY_OF_MONTH, new Date(), -1),"yyyy-MM-dd");
        }
        Integer maxSort = merchantOrderService.getOrderMaxSort(date);
        Integer uMaxSort = userAppMapper.getMaxSort();
        Integer nowSort = maxSort;
        if(!uMaxSort.equals(maxSort)){
            nowSort = uMaxSort;
        }
        for (int i = nowSort; i > 0; i-- ) {
            List<UserProfit> list = merchantOrderService.getOrderFlow(date, i);
            for (UserProfit p:list) {
                p.setCreateTime(DateUtils.currentDate());
                BigDecimal teamTransFlow = BigDecimal.ZERO;
                BigDecimal flow = p.getTeamTransFlow();
                BigDecimal beforFlow = baseMapper.getBeforeFlowByUserId(p.getUserId());
                teamTransFlow = teamTransFlow.add(flow).add(beforFlow);
                if(teamTransFlow.doubleValue() >= MAX_LEVEL_AMT){
                    int maxCount = teamTransFlow.intValue() / MAX_LEVEL_AMT;
                    if(maxCount > 0){
                        ExtraLevelBenefit levelBenefit = extraLevelBenefitService.getByUserId(p.getUserId());
                        if(levelBenefit == null){
                            ExtraLevelBenefit benefit = new ExtraLevelBenefit(p.getUserId().intValue(),maxCount);
                            extraLevelBenefitService.save(benefit);
                        }else{
                            levelBenefit.setMaxCount(maxCount);
                            extraLevelBenefitService.updateById(levelBenefit);
                        }
                    }
                }
            }
            if(list.size() < 1000){
                saveBatch(list);
            }else{
                saveBatch(list,list.size());
            }
        }
    }

    @Override
    public BigDecimal getMonthTeamFlow(String userId, String month) {


        return null;
    }

    @Override
    public Page<UserAppVO> apiPageMonthSubTeamData(Page<UserAppVO> page, String userName) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        return pageMonthSubTeamData(page, tokenUa.getUserId() + "", userName);
    }

    @Override
    public Page<UserAppVO> pageMonthSubTeamData(Page<UserAppVO> page, String userId, String userName) {
        return baseMapper.selectPageSubTeamData(page, userId, userName);
    }

    @Override
    public void calcLevelTask() {
        String profitMonth = DateUtils.formatDateDefault(DateUtils.add(Calendar.MONTH,new Date(),-1),"yyyy-MM");
        List<UserProfit> list = selectLevelFlow(profitMonth);
        if(!list.isEmpty()){
            for (UserProfit u:list) {
                if(StringUtil.isEmpty(u.getUserId())){
                    continue;
                }
                UserApp userApp = userAppMapper.selectByUserId(u.getUserId());
                String oldLevelCode = userApp.getLevelCode();
                if(userApp == null || userApp.getLevelCode() == null || UserRoleEnum.ZY_BST.getCode().equals(userApp.getRoleCode())){
                    continue;
                }
                UserLevel userLevel = userLevelService.getNowQuotaLevel(u.getTeamTransFlow());
                if(userLevel == null || userApp.getLevelCode().equals(userLevel.getLevelCode())){
                    continue;
                }
                boolean flag = StringUtil.isNumber(oldLevelCode.replace(UserLevel.LEVEL_CODE_PREFIX, ""));
                boolean nowFlag = StringUtil.isNumber(userLevel.getLevelCode().replace(UserLevel.LEVEL_CODE_PREFIX, ""));
                if(!flag || !nowFlag){
                    continue;
                }
                Integer oldLevel = Integer.valueOf(oldLevelCode.replace(UserLevel.LEVEL_CODE_PREFIX, ""));
                Integer upLevel = Integer.valueOf(userLevel.getLevelCode().replace(UserLevel.LEVEL_CODE_PREFIX, ""));
                if(oldLevel >= upLevel){
                    continue;
                }
                userApp.setLevelCode(userLevel.getLevelCode());
                userAppMapper.updateById(userApp);
                log.info("月统计用户流水是否达标升级，用户ID:{},之前等级:{}，更新后的等级：{}更新成功",userApp.getUserId(),oldLevelCode,userLevel.getLevelCode());
            }
        }
    }

    /**
     * 获取用户月团队流水
     * @date: 2022/1/25 22:59
     * @return java.util.List<cn.pluss.platform.entity.UserProfit>
     */
    @Override
    public List<UserProfit> selectLevelFlow(String profitMonth) {
        return baseMapper.selectLevelFlow(profitMonth);
    }

    /**
     * 分页查询
     * @date: 2022/3/11 15:55
     * @param page:
     * @param condition:
     * @return com.baomidou.mybatisplus.extension.plugins.pagination.Page<cn.pluss.platform.entity.UserProfit>
     */
    @Override
    public Page<UserProfit> pageData(Page<UserProfit> page, UserProfit condition) {
        return  baseMapper.pageData(page,condition);
    }
}
