package com.hzs.bonus.achieve.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.service.ICuMemberAchieveService;
import com.hzs.bonus.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.bonus.achieve.service.ICuMemberTreeService;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.achieve.CuMemberAchieve;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.achieve.ext.CuMemberAchieveExt;
import com.hzs.common.domain.member.swing.ext.CuMemberSwingNetExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.bonus.achieve.mapper.CuMemberAchieveMapper;
import com.hzs.bonus.achieve.param.MemberAchieveParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 会员业绩记录 服务实现类
 *
 * @author hzs
 * @since 2022-10-26
 */
@Slf4j
@Service
public class CuMemberAchieveServiceImpl extends ServiceImpl<CuMemberAchieveMapper, CuMemberAchieve> implements ICuMemberAchieveService {

    @Autowired
    private ICuMemberTreeService cuMemberTreeService;
    @Autowired
    private CuMemberBonusSettle cuMemberBonusSettle;
    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;

    @Override
    public String createCuMemberAchieve(String date) {
        // 创建业绩月表记录表
        String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + DateUtils.getMonth(date);
        Integer num = cuMemberTreeService.queryExistOracleTable(tableName);
        if (num == null || num <= 0) {
            baseMapper.createCuMemberAchieveTable(tableName);
            cuMemberTreeService.createCuMemberTableUniqueIndex(tableName);
            cuMemberTreeService.createCuMemberTableSequence(tableName, TableNameConstants.CU_MEMBER_ACHIEVE_SEQ);
        }
        return tableName;
    }

    @Override
    public void createCuMemberMonthTable(String tableName) {
        baseMapper.createCuMemberMonthTable(tableName);
    }

    @Override
    public void mergeCuMemberMonth(Integer day, String date) {
        String tableName = TableNameConstants.CU_MEMBER_MONTH + DateUtils.getMonth(date);
        CuMemberSettlePeriod cuMemberSettlePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date);
        // 每月6号删除上月数据,重新生成
//        if (day == 6) {
        Integer number = cuMemberTreeService.queryExistOracleTable(tableName);
        if (number != null && number > 0) {
            cuMemberTreeService.truncateCuMemberTreeTable(tableName);
        }
//        }
        baseMapper.mergeCuMemberMonth(DateUtils.getMonth(date), cuMemberSettlePeriod.getPkId());
    }

    @Override
    public void mergeCuMemberAchieveBySettleDate(String targetTableName, String sourceTableName, Integer period) {
        baseMapper.mergeCuMemberAchieveBySettleDate(targetTableName, sourceTableName, period);
    }

    @Override
    public void updateCuMemberSettleInitAchieve(String targetTable) {
        baseMapper.updateCuMemberSettleInitAchieve(targetTable);
    }

    @Override
    public void updateCuMemberSettleAchieveByBeforeDay(String sourceTable, String targetTable) {
        baseMapper.updateCuMemberSettleAchieveByBeforeDay(sourceTable, targetTable);
    }

    @Override
    public void updateCuMemberExpandSettleAchieveByBeforeDay(String sourceTable, String targetTable) {
        baseMapper.updateCuMemberExpandSettleAchieveByBeforeDay(sourceTable, targetTable);
    }

    @Override
    public void updateCuMemberSettleAchieveBySpecialBus(String targetTable, Integer period, Long pkId) {
        baseMapper.updateCuMemberSettleAchieveBySpecialBus(targetTable, period, pkId);
    }

    @Override
    public void mergeCuMemberSettleByAchieveLogByDate(String targetTable, Date settleDate) {
        baseMapper.mergeCuMemberSettleByAchieveLogByDate(targetTable, settleDate);
    }

    @Override
    public void updateCuMemberSettleAchieveByDueDate(String currentTableName, String yesTableName, Date currentDate) {
        baseMapper.updateCuMemberSettleAchieveByDueDate(currentTableName, yesTableName, currentDate);
    }

    @Override
    public void updateCuMemberAchieveEveryDay(Map<Long, MemberAchieveParam> memberAchieveParamMap, String tablaName) {
        if (memberAchieveParamMap.size() == 0) {
            return;
        }
        List<MemberAchieveParam> memberAchieveParamList = new ArrayList<>();
        memberAchieveParamMap.forEach((key, memberAchieveParam) ->
                memberAchieveParamList.add(memberAchieveParam));
        List<List<?>> listList = cuMemberBonusSettle.handleCutList(memberAchieveParamList, MagicNumberConstants.DELETE_DATA_BATCH_UPDATE_NUM);
        listList.forEach(list -> {
            baseMapper.updateCuMemberBackAchieveEveryDay(list, tablaName);
        });
    }

    @Override
    public void updateCuMemberNetAchieve(List<CuMemberAchieveExt> updMemberAchieveExtList, String currentSettleTableName) {
        baseMapper.updateCuMemberNetAchieve(updMemberAchieveExtList, currentSettleTableName);
    }

    @Override
    public void updateCuMemberBackOldAchieveEveryDay(Map<Long, MemberAchieveParam> memberAchieveParamMap, String tablaName) {
        if (memberAchieveParamMap.size() == 0) {
            return;
        }
        List<MemberAchieveParam> memberAchieveParamList = new ArrayList<>();
        memberAchieveParamMap.forEach((key, memberAchieveParam) ->
                memberAchieveParamList.add(memberAchieveParam));
        List<List<?>> listList = cuMemberBonusSettle.handleCutList(memberAchieveParamList, MagicNumberConstants.DELETE_DATA_BATCH_UPDATE_NUM);
        listList.forEach(list -> {
            baseMapper.updateCuMemberBackOldAchieveEveryDay(list, tablaName);
        });
    }

    @Override
    public List<CuMemberAchieveExt> queryCuMemberMonthAchieveByMemberIdList(String settleTableName, List<CuMemberSwingNetExt> memberSwingNetExtList) {
        return baseMapper.queryCuMemberMonthAchieveByMemberIdList(settleTableName, memberSwingNetExtList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean chargeBackSaOrder(SaOrder saOrder) {
        // 根据支付时间查询期间
        // 查询期间的cu_member_tree 查询网体，根据网体更新业绩，更新7天前到昨天网体业绩
        MemberAchieveParam cuMemberAchieve = MemberAchieveParam.builder()
                .pkRate(saOrder.getPkRate())
                .pkMember(saOrder.getPkMember())
                .newAmount(BigDecimal.ZERO)
                .newPv(BigDecimal.ZERO)
                .repNewAmount(BigDecimal.ZERO)
                .repNewPv(BigDecimal.ZERO)
                .newRealAmount(BigDecimal.ZERO)
                .newRealPv(BigDecimal.ZERO)
                .build();
        if (Objects.equals(EOrderType.REGISTER_ORDER.getValue(), saOrder.getOrderType()) ||
                Objects.equals(EOrderType.UPGRADE_ORDER.getValue(), saOrder.getOrderType()) ||
                Objects.equals(EOrderType.FICTITIOUS_ORDER.getValue(), saOrder.getOrderType()) ||
                Objects.equals(EOrderType.SPECIAL_REGISTER_ORDER.getValue(), saOrder.getOrderType()) ||
                Objects.equals(EOrderType.SPECIAL_UPGRADE_ORDER.getValue(), saOrder.getOrderType())) {
            cuMemberAchieve.setNewAmount(saOrder.getOrderAmount());
            cuMemberAchieve.setNewPv(saOrder.getOrderAchieve());
        } else {
            cuMemberAchieve.setRepNewAmount(saOrder.getOrderAmount());
            cuMemberAchieve.setRepNewPv(saOrder.getOrderAchieve());
        }
        String payTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, saOrder.getPayTime());
        int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(payTime).getPkId();
        String sourceTable = TableNameConstants.CU_MEMBER_TREE + DateUtils.getMonth(payTime);
        for (int i = 7; i > 0; i--) {
            String settleDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.beforeDate(i, ChronoUnit.DAYS));
            int settlePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(settleDate).getPkId();
            String targetTable = TableNameConstants.CU_MEMBER_SETTLE + settlePeriod;
            baseMapper.chargeBackSaOrder(targetTable, sourceTable, period, cuMemberAchieve);
        }
        return Boolean.TRUE;
    }


}
