package com.hzs.member.base.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.*;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.exception.ServiceException;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.detail.CuMemberAchieveLog;
import com.hzs.common.security.service.UserTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.achieve.service.ICuMemberTreeService;
import com.hzs.member.base.mapper.CuMemberAchieveLogMapper;
import com.hzs.member.base.service.ICuMemberAchieveLogService;
import com.hzs.member.base.vo.CuMemberAchieveLogVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.sys.IApprovalServiceApi;
import com.hzs.system.sys.dto.ApprovalBusinessResultDTO;
import com.hzs.system.sys.dto.ApprovalSubmitDTO;
import com.hzs.system.sys.dto.BusinessLogDTO;
import com.hzs.system.sys.dto.LoginUser;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * <p>
 * 注水业绩记录表 服务实现类
 * </p>
 *
 * @author zhangjing
 * @since 2023-02-03
 */
@Service
public class CuMemberAchieveLogServiceImpl extends ServiceImpl<CuMemberAchieveLogMapper, CuMemberAchieveLog> implements ICuMemberAchieveLogService {

    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @DubboReference
    IApprovalServiceApi approvalServiceApi;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private ICuMemberSettlePeriodService memberSettlePeriodService;
    @Autowired
    private ICuMemberTreeService memberTreeService;
    @DubboReference
    private ICurrencyServiceApi currencyServiceApi;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ICuMemberAchieveLogService cuMemberAchieveLogService;

    /**
     * @description: 特殊业务-注水业绩记录查询
     * @author: zhang jing
     * @date: 2023/2/3 17:15
     * @param: [cuMemberAchieveLogVO]
     * @return: java.util.List<com.hzs.member.base.vo.CuMemberAchieveLogVO>
     **/
    @Override
    public List<CuMemberAchieveLogVO> queryMemberAchieveLogList(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        //先查询
//        List<CuMemberAchieveLogVO> listAll = new ArrayList<>();
//        if (StringUtils.isNotNull(cuMemberAchieveLogVO.getStartDate()) &&
//                StringUtils.isNotNull(cuMemberAchieveLogVO.getEndtDate())) {
//            Instant startInstant = cuMemberAchieveLogVO.getStartDate().toInstant();
//            Instant endInstant = cuMemberAchieveLogVO.getEndtDate().toInstant();
//            ZoneId zoneId = ZoneId.systemDefault();
//            LocalDate startLocalDate = startInstant.atZone(zoneId).toLocalDate();
//            LocalDate endLocalDate = endInstant.atZone(zoneId).toLocalDate();
//            //根据日期范围遍历日期
//            for (LocalDate localDate = startLocalDate; localDate.isBefore(endLocalDate);
//                 localDate = localDate.plusDays(1)) {
//                ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
//                Date date = Date.from(zdt.toInstant());
//                String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
//                String month = DateUtils.getMonth(datestr);
//                String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
//                List<CuMemberAchieveLogVO> list = baseMapper.queryMemberAchieveLogList(cuMemberAchieveLogVO.getMemberCode(),
//                        cuMemberAchieveLogVO.getMemberName(), cuMemberAchieveLogVO.getPkCountry(),
//                        cuMemberAchieveLogVO.getPkAwards(), cuMemberAchieveLogVO.getPkTeamCode(),
//                        cuMemberAchieveLogVO.getPkVertex(), cuMemberAchieveLogVO.getStartDate(),
//                        cuMemberAchieveLogVO.getEndtDate(), cuMemberAchieveLogVO.getStaDueDate(),
//                        cuMemberAchieveLogVO.getEndDueDate(), cuMemberAchieveLogVO.getWaterStatus(),
//                        cuMemberAchieveLogVO.getInfusingWaterType());
//                listAll.addAll(list);
//            }
//        } else {
//            Date date = new Date();
//            date = DateUtils.beforeDate(1, ChronoUnit.DAYS, date);
//            String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
//            String month = DateUtils.getMonth(datestr);
//            String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
//            listAll = baseMapper.queryMemberAchieveLogList(cuMemberAchieveLogVO.getMemberCode(),
//                    cuMemberAchieveLogVO.getMemberName(), cuMemberAchieveLogVO.getPkCountry(),
//                    cuMemberAchieveLogVO.getPkAwards(), cuMemberAchieveLogVO.getPkTeamCode(),
//                    cuMemberAchieveLogVO.getPkVertex(), cuMemberAchieveLogVO.getStartDate(),
//                    cuMemberAchieveLogVO.getEndtDate(), cuMemberAchieveLogVO.getStaDueDate(),
//                    cuMemberAchieveLogVO.getEndDueDate(), cuMemberAchieveLogVO.getWaterStatus(),
//                    cuMemberAchieveLogVO.getInfusingWaterType());
//        }
        //先查询注水日志表
        List<CuMemberAchieveLogVO> list = baseMapper.queryMemberAchieveLogList(cuMemberAchieveLogVO.getMemberCode(),
                cuMemberAchieveLogVO.getMemberName(), cuMemberAchieveLogVO.getPkCountry(),
                cuMemberAchieveLogVO.getPkAwards(), cuMemberAchieveLogVO.getPkTeamCode(),
                cuMemberAchieveLogVO.getPkVertex(), cuMemberAchieveLogVO.getStartDate(),
                cuMemberAchieveLogVO.getEndtDate(), cuMemberAchieveLogVO.getStaDueDate(),
                cuMemberAchieveLogVO.getEndDueDate(), cuMemberAchieveLogVO.getWaterStatus(),
                cuMemberAchieveLogVO.getInfusingWaterType());
//        if (CollectionUtil.isNotEmpty(list)) {
//            list.forEach(itm -> {
//                String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, itm.getSettleDate());
//                String month = DateUtils.getMonth(datestr);
//                String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
//                //查询最新期数
//                int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
//                        DateUtils.parseDateToStr(datestr)).getPkId();
//                itm.setPeriod(period);
//                itm.setTableName(tableName);
//            });
//            List<CuMemberAchieveLogVO> achieveHistoryList = baseMapper.queryMemberAchieveHistoryList(list);
//            if (CollectionUtil.isNotEmpty(achieveHistoryList)) {
//                list.forEach(itm -> {
//                    achieveHistoryList.forEach(itmm -> {
//                        if (itmm.getPkMember().equals(itm.getPkMember()) &&
//                                itmm.getPeriod().equals(itm.getPeriod())) {
//                            itm.setAbalance(itmm.getAbalance());
//                            itm.setBbalance(itmm.getBbalance());
//                            itm.setAsumPv(itmm.getAsumPv());
//                            itm.setBsumPv(itmm.getBsumPv());
//                            itm.setAsumRealPv(itmm.getAsumRealPv());
//                            itm.setBsumRealPv(itmm.getBsumRealPv());
//                            itm.setRepABalance(itmm.getRepABalance());
//                            itm.setRepBBalance(itmm.getRepBBalance());
//                            itm.setRepASumPv(itmm.getRepASumPv());
//                            itm.setRepBSumPv(itmm.getRepBSumPv());
//                        }
//                    });
//                });
//            }
//        }
        return list;
    }

    /**
     * @description: 查询某一期的历史业绩
     * @author: zhang jing
     * @date: 2023/9/11 9:19
     * @param: [calList]
     * @return: java.util.List<com.hzs.member.base.vo.CuMemberAchieveLogVO>
     **/
    public List<CuMemberAchieveLogVO> queryMemberAchieveHistoryList(List<CuMemberAchieveLogVO> calList) {
        List<CuMemberAchieveLogVO> list = baseMapper.queryMemberAchieveHistoryList(calList);
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal exchangeRate = SecurityUtils.getPkCountry() == CountryConstants.CHINA_COUNTRY ? currency.getData().getInExchangeRate() : BigDecimal.ONE;
        List<CuMemberAchieveLogVO> listnew = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            list.forEach(itm -> {
                itm.setAsumRealModifyPv(itm.getAsumRealPv().multiply(exchangeRate));
                itm.setBsumRealModifyPv(itm.getBsumRealPv().multiply(exchangeRate));
                itm.setAfirstModifyPv(itm.getAsumPv().multiply(exchangeRate));
                itm.setBfirstModifyPv(itm.getBsumPv().multiply(exchangeRate));
                itm.setRepAFirstModifyBalance(itm.getAbalance().multiply(exchangeRate));
                itm.setRepBFirstModifyBalance(itm.getBbalance().multiply(exchangeRate));
                itm.setRepAModifySumPv(itm.getRepASumPv().multiply(exchangeRate));
                itm.setRepBModifySumPv(itm.getRepBSumPv().multiply(exchangeRate));
                itm.setRepAModifyBalance(itm.getRepABalance().multiply(exchangeRate));
                itm.setRepBModifyBalance(itm.getRepBBalance().multiply(exchangeRate));
                listnew.add(itm);
            });
        }
        return listnew;
    }


    /**
     * @description: 特殊业务-注水业绩-审核列表
     * @author: zhang jing
     * @date: 2023/3/28 16:28
     * @param: [cuMemberAchieveLogVO]
     * @return: java.util.List<com.hzs.member.base.vo.CuMemberAchieveLogVO>
     **/
    public List<CuMemberAchieveLogVO> queryTryAchieveLogList(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        return baseMapper.queryTryAchieveLogList(cuMemberAchieveLogVO.getApproveStatus(), cuMemberAchieveLogVO.getBusinessNo());
    }


    /**
     * @description: 查询单个会员当期业绩
     * @author: zhang jing
     * @date: 2023/2/4 10:14
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.member.base.vo.CuMemberAchieveLogVO
     **/
    @Override
    public CuMemberAchieveLogVO searchOne(CuMemberAchieveLogVO cuMemberAchieveLogVO, Integer pkCountry) {
        CuMemberAchieveLogVO achieveLogVO = new CuMemberAchieveLogVO();
        Date date = new Date();
        String time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date);
        //查询秒结
        CuMemberSettlePeriod csPeriod = memberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
        if (StringUtils.isNotNull(csPeriod)) {
            Integer secondid = csPeriod.getPkId();
            // 会员结算秒结表
            String settleTableName = TableNameConstants.CU_MEMBER_SECOND + secondid;
            if (StringUtils.isNotEmpty(settleTableName)) {
                achieveLogVO = baseMapper.searchOne(settleTableName, cuMemberAchieveLogVO.getPkMember());
            }
        }
        //历史记录
        if (StringUtils.isNull(achieveLogVO)) {
            for (int i = 6; i > 0; i--) {
                String settleDate = DateUtils.getDay(date, -1);
                Integer period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(settleDate).getPkId();
                if (StringUtils.isNull(period)) {
                    continue;
                }
                String currentSettleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
                if (StringUtils.isNotEmpty(currentSettleTableName)) {
                    achieveLogVO = baseMapper.searchOne(currentSettleTableName, cuMemberAchieveLogVO.getPkMember());
                    if (StringUtils.isNotNull(achieveLogVO)) {
                        break;
                    }
                }
            }
        }
        return achieveLogVO;
    }

    /**
     * @description: 查询最大审核次数
     * @author: zhang jing
     * @date: 2023/2/6 16:11
     * @param: [pkMember, approveStatus]
     * @return: java.lang.Integer
     **/
    @Override
    public Integer selectByMaxApproveNumber(Long pkMember, int approveStatus) {
        return baseMapper.selectByMaxApproveNumber(pkMember, approveStatus);
    }

    /**
     * @description: 注水业绩
     * @author: zhang jing
     * @date: 2023/2/6 17:58
     * @param: [cuMemberAchieveLogVO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CuMemberAchieveLogVO infusingWater(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.MEMBER_ACHIEVE.getValue());
        cuMemberAchieveLogVO.setPkAccount(cuMemberAchieveLogVO.getCmalvList().get(0).getPkAccount());
        for (CuMemberAchieveLogVO cmal : cuMemberAchieveLogVO.getCmalvList()) {
            //中国区人民币转为美元
            if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                if (cmal.getAsumRealModifyPv() != null && cmal.getAsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setAsumRealModifyPv(cmal.getAsumRealModifyPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getBsumRealModifyPv() != null && cmal.getBsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setBsumRealModifyPv(cmal.getBsumRealModifyPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getAfirstModifyPv() != null && cmal.getAfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setAfirstModifyPv(cmal.getAfirstModifyPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getBfirstModifyPv() != null && cmal.getBfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setBfirstModifyPv(cmal.getBfirstModifyPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepAFirstModifyBalance() != null && cmal.getRepAFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepAFirstModifyBalance(cmal.getRepAFirstModifyBalance().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepBFirstModifyBalance() != null && cmal.getRepBFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepBFirstModifyBalance(cmal.getRepBFirstModifyBalance().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepAModifySumPv() != null && cmal.getRepAModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepAModifySumPv(cmal.getRepAModifySumPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepBModifySumPv() != null && cmal.getRepBModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepBModifySumPv(cmal.getRepBModifySumPv().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepAModifyBalance() != null && cmal.getRepAModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepAModifyBalance(cmal.getRepAModifyBalance().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
                if (cmal.getRepBModifyBalance() != null && cmal.getRepBModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    cmal.setRepBModifyBalance(cmal.getRepBModifyBalance().divide(currency.getData().getInExchangeRate(), 6, RoundingMode.HALF_UP));
                }
            }

            //历史期业绩
            String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cmal.getSettleDate());
            String month = DateUtils.getMonth(datestr);
            String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
            //查询最新期数
            int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                    DateUtils.parseDateToStr(datestr)).getPkId();
            cuMemberAchieveLogVO.setTableName(tableName);
            cuMemberAchieveLogVO.setPeriod(1137);
            cuMemberAchieveLogVO.setPkMember(cmal.getPkMember());
            List<CuMemberAchieveLogVO> calList=new ArrayList<>();
            calList.add(cuMemberAchieveLogVO);
            calList=cuMemberAchieveLogService.queryMemberAchieveHistoryList(calList);

            //免签呈 或 免签呈+免支付
            if (cuMemberAchieveLogVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                    cuMemberAchieveLogVO.getProcessType() == EProcessType.DOUBLEAVOID.getValue()) {
                CuMemberAchieveLog memberAchieveLog = BeanUtil.copyProperties(cmal, CuMemberAchieveLog.class);
                memberAchieveLog.setASumRealModifyPv(cmal.getAsumRealModifyPv());
                memberAchieveLog.setBSumRealModifyPv(cmal.getBsumRealModifyPv());
                memberAchieveLog.setAFirstModifyPv(cmal.getAfirstModifyPv());
                memberAchieveLog.setBFirstModifyPv(cmal.getBfirstModifyPv());
                memberAchieveLog.setRepAFirstModifyBalance(cmal.getRepAFirstModifyBalance());
                memberAchieveLog.setRepBFirstModifyBalance(cmal.getRepBFirstModifyBalance());
                memberAchieveLog.setRepAModifySumPv(cmal.getRepAModifySumPv());
                memberAchieveLog.setRepBModifySumPv(cmal.getRepBModifySumPv());
                memberAchieveLog.setRepAModifyBalance(cmal.getRepAModifyBalance());
                memberAchieveLog.setRepBModifyBalance(cmal.getRepBModifyBalance());
                memberAchieveLog.setPkCountry(pkCountry);
                memberAchieveLog.setInfusingWaterType(cuMemberAchieveLogVO.getInfusingWaterType());
                memberAchieveLog.setProcessType(cuMemberAchieveLogVO.getProcessType());
                memberAchieveLog.setApproveStatus(EApproveStatus.FINISH.getValue());
                memberAchieveLog.setEditType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                memberAchieveLog.setBusinessNo(code);
                memberAchieveLog.setCost(cmal.getCost());
                memberAchieveLog.setPkAccount(cmal.getPkAccount());
                memberAchieveLog.setRemarks(cmal.getRemarks());
                memberAchieveLog.setDueDate(cmal.getDueDate());
                memberAchieveLog.setSettleDate(cmal.getSettleDate());
                memberAchieveLog.setCreationTime(date);
                memberAchieveLog.setPkCreator(userID);
                if(CollectionUtil.isNotEmpty(calList)){
                    memberAchieveLog.setAsumRealPv(calList.get(0).getAsumRealPv());
                    memberAchieveLog.setBsumRealPv(calList.get(0).getBsumRealPv());
                    memberAchieveLog.setAsumPv(calList.get(0).getAsumPv());
                    memberAchieveLog.setBsumPv(calList.get(0).getBsumPv());
                    memberAchieveLog.setAbalance(calList.get(0).getAbalance());
                    memberAchieveLog.setBbalance(calList.get(0).getBbalance());
                    memberAchieveLog.setRepASumPv(calList.get(0).getRepASumPv());
                    memberAchieveLog.setRepBSumPv(calList.get(0).getRepBSumPv());
                    memberAchieveLog.setRepABalance(calList.get(0).getRepABalance());
                    memberAchieveLog.setRepBBalance(calList.get(0).getRepBBalance());
                }
                baseMapper.insert(memberAchieveLog);
                String content = EApprovalBusiness.MEMBER_ACHIEVE.getLabel();
                String waterType = "";
                if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.ADD.getValue()){
                    waterType =EInfusingWaterType.ADD.getLabel();
                }else if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.BANK_TRANSFER.getValue()){
                    waterType =EInfusingWaterType.BANK_TRANSFER.getLabel();
                }else if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.FULL_PV.getValue()){
                    waterType =EInfusingWaterType.FULL_PV.getLabel();
                }
                if (cmal.getAsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区真实业绩"+waterType+": " + cmal.getAsumRealModifyPv();
                }  if (cmal.getBsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区真实业绩"+waterType+": " + cmal.getBsumRealModifyPv();
                }  if (cmal.getAfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区首购业绩"+waterType+": " + cmal.getAfirstModifyPv();
                }  if (cmal.getBfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区首购业绩"+waterType+": " + cmal.getBfirstModifyPv();
                }  if (cmal.getRepAFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区首购结余"+waterType+": " + cmal.getRepAFirstModifyBalance();
                }  if (cmal.getRepBFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区首购结余"+waterType+": " + cmal.getRepBFirstModifyBalance();
                }  if (cmal.getRepAModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区复购业绩累计业绩"+waterType+": " + cmal.getRepAModifySumPv();
                }  if (cmal.getRepBModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区复购业绩累计业绩"+waterType+": " + cmal.getRepBModifySumPv();
                }  if (cmal.getRepAModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区复购结余"+waterType+": " + cmal.getRepAModifyBalance();
                }  if (cmal.getRepBModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区复购结余"+waterType+": " + cmal.getRepBModifyBalance();
                }

                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.MEMBER_ACHIEVE.getValue())
                        .businessCode(code)
                        .pkMember(cmal.getPkMember())
                        .content(content)
                        .pkCreator(userID)
                        .pkCountry(pkCountry)
                        .freeSignFlag(true).build();
                dtoList.add(businessLog);
            }
        }
        //扣钱
        if (cuMemberAchieveLogVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(cuMemberAchieveLogVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(cuMemberAchieveLogVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.MEMBER_ACHIEVE_DEDUCT_MONEY);
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return cuMemberAchieveLogVO;
    }

    /**
     * @description: 发起签呈
     * @author: zhang jing
     * @date: 2023/4/12 9:04
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.member.base.vo.CuMemberAchieveLogVO
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CuMemberAchieveLogVO petition(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        Date date = new Date();
        Long userID = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 封装修改会员编号业务日志
        List<BusinessLogDTO> dtoList = new ArrayList<>();
        //业务单号
        String code = CommonUtil.createSerialNumber(EOrderPrefix.MEMBER_ACHIEVE.getValue());
        Set<Long> pkMemberIds = new HashSet<>();
        cuMemberAchieveLogVO.setPkAccount(cuMemberAchieveLogVO.getCmalvList().get(0).getPkAccount());

        for (CuMemberAchieveLogVO cmal : cuMemberAchieveLogVO.getCmalvList()) {

            //历史期业绩
            String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cmal.getSettleDate());
            String month = DateUtils.getMonth(datestr);
            String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
            //查询最新期数
            int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                    DateUtils.parseDateToStr(datestr)).getPkId();
            cuMemberAchieveLogVO.setTableName(tableName);
            cuMemberAchieveLogVO.setPeriod(period);
            cuMemberAchieveLogVO.setPkMember(cmal.getPkMember());
            List<CuMemberAchieveLogVO> calList=new ArrayList<>();
            calList.add(cuMemberAchieveLogVO);
            calList=cuMemberAchieveLogService.queryMemberAchieveHistoryList(calList);

            //免支付 或 需签呈+支付
            if (cuMemberAchieveLogVO.getProcessType() == EProcessType.AVOIDPAY.getValue() ||
                    cuMemberAchieveLogVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                pkMemberIds.add(cmal.getPkMember());
                CuMemberAchieveLog memberAchieveLog = BeanUtil.copyProperties(cmal, CuMemberAchieveLog.class);
                memberAchieveLog.setASumRealModifyPv(cmal.getAsumRealModifyPv());
                memberAchieveLog.setBSumRealModifyPv(cmal.getBsumRealModifyPv());
                memberAchieveLog.setAFirstModifyPv(cmal.getAfirstModifyPv());
                memberAchieveLog.setBFirstModifyPv(cmal.getBfirstModifyPv());
                memberAchieveLog.setRepAFirstModifyBalance(cmal.getRepAFirstModifyBalance());
                memberAchieveLog.setRepBFirstModifyBalance(cmal.getRepBFirstModifyBalance());
                memberAchieveLog.setRepAModifySumPv(cmal.getRepAModifySumPv());
                memberAchieveLog.setRepBModifySumPv(cmal.getRepBModifySumPv());
                memberAchieveLog.setRepAModifyBalance(cmal.getRepAModifyBalance());
                memberAchieveLog.setRepBModifyBalance(cmal.getRepBModifyBalance());
                memberAchieveLog.setCreationTime(date);
                memberAchieveLog.setInfusingWaterType(cuMemberAchieveLogVO.getInfusingWaterType());
                memberAchieveLog.setProcessType(cuMemberAchieveLogVO.getProcessType());
                memberAchieveLog.setPkCreator(userID);
                memberAchieveLog.setPeriod(cmal.getPeriod());
                memberAchieveLog.setPkCountry(pkCountry);
                memberAchieveLog.setBusinessNo(code);
                memberAchieveLog.setCost(cmal.getCost());
                memberAchieveLog.setPkAccount(cmal.getPkAccount());
                memberAchieveLog.setRemarks(cmal.getRemarks());
                memberAchieveLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
                memberAchieveLog.setEditType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                memberAchieveLog.setDueDate(cmal.getDueDate());
                memberAchieveLog.setSettleDate(cmal.getSettleDate());
                if(CollectionUtil.isNotEmpty(calList)){
                    memberAchieveLog.setAsumRealPv(calList.get(0).getAsumRealPv());
                    memberAchieveLog.setBsumRealPv(calList.get(0).getBsumRealPv());
                    memberAchieveLog.setAsumPv(calList.get(0).getAsumPv());
                    memberAchieveLog.setBsumPv(calList.get(0).getBsumPv());
                    memberAchieveLog.setAbalance(calList.get(0).getAbalance());
                    memberAchieveLog.setBbalance(calList.get(0).getBbalance());
                    memberAchieveLog.setRepASumPv(calList.get(0).getRepASumPv());
                    memberAchieveLog.setRepBSumPv(calList.get(0).getRepBSumPv());
                    memberAchieveLog.setRepABalance(calList.get(0).getRepABalance());
                    memberAchieveLog.setRepBBalance(calList.get(0).getRepBBalance());
                }
                baseMapper.insert(memberAchieveLog);
                String content = EApprovalBusiness.MEMBER_ACHIEVE.getLabel();
                String waterType = "";
                //注水方式
                if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.ADD.getValue()){
                    waterType =EInfusingWaterType.ADD.getLabel();
                }else if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.BANK_TRANSFER.getValue()){
                    waterType =EInfusingWaterType.BANK_TRANSFER.getLabel();
                }else if(cuMemberAchieveLogVO.getInfusingWaterType()==EInfusingWaterType.FULL_PV.getValue()){
                    waterType =EInfusingWaterType.FULL_PV.getLabel();
                }
                if (cmal.getAsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区真实业绩"+waterType+": " + cmal.getAsumRealModifyPv();
                }  if (cmal.getBsumRealModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 更后右区真实业绩"+waterType+": " + cmal.getBsumRealModifyPv();
                }  if (cmal.getAfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区首购业绩"+waterType+": " + cmal.getAfirstModifyPv();
                }  if (cmal.getBfirstModifyPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区首购业绩"+waterType+": " + cmal.getBfirstModifyPv();
                }  if (cmal.getRepAFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区首购结余"+waterType+": " + cmal.getRepAFirstModifyBalance();
                }  if (cmal.getRepBFirstModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区首购结余"+waterType+": " + cmal.getRepBFirstModifyBalance();
                }  if (cmal.getRepAModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区复购业绩累计业绩"+waterType+": " + cmal.getRepAModifySumPv();
                }  if (cmal.getRepBModifySumPv().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区复购业绩累计业绩"+waterType+": " + cmal.getRepBModifySumPv();
                }  if (cmal.getRepAModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 左区复购结余"+waterType+": " + cmal.getRepAModifyBalance();
                }  if (cmal.getRepBModifyBalance().compareTo(BigDecimal.ZERO) > 0) {
                    content = content + " 右区复购结余"+waterType+": " + cmal.getRepBModifyBalance();
                }

                //组装日志数据
                BusinessLogDTO businessLog = BusinessLogDTO.builder()
                        .businessType(EApprovalBusiness.MEMBER_ACHIEVE.getValue())
                        .businessCode(code)
                        .pkMember(cmal.getPkMember())
                        .content(content)
                        .pkCreator(userID)
                        .pkCountry(pkCountry)
                        .freeSignFlag(false).build();
                dtoList.add(businessLog);
            }
        }
        //生成签呈
        LoginUser loginUser = userTokenService.getLoginUser();
        ApprovalSubmitDTO approvalSubmitDTO = ApprovalSubmitDTO.builder().eApprovalBusiness(EApprovalBusiness.MEMBER_ACHIEVE)
                .businessCode(code)
                .signType(ESignType.getEnumByValue(cuMemberAchieveLogVO.getSignType()))
                .remark(cuMemberAchieveLogVO.getRemark())
                .pkMemberList(cuMemberAchieveLogVO.getPkMemberList())
                .userIdList(cuMemberAchieveLogVO.getUserIdList())
                .sendIdList(cuMemberAchieveLogVO.getSendIdList())
                .build();
        R<String> submit = approvalServiceApi.submit(approvalSubmitDTO, loginUser);
        if (!submit.isSuccess()) {
            log.error("====" + submit.getData());
            throw new RuntimeException(ConfigMsgConstants.MEMBER_ACHIEVE_DEDUCT_PETITION);
        }

        //扣钱
        if (cuMemberAchieveLogVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            businessCommissionDTO.setTradeCode(code);
            businessCommissionDTO.setPkCountry(pkCountry);
            businessCommissionDTO.setPkAccount(cuMemberAchieveLogVO.getPkAccount());
            businessCommissionDTO.setMemberAmountDTOList(cuMemberAchieveLogVO.getMemberAmountDTOList());
            businessCommissionDTO.setTradeType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
            Boolean b = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO);
            if (!b) {
                throw new ServiceException(ConfigMsgConstants.MEMBER_ACHIEVE_DEDUCT_MONEY);
            }
        }
        //发送MQ到操作日志
        rabbitTemplate.convertAndSend(RabbitMqConstants.BUSINESS_LOG_EXCHANGE, RabbitMqConstants.BUSINESS_LOG_KEY,
                dtoList);
        return cuMemberAchieveLogVO;
    }

    /**
     * @description: 注水业绩签呈审批-通过或驳回
     * @author: zhang jing
     * @date: 2023/4/11 9:57
     * @param: [approvalBusinessResultDTO]
     * @return: boolean
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean toExamine(ApprovalBusinessResultDTO approvalBusinessResultDTO) {
        Date date = new Date();
        Long userID = approvalBusinessResultDTO.getLoginUser().getUserId();
        Integer pkCountry = approvalBusinessResultDTO.getLoginUser().getDataCountry();
        QueryWrapper<CuMemberAchieveLog> queryWrapper = new QueryWrapper();
        queryWrapper.eq("BUSINESS_NO", approvalBusinessResultDTO.getBusinessCode());
        queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
        List<CuMemberAchieveLog> malList = baseMapper.selectList(queryWrapper);
        //审核通过
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.FINISH.getValue()) {
            if (CollectionUtil.isNotEmpty(malList)) {
                for (CuMemberAchieveLog cmal : malList) {
                    //修改日志表审核状态
                    UpdateWrapper<CuMemberAchieveLog> updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("PK_MEMBER", cmal.getPkMember());
                    updateWrapper.eq("BUSINESS_NO", cmal.getBusinessNo());
                    updateWrapper.set("APPROVE_STATUS", EApproveStatus.FINISH.getValue());
                    updateWrapper.set("MODIFIED_TIME", date);
                    updateWrapper.set("PK_MODIFIED", userID);
                    baseMapper.update(null, updateWrapper);
                }
            }
        }
        //审核驳回
        if (approvalBusinessResultDTO.getEApproveStatus().getValue() == EApproveStatus.REJECTED.getValue()) {
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(malList)) {
                for (CuMemberAchieveLog cmal : malList) {
                    if (StringUtils.isNotNull(cmal.getCost()) && cmal.getCost().compareTo(BigDecimal.ZERO) > 0) {
                        MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                        memberAmountDTO.setPkMember(cmal.getPkMember());
                        memberAmountDTO.setTradeAmount(cmal.getCost());
                        memberAmountDTO.setPkAccount(cmal.getPkAccount());
                        memberAmountDTOList.add(memberAmountDTO);
                    }
                    //修改日志表审核状态
                    CuMemberAchieveLog memberAchieveLog = BeanUtil.copyProperties(cmal, CuMemberAchieveLog.class);
                    memberAchieveLog.setModifiedTime(date);
                    memberAchieveLog.setPkModified(userID);
                    memberAchieveLog.setPkCountry(pkCountry);
                    memberAchieveLog.setApproveStatus(EApproveStatus.REJECTED.getValue());
                    UpdateWrapper<CuMemberAchieveLog> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("PK_MEMBER", cmal.getPkMember());
                    updateWrapper.eq("BUSINESS_NO", cmal.getBusinessNo());
                    baseMapper.update(memberAchieveLog, updateWrapper);
                }
                if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                    //退款
                    BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                    businessCommissionDTO.setPkCountry(pkCountry);
                    businessCommissionDTO.setPkAccount(memberAmountDTOList.get(0).getPkAccount());
                    businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                    businessCommissionDTO.setTradeType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                    businessCommissionDTO.setTradeCode(approvalBusinessResultDTO.getBusinessCode());
                    businessCommissionDTO.setPkCreator(approvalBusinessResultDTO.getLoginUser().getUserId());
                    Boolean result = cuMemberTradeService.businessCommissionSubmit(businessCommissionDTO, EApproveStatus.REJECTED);
                    if (!result) {
                        throw new ServiceException(ConfigMsgConstants.MEMBER_ACHIEVE_IS_REFUND);
                    }
                }
            }
        }
        return true;
    }

    @Override
    public List<CuMemberAchieveLog> queryMemberAchieveLogByPeriod(Integer period) {
        QueryWrapper<CuMemberAchieveLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(MemberFieldConstants.PERIOD, period);
        queryWrapper.in(SystemFieldConstants.APPROVE_STATUS, EApproveStatus.FINISH.getValue());
        queryWrapper.orderByAsc(MemberFieldConstants.PK_MEMBER, SystemFieldConstants.CREATION_TIME);
        return baseMapper.selectList(queryWrapper);
    }

    /**
     * @description: 校验是否存在未审核数据
     * @author: zhang jing
     * @date: 2023/3/28 14:36
     * @param: [memberAchieveLogVO]
     * @return: java.util.List<com.hzs.member.base.vo.CuMemberAchieveLogVO>
     **/
    @Override
    public List<CuMemberAchieveLogVO> checkAchieveList(CuMemberAchieveLogVO memberAchieveLogVO) {
        return baseMapper.checkAchieveList(memberAchieveLogVO);
    }

}
