package com.hzs.member.base.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.TableNameConstants;
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.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.account.dto.BusinessCommissionDTO;
import com.hzs.member.account.dto.MemberAmountDTO;
import com.hzs.member.account.dto.MemberBalanceDTO;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.base.service.ICuMemberAchieveLogService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.CuMemberAchieveLogImportVO;
import com.hzs.member.base.vo.CuMemberAchieveLogVO;
import com.hzs.member.base.vo.UpdateCodeVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 注水业绩记录表 前端控制器
 *
 * @author zhangjing
 * @since 2023-02-03
 */
@RestController
@RequestMapping("/manager/member-achieve-log")
public class CuMemberAchieveLogController extends BaseController {

    @Autowired
    private ICuMemberAchieveLogService cuMemberAchieveLogService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;
    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    IServiceChargeServiceApi serviceChargeServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    /**
     * @description: 特殊业务-注水业绩记录查询
     * @author: zhang jing
     * @date: 2023/2/3 17:21
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @AccessPermissions("WaterPv")
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo achieveLogList(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        startPage();
        cuMemberAchieveLogVO.setPkCountry(SecurityUtils.getPkCountry());
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        List<CuMemberAchieveLogVO> list = cuMemberAchieveLogService.queryMemberAchieveLogList(cuMemberAchieveLogVO);
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAchieveLogVO cma : list) {
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    if (cma.getAsumRealModifyPv() != null) {
                        cma.setAsumRealModifyPv(cma.getAsumRealModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumRealModifyPv() != null) {
                        cma.setBsumRealModifyPv(cma.getBsumRealModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAfirstModifyPv() != null) {
                        cma.setAfirstModifyPv(cma.getAfirstModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBfirstModifyPv() != null) {
                        cma.setBfirstModifyPv(cma.getBfirstModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAFirstModifyBalance() != null) {
                        cma.setRepAFirstModifyBalance(cma.getRepAFirstModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBFirstModifyBalance() != null) {
                        cma.setRepBFirstModifyBalance(cma.getRepBFirstModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAModifySumPv() != null) {
                        cma.setRepAModifySumPv(cma.getRepAModifySumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBModifySumPv() != null) {
                        cma.setRepBModifySumPv(cma.getRepBModifySumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAModifyBalance() != null) {
                        cma.setRepAModifyBalance(cma.getRepAModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBModifyBalance() != null) {
                        cma.setRepBModifyBalance(cma.getRepBModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAsumRealPv() != null) {
                        cma.setAsumRealPv(cma.getAsumRealPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumRealPv() != null) {
                        cma.setBsumRealPv(cma.getBsumRealPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAsumPv() != null) {
                        cma.setAsumPv(cma.getAsumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumPv() != null) {
                        cma.setBsumPv(cma.getBsumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAbalance() != null) {
                        cma.setAbalance(cma.getAbalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBbalance() != null) {
                        cma.setBbalance(cma.getBbalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepASumPv() != null) {
                        cma.setRepASumPv(cma.getRepASumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBSumPv() != null) {
                        cma.setRepBSumPv(cma.getRepBSumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepABalance() != null) {
                        cma.setRepABalance(cma.getRepABalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBBalance() != null) {
                        cma.setRepBBalance(cma.getRepBBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                }
                // 判断注水状态
                // 开始时间
                long startTime = cma.getSettleDate().getTime();
                // 结束时间
                long endTime = cma.getDueDate().getTime();
                // 当前时间
                long currentTime = DateUtils.currentDate().getTime();
                if ((currentTime > startTime && currentTime < endTime) || currentTime == startTime || currentTime == endTime) {
                    // 当前时间大于开始 小于结束
                    cma.setWaterStatusVal(EActivityStatus.IN_PROGRESS.getLabel());
                } else if (currentTime < startTime) {
                    // 当前时间小于开始时间
                    cma.setWaterStatusVal(EActivityStatus.NOT_STARTED.getLabel());
                } else if (currentTime > endTime) {
                    // 当前时间大于结束时间
                    cma.setWaterStatusVal(EActivityStatus.EXPIRED.getLabel());
                }
            }
        }
        return getDataTable(list);
    }

    /**
     * @description: 导出
     * @author: zhang jing
     * @date: 2023/4/7 10:14
     * @param: [response, cuMemberAchieveLogVO, language]
     * @return: void
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        startPage();
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        List<CuMemberAchieveLogVO> list = cuMemberAchieveLogService.queryMemberAchieveLogList(cuMemberAchieveLogVO);
        if (CollectionUtil.isNotEmpty(list)) {
            //枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EInfusingWaterType.values());
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(
                    EnumsPrefixConstants.KEY_AWARD);
            for (CuMemberAchieveLogVO cma : list) {
                //中国把美元转成人民币
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    if (cma.getAsumRealModifyPv() != null) {
                        cma.setAsumRealModifyPv(cma.getAsumRealModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumRealModifyPv() != null) {
                        cma.setBsumRealModifyPv(cma.getBsumRealModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAfirstModifyPv() != null) {
                        cma.setAfirstModifyPv(cma.getAfirstModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBfirstModifyPv() != null) {
                        cma.setBfirstModifyPv(cma.getBfirstModifyPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAFirstModifyBalance() != null) {
                        cma.setRepAFirstModifyBalance(cma.getRepAFirstModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBFirstModifyBalance() != null) {
                        cma.setRepBFirstModifyBalance(cma.getRepBFirstModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAModifySumPv() != null) {
                        cma.setRepAModifySumPv(cma.getRepAModifySumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBModifySumPv() != null) {
                        cma.setRepBModifySumPv(cma.getRepBModifySumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepAModifyBalance() != null) {
                        cma.setRepAModifyBalance(cma.getRepAModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBModifyBalance() != null) {
                        cma.setRepBModifyBalance(cma.getRepBModifyBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAsumRealPv() != null) {
                        cma.setAsumRealPv(cma.getAsumRealPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumRealPv() != null) {
                        cma.setBsumRealPv(cma.getBsumRealPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAsumPv() != null) {
                        cma.setAsumPv(cma.getAsumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBsumPv() != null) {
                        cma.setBsumPv(cma.getBsumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getAbalance() != null) {
                        cma.setAbalance(cma.getAbalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getBbalance() != null) {
                        cma.setBbalance(cma.getBbalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepASumPv() != null) {
                        cma.setRepASumPv(cma.getRepASumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBSumPv() != null) {
                        cma.setRepBSumPv(cma.getRepBSumPv().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepABalance() != null) {
                        cma.setRepABalance(cma.getRepABalance().multiply(currency.getData().getInExchangeRate()));
                    }
                    if (cma.getRepBBalance() != null) {
                        cma.setRepBBalance(cma.getRepBBalance().multiply(currency.getData().getInExchangeRate()));
                    }
                }
                cma.setInfusingWaterTypeVal(transactionMap.get(EnumsPrefixConstants.INFUSING_WATER_TYPE + cma.getInfusingWaterType()));
                cma.setAwardsVal(transactionMap1.get(cma.getAwards()));
                // 判断注水状态
                // 开始时间
                long startTime = cma.getSettleDate().getTime();
                // 结束时间
                long endTime = cma.getDueDate().getTime();
                // 当前时间
                long currentTime = DateUtils.currentDate().getTime();
                if ((currentTime > startTime && currentTime < endTime) || currentTime == startTime || currentTime == endTime) {
                    // 当前时间大于开始 小于结束
                    cma.setWaterStatusVal(EActivityStatus.IN_PROGRESS.getLabel());
                } else if (currentTime < startTime) {
                    // 当前时间小于开始时间
                    cma.setWaterStatusVal(EActivityStatus.NOT_STARTED.getLabel());
                } else if (currentTime > endTime) {
                    // 当前时间大于结束时间
                    cma.setWaterStatusVal(EActivityStatus.EXPIRED.getLabel());
                }
            }
        }
        ExcelUtil<CuMemberAchieveLogVO> util = new ExcelUtil<>(CuMemberAchieveLogVO.class);
        util.exportExcel(response, list, "注水业绩");

    }

    /**
     * @description: 下载模板
     * @author: zhang jing
     * @date: 2023/4/11 17:45
     * @param: [response]
     * @return: void
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<CuMemberAchieveLogImportVO> list = new ArrayList<>();
        ExcelUtil<CuMemberAchieveLogImportVO> util = new ExcelUtil<>(CuMemberAchieveLogImportVO.class);
        util.exportExcel(response, list, "注水业绩");

    }

    /**
     * @description: 查询会员当期业绩
     * @author: zhang jing
     * @date: 2023/2/4 9:37
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.page.TableDataInfo
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SELECT)
    @GetMapping("/searchList")
    public AjaxResult searchList(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        if (StringUtils.isEmpty(cuMemberAchieveLogVO.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
        }
        UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(cuMemberAchieveLogVO, UpdateCodeVO.class);
        updateCodeVO = cuMemberService.specialBusinessQuery(updateCodeVO);
        Integer pkCountry = SecurityUtils.getPkCountry();
        Integer maxSecond = cuMemberAchieveLogService.selectByMaxApproveNumber(updateCodeVO.getPkId(), EApproveStatus.FINISH.getValue());
        //查询扣费金额，账户信息
        ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
        serviceChargeDTO.setType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
        serviceChargeDTO.setQuantity(maxSecond + 1);
        serviceChargeDTO.setPkCountry(pkCountry);
        R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
        updateCodeVO.setCost(serviceChargeDTOR.getData().getCost());
        updateCodeVO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
        updateCodeVO.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
        cuMemberAchieveLogVO = BeanUtil.copyProperties(updateCodeVO, CuMemberAchieveLogVO.class);
        cuMemberAchieveLogVO.setPkMember(updateCodeVO.getPkId());
        List<CuMemberAchieveLogVO> list = new ArrayList<>();
        list.add(cuMemberAchieveLogVO);
        return AjaxResult.success(list);
    }

    /**
     * @description: 根据某一期查询历史业绩
     * @author: zhang jing
     * @date: 2023/9/11 9:26
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SELECT)
    @GetMapping("/historyAchieve")
    public AjaxResult historyAchieve(CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        if (cuMemberAchieveLogVO.getSettleDate() != null && cuMemberAchieveLogVO.getPkMember() != null) {
            String datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cuMemberAchieveLogVO.getSettleDate());
            String month = DateUtils.getMonth(datestr);
            String tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
            Integer count = cuMemberService.selectExistTable(tableName);
            if (count == 0) {
                //表不存在则查询之前一天的数据
                cuMemberAchieveLogVO.setSettleDate(DateUtils.beforeDate(1, ChronoUnit.DAYS, cuMemberAchieveLogVO.getSettleDate()));
                datestr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cuMemberAchieveLogVO.getSettleDate());
                month = DateUtils.getMonth(datestr);
                tableName = TableNameConstants.CU_MEMBER_ACHIEVE + month;
            }
            //查询最新期数
            int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                    DateUtils.parseDateToStr(datestr)).getPkId();
            cuMemberAchieveLogVO.setTableName(tableName);
            cuMemberAchieveLogVO.setPeriod(period);
            List<CuMemberAchieveLogVO> calList = new ArrayList<>();
            calList.add(cuMemberAchieveLogVO);
            calList = cuMemberAchieveLogService.queryMemberAchieveHistoryList(calList);
            if (CollectionUtil.isNotEmpty(calList)) {
                return AjaxResult.success(calList.get(0));
            } else {
                return AjaxResult.success(cuMemberAchieveLogVO);
            }
        } else {
            return AjaxResult.success(cuMemberAchieveLogVO);
        }
    }

    /**
     * @description: 判断日期是否在7天内
     * @author: zhang jing
     * @date: 2023/3/28 9:25
     * @param: [addtime, now]
     * @return: boolean
     **/
    private boolean isLatestWeek(Date addtime, Date now) {
        Calendar calendar = Calendar.getInstance();  //得到日历
        calendar.setTime(now);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, -7);  //设置为7天前
        Date before7days = calendar.getTime();   //得到7天前的时间
        return before7days.getTime() < addtime.getTime();
    }

    /**
     * @description: 导入信息
     * @author: zhang jing
     * @date: 2023/2/3 17:48
     * @param: [file, updateSupport]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<CuMemberAchieveLogImportVO> util = new ExcelUtil<>(CuMemberAchieveLogImportVO.class);
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuMemberAchieveLogImportVO> list = util.importExcel(file.getInputStream());
        List<CuMemberAchieveLogImportVO> errorlist = new ArrayList<>();
        List<CuMemberAchieveLogImportVO> listNew = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            for (CuMemberAchieveLogImportVO cma : list) {
                if (StringUtils.isNotEmpty(cma.getMemberCode())) {
                    UpdateCodeVO updateCodeVO = BeanUtil.copyProperties(cma, UpdateCodeVO.class);
                    updateCodeVO = cuMemberService.specialBusinessQuery(updateCodeVO);
                    if (null == updateCodeVO) {
                        cma.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                        errorlist.add(cma);
                        continue;
                    }
                    cma.setPkMember(updateCodeVO.getPkId());
                    cma.setMemberName(updateCodeVO.getMemberName());
                    Integer maxSecond = cuMemberAchieveLogService.selectByMaxApproveNumber(updateCodeVO.getPkId(), EApproveStatus.FINISH.getValue());
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                    serviceChargeDTO.setQuantity(maxSecond + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    cma.setCost(serviceChargeDTOR.getData().getCost());
                    cma.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    cma.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                    listNew.add(cma);
                } else {
                    cma.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                    errorlist.add(cma);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
        }
        return AjaxResult.success(listNew);
    }

    /**
     * @description: 根据选中的会员查询会员的历史业绩
     * @author: zhang jing
     * @date: 2023/3/28 19:46
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SELECT)
    @PostMapping("/infusingWaterBelow")
    public AjaxResult infusingWaterBelow(@RequestBody CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        if (CollectionUtil.isEmpty(cuMemberAchieveLogVO.getPkMemberList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        if (CollectionUtil.isEmpty(cuMemberAchieveLogVO.getAchieveList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACHIEVE_NOT_NULL));
        }

        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuMemberAchieveLogVO> listNew = new ArrayList<>();
        for (Long pkid : cuMemberAchieveLogVO.getPkMemberList()) {
            CuMemberAchieveLogVO cma = new CuMemberAchieveLogVO();
            cma.setPkMember(pkid);
            CuMemberAchieveLogVO cmal = cuMemberAchieveLogService.searchOne(cma, pkCountry);
            if (StringUtils.isNotNull(cmal)) {
                CuMemberAchieveLogVO cmalnew = new CuMemberAchieveLogVO();
                cmalnew.setPkMember(cma.getPkMember());
                for (int i = 0; i < cuMemberAchieveLogVO.getAchieveList().size(); i++) {
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.ASUMREALMODIFY_PV.getValue()) {
                        cmalnew.setAsumRealPv(cma.getAsumRealPv());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.BSUMREALMODIFY_PV.getValue()) {
                        cmalnew.setBsumRealPv(cma.getBsumRealPv());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.AFIRSTMODIFY_PV.getValue()) {
                        cmalnew.setAfirstModifyPv(cma.getAfirstModifyPv());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.BFIRSTMODIFY_PV.getValue()) {
                        cmalnew.setBfirstModifyPv(cma.getBfirstModifyPv());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPAFIRSTMODIFY_BALANCE.getValue()) {
                        cmalnew.setRepAFirstModifyBalance(cma.getRepAFirstModifyBalance());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPBFIRSTMODIFY_BALANCE.getValue()) {
                        cmalnew.setRepBFirstModifyBalance(cma.getRepBFirstModifyBalance());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPAMODIFY_BALANCE.getValue()) {
                        cmalnew.setRepABalance(cma.getRepABalance());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPBMODIFY_BALANCE.getValue()) {
                        cmalnew.setRepBBalance(cma.getRepBBalance());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPAMODIFYSUM_PV.getValue()) {
                        cmalnew.setRepASumPv(cma.getRepASumPv());
                    }
                    if (cuMemberAchieveLogVO.getAchieveList().get(i) == EMemberAchieve.REPBMODIFYSUM_PV.getValue()) {
                        cmalnew.setRepBSumPv(cma.getRepBSumPv());
                    }
                }
                Integer maxSecond = cuMemberAchieveLogService.selectByMaxApproveNumber(cmal.getPkMember(), EApproveStatus.FINISH.getValue());
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                serviceChargeDTO.setQuantity(maxSecond + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                //接口查询金额是否足够
                cmalnew.setCost(serviceChargeDTOR.getData().getCost());
                cmalnew.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                cmalnew.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                listNew.add(cmalnew);
            }
        }

        return AjaxResult.success(listNew);
    }

    /**
     * @description:注水业绩 确认
     * @author: zhang jing
     * @date: 2023/2/6 14:50
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SUBMIT)
    @PostMapping("/infusingWater")
    public AjaxResult infusingWater(@RequestBody CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        if (StringUtils.isNull(cuMemberAchieveLogVO.getInfusingWaterType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.INFUSING_WATER_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(cuMemberAchieveLogVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        List<CuMemberAchieveLogVO> errorList = new ArrayList<>();
        CuMemberAchieveLogVO memberAchieveLogVONew;
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        Set<Long> pkMemberList = new HashSet<>();
        if (CollectionUtil.isNotEmpty(cuMemberAchieveLogVO.getCmalvList())) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            for (CuMemberAchieveLogVO cmal : cuMemberAchieveLogVO.getCmalvList()) {
                if (StringUtils.isNull(cmal.getSettleDate())) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.SETTLEDATE_NOT_VALID));
                    errorList.add(cmal);
                    continue;
                }
                if (cmal.getRepAFirstModifyBalance() != null && cmal.getRepAFirstModifyBalance().compareTo(BigDecimal.ONE) > 0
                        && cmal.getRepBFirstModifyBalance() != null && cmal.getRepBFirstModifyBalance().compareTo(BigDecimal.ONE) > 0) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.BALANCE_NOT_ZERO));
                    errorList.add(cmal);
                    continue;
                }
                if (cmal.getRepAModifyBalance() != null && cmal.getRepAModifyBalance().compareTo(BigDecimal.ONE) > 0
                        && cmal.getRepBModifyBalance() != null && cmal.getRepBModifyBalance().compareTo(BigDecimal.ONE) > 0) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.BALANCE_NOT_ZERO));
                    errorList.add(cmal);
                    continue;
                }
                if (StringUtils.isNull(cmal.getDueDate())) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_DUE_DATE_COMPARE));
                    errorList.add(cmal);
                    continue;
                }
                Integer dateInt = DateUtils.compareDate(cmal.getDueDate(), cmal.getSettleDate());
                if (dateInt < 0) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_DUE_DATE_COMPARE));
                    errorList.add(cmal);
                    continue;
                }

                //获取期数
                int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cmal.getSettleDate())).getPkId();
                if (period == 0) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.ACHIEVE_WITHIN_SEVEN_DAYS));
                    errorList.add(cmal);
                    continue;
                }
                cmal.setPeriod(period);
                if (!isLatestWeek(cmal.getSettleDate(), new Date())) {
                    cmal.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.ACHIEVE_WITHIN_SEVEN_DAYS));
                    errorList.add(cmal);
                    continue;
                }
                cmal.setSettleDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cmal.getSettleDate()));
                cmal.setDueDateStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, cmal.getDueDate()));
                if (StringUtils.isNull(cmal.getAsumRealModifyPv())
                        && StringUtils.isNull(cmal.getBsumRealModifyPv())
                        && StringUtils.isNull(cmal.getAfirstModifyPv())
                        && StringUtils.isNull(cmal.getBfirstModifyPv())
                        && StringUtils.isNull(cmal.getRepAFirstModifyBalance())
                        && StringUtils.isNull(cmal.getRepBFirstModifyBalance())
                        && StringUtils.isNull(cmal.getRepAModifyBalance())
                        && StringUtils.isNull(cmal.getRepBModifyBalance())
                        && StringUtils.isNull(cmal.getRepAModifySumPv())
                        && StringUtils.isNull(cmal.getRepBModifySumPv())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.INFUSING_WATER_PV_NOT_NULL));
                }
                Integer maxSecond = cuMemberAchieveLogService.selectByMaxApproveNumber(cmal.getPkMember(), EApproveStatus.FINISH.getValue());
                cmal.setApproveNumber(maxSecond + 1);
                if (cuMemberAchieveLogVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        cuMemberAchieveLogVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                    serviceChargeDTO.setQuantity(maxSecond + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(cmal.getPkMember());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    cmal.setCost(serviceChargeDTOR.getData().getCost());
                    cmal.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    cmal.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                    memberAmountDTOList.add(memberAmountDTO);
                }
                pkMemberList.add(cmal.getPkMember());
            }
            if (CollectionUtil.isNotEmpty(errorList)) {
                return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorList);
            }
            cuMemberAchieveLogVO.setPkMemberList(pkMemberList);
            List<CuMemberAchieveLogVO> achieveList = cuMemberAchieveLogService.checkAchieveList(cuMemberAchieveLogVO);
            if (CollectionUtil.isNotEmpty(achieveList)) {
                achieveList.forEach(itm -> itm.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT))
                );
                return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, achieveList);
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                cuMemberAchieveLogVO.setMemberAmountDTOList(memberAmountDTOList);
                cuMemberAchieveLogVO.setPkCountry(pkCountry);
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    memberBalanceList.forEach(item -> errorList.add(BeanUtil.copyProperties(item, CuMemberAchieveLogVO.class)));
                    errorList.forEach(itm2 -> itm2.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT)));
                    return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorList);
                }
            }
            memberAchieveLogVONew = cuMemberAchieveLogService.infusingWater(cuMemberAchieveLogVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(memberAchieveLogVONew);
    }

    /**
     * @description: 特殊业务-注水业绩-发起签呈
     * @author: zhang jing
     * @date: 2023/3/28 13:50
     * @param: [cuMemberAchieveLogVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_ACHIEVEMENT, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody CuMemberAchieveLogVO cuMemberAchieveLogVO) {
        if (StringUtils.isNull(cuMemberAchieveLogVO.getInfusingWaterType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.INFUSING_WATER_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(cuMemberAchieveLogVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(cuMemberAchieveLogVO.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(cuMemberAchieveLogVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }

        CuMemberAchieveLogVO memberAchieveLogVONew;
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        List<CuMemberAchieveLogVO> errorList = new ArrayList<>();
        Set<Long> pkMemberList = new HashSet<>();
        if (CollectionUtil.isNotEmpty(cuMemberAchieveLogVO.getCmalvList())) {
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            for (CuMemberAchieveLogVO cmal : cuMemberAchieveLogVO.getCmalvList()) {
                if (StringUtils.isNull(cmal.getSettleDate())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLEDATE_NOT_VALID));
                }
                Date settleDate = cmal.getSettleDate();
                if (!isLatestWeek(settleDate, new Date())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ACHIEVE_WITHIN_SEVEN_DAYS));
                }
                if (StringUtils.isNull(cmal.getAsumRealModifyPv())
                        && StringUtils.isNull(cmal.getBsumRealModifyPv())
                        && StringUtils.isNull(cmal.getAfirstModifyPv())
                        && StringUtils.isNull(cmal.getBfirstModifyPv())
                        && StringUtils.isNull(cmal.getRepAFirstModifyBalance())
                        && StringUtils.isNull(cmal.getRepBFirstModifyBalance())
                        && StringUtils.isNull(cmal.getRepAModifyBalance())
                        && StringUtils.isNull(cmal.getRepBModifyBalance())
                        && StringUtils.isNull(cmal.getRepAModifySumPv())
                        && StringUtils.isNull(cmal.getRepBModifySumPv())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.INFUSING_WATER_PV_NOT_NULL));
                }
                Integer maxSecond = cuMemberAchieveLogService.selectByMaxApproveNumber(cmal.getPkMember(), EApproveStatus.FINISH.getValue());
                cmal.setApproveNumber(maxSecond + 1);
                if (cuMemberAchieveLogVO.getProcessType() == EProcessType.DOUBLEPAY.getValue() ||
                        cuMemberAchieveLogVO.getProcessType() == EProcessType.AVOIDPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.MEMBER_ACHIEVE.getValue());
                    serviceChargeDTO.setQuantity(maxSecond + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(cmal.getPkMember());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    cmal.setCost(serviceChargeDTOR.getData().getCost());
                    cmal.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    cmal.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                    memberAmountDTOList.add(memberAmountDTO);
                    pkMemberList.add(cmal.getPkMember());
                }
            }
            cuMemberAchieveLogVO.setPkMemberList(pkMemberList);
            List<CuMemberAchieveLogVO> achieveList = cuMemberAchieveLogService.checkAchieveList(cuMemberAchieveLogVO);
            if (CollectionUtil.isNotEmpty(achieveList)) {
                achieveList.forEach(itm -> itm.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT))
                );
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), achieveList);
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                cuMemberAchieveLogVO.setMemberAmountDTOList(memberAmountDTOList);
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    memberBalanceList.forEach(item -> errorList.add(BeanUtil.copyProperties(item, CuMemberAchieveLogVO.class)));
                    errorList.forEach(itm2 -> itm2.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT)));
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorList);
                }
            }
            memberAchieveLogVONew = cuMemberAchieveLogService.petition(cuMemberAchieveLogVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(memberAchieveLogVONew);
    }


}
