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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
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.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.domain.member.base.CuMember;
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.base.service.ICuMemberService;
import com.hzs.member.base.vo.*;
import com.hzs.member.base.vo.ImportPolicyCurrencyVO;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
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.util.*;
import java.util.stream.Collectors;

/**
 * @description: 特殊配置-修改政策币
 * @author: zhang jing
 * @date: 2022/12/29 11:39
 * @param:
 * @return:
 **/
@RequestMapping("/manage/update-policy-currency")
@RestController
public class UpPolicyCurrencyController extends BaseController {

    private ICuMemberService cuMemberService;

    @Autowired
    public void setCuMemberService(ICuMemberService cuMemberService) {
        this.cuMemberService = cuMemberService;
    }

    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    IServiceChargeServiceApi serviceChargeServiceApi;


    /**
     * @description: 特殊业务-修改政策币列表
     * @author: zhang jing
     * @date: 2022/11/17 15:39
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @AccessPermissions("PolicyMoney")
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo upsePolicyCurrencyList(UpPolicyCurrencyVO upPolicyVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        upPolicyVO.setPkCountry(pkCountry);
        upPolicyVO.setApproveStatus(EApproveStatus.FINISH.getValue());
        List<UpPolicyCurrencyVO> list = cuMemberService.upPolicyCurrencyList(upPolicyVO);
        list.forEach(itm -> {
            UpPolicyCurrencyVO upc = JSONObject.parseObject(itm.getNewValue(), UpPolicyCurrencyVO.class);
            itm.setDeductMoney(upc.getDeductMoney());
            itm.setEnableStatus(upc.getEnableStatus());
            itm.setTransfer(upc.getTransfer());
            if (itm.getBusinessScope() != null &&
                    itm.getBusinessScope() == EBusinessScope.VERTEX.getValue()) {
                itm.setBusinessScopeVal(EBusinessScope.VERTEX.getLabel());
            } else {
                itm.setBusinessScopeVal(EBusinessScope.MEMBER.getLabel());
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出
     *
     * @param response
     * @param upPolicyVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UpPolicyCurrencyVO upPolicyVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        upPolicyVO.setPkCountry(pkCountry);
        List<UpPolicyCurrencyVO> list = cuMemberService.upPolicyCurrencyList(upPolicyVO);
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EnableStatus.values(),
                EPopupType.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(
                EnumsPrefixConstants.KEY_AWARD);
        list.forEach(itm -> {
            UpPolicyCurrencyVO upc = JSONObject.parseObject(itm.getNewValue(), UpPolicyCurrencyVO.class);
            itm.setEnableStatusVal(transactionMap.get(EnumsPrefixConstants.ENABLE_STATUS + upc.getEnableStatus()));
            itm.setTransferVal(transactionMap.get(EnumsPrefixConstants.POPUP_TYPE + upc.getTransfer()));
            itm.setDeductMoney(upc.getDeductMoney());
            itm.setPkAwardsVal(transactionMap1.get(itm.getPkAwards()));
        });
        ExcelUtil<UpPolicyCurrencyVO> util = new ExcelUtil<>(UpPolicyCurrencyVO.class);
        util.exportExcel(response, list, "导出修改政策币");
    }

    /**
     * 下载模板
     *
     * @param response
     * @param
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<ImportPolicyCurrencyVO> list = new ArrayList<>();
        ExcelUtil<ImportPolicyCurrencyVO> util = new ExcelUtil<>(ImportPolicyCurrencyVO.class);
        util.exportExcel(response, list, "修改政策币");
    }

    /**
     * @description: 查询会员信息
     * @author: zhang jing
     * @date: 2023/3/30 11:19
     * @param: [upPolicyVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SELECT)
    @PostMapping("/selected")
    public AjaxResult selected(@RequestBody UpPolicyCurrencyVO upPolicyVO) {
        if (StringUtils.isEmpty(upPolicyVO.getMemberCode()) && StringUtils.isEmpty(upPolicyVO.getMemberName())) {
            return AjaxResult.error(ConfigMsgConstants.MEMBER_NOT_VALID);
        }
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<UpPolicyCurrencyVO> newlist = new ArrayList<>();
        CuMemberVO memberParam = BeanUtil.copyProperties(upPolicyVO, CuMemberVO.class);
        memberParam.setPkCountry(pkCountry);
        CuMember member = cuMemberService.getMember(memberParam.getMemberCode());
        if (StringUtils.isNotNull(member)) {
            UpPolicyCurrencyVO upc = BeanUtil.copyProperties(member, UpPolicyCurrencyVO.class);
            newlist.add(upc);
        }
        for (UpPolicyCurrencyVO pc : newlist) {
            pc.setPkMember(pc.getPkId());
            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(pc.getPkId(),
                    EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
            pc.setChangeNumber(approveNumber + 1);
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
            serviceChargeDTO.setQuantity(approveNumber + 1);
            serviceChargeDTO.setPkCountry(pkCountry);
            R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            if (null == serviceChargeDTOR.getData() ||
                    null == serviceChargeDTOR.getData().getPkAccount()) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
            }
            //接口查询金额是否足够
            pc.setPkAccount(serviceChargeDTOR.getData().getPkCountry());
            pc.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
            pc.setCost(serviceChargeDTOR.getData().getCost());
        }
        return AjaxResult.success(newlist);
    }

    /**
     * @description: 导入会员信息
     * @author: zhang jing
     * @date: 2023/1/11 10:27
     * @param: [file, updateSupport]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<ImportPolicyCurrencyVO> util = new ExcelUtil<>(ImportPolicyCurrencyVO.class);
        List<ImportPolicyCurrencyVO> list = util.importExcel(file.getInputStream());
        List<UpPolicyCurrencyVO> errorlist = new ArrayList<>();
        List<UpPolicyCurrencyVO> newlist = new ArrayList<>();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollectionUtil.isNotEmpty(list)) {
            for (ImportPolicyCurrencyVO ucv : list) {
                if (StringUtils.isNull(ucv.getMemberCode())) {
                    return AjaxResult.error(ConfigMsgConstants.MEMBER_CODE_NOT_NULL);
                }

                CuMember cuMember = cuMemberService.getMember(ucv.getMemberCode());
                if (StringUtils.isNull(cuMember)) {
                    UpPolicyCurrencyVO countryVO = BeanUtil.copyProperties(ucv, UpPolicyCurrencyVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                    errorlist.add(countryVO);
                } else {
                    UpPolicyCurrencyVO countryVO = BeanUtil.copyProperties(cuMember, UpPolicyCurrencyVO.class);
                    countryVO.setPkMember(countryVO.getPkId());
                    //当前最大次数
                    Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(countryVO.getPkId(),
                            EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
                    countryVO.setChangeNumber(approveNumber + 1);
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    countryVO.setPkAccount(serviceChargeDTOR.getData().getPkCountry());
                    countryVO.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                    countryVO.setCost(serviceChargeDTOR.getData().getCost());
                    newlist.add(countryVO);
                }
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist);
        }
        return AjaxResult.success(newlist);
    }

    /**
     * @description: 修改政策币
     * @author: zhang jing
     * @date: 2022/12/30 10:22
     * @param: [postageParams]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SUBMIT)
    @PostMapping("/upPolicyCurrency")
    public AjaxResult upPolicyCurrency(@RequestBody UpPolicyCurrencyVO upPolicyVO) {
        if (StringUtils.isNull(upPolicyVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (upPolicyVO.getBusinessScope() == null) {
            upPolicyVO.setBusinessScope(EBusinessScope.MEMBER.getValue());
        }
        List<UpPolicyCurrencyVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(upPolicyVO.getPlculist())) {
            Date date = new Date();
            Integer pkCountry = SecurityUtils.getPkCountry();
            upPolicyVO.setCreationTime(date);
            upPolicyVO.setPkCreator(SecurityUtils.getUserId());
            upPolicyVO.setPkCountry(pkCountry);
            Set<Long> pkMemberIds = new HashSet<>();
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EnableStatus.values(),
                    EPopupType.values());
            // 查询国家
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            for (UpPolicyCurrencyVO plc : upPolicyVO.getPlculist()) {
                if (StringUtils.isEmpty(plc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(plc.getPkMember())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isNull(plc.getEnableStatus())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATUS_NOT_NULL));
                }
                if (plc.getEnableStatus() == EnableStatus.ENABLE.getValue()) {
                    if (StringUtils.isNull(plc.getDeductMoney())) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_MONEY_NOT_NULL));
                    }
                    if (StringUtils.isNull(plc.getTransfer())) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TRANSFER_NOT_NULL));
                    }
                }
                if (StringUtils.isNull(plc.getTransfer())) {
                    plc.setTransfer(EPopupType.STOP.getValue());
                }
                plc.setEnableStatusVal(transactionMap.get(EnumsPrefixConstants.ENABLE_STATUS + plc.getEnableStatus()));
                plc.setTransferVal(transactionMap.get(EnumsPrefixConstants.POPUP_TYPE + plc.getTransfer()));
                if (plc.getBusinessScope() != null && plc.getBusinessScope() == EBusinessScope.MEMBER.getValue()) {
                    plc.setBusinessScopeVal(EBusinessScope.MEMBER.getLabel());
                }
                if (plc.getBusinessScope() != null && plc.getBusinessScope() == EBusinessScope.VERTEX.getValue()) {
                    plc.setBusinessScopeVal(EBusinessScope.VERTEX.getLabel());
                }

                Integer count = cuMemberService.checkmsLogCount(plc.getPkMember(), EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                if (StringUtils.isNotNull(count) && count > 0) {
                    UpPolicyCurrencyVO erplc = BeanUtil.copyProperties(plc, UpPolicyCurrencyVO.class);
                    erplc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(erplc);
                    continue;
                }
                pkMemberIds.add(plc.getPkMember());

                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(plc.getPkMember(),
                        EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
                plc.setChangeNumber(approveNumber + 1);
                if (upPolicyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        upPolicyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(plc.getPkMember());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    plc.setCost(serviceChargeDTOR.getData().getCost());
                    plc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    upPolicyVO.setMemberAmountDTOList(memberAmountDTOList);
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }

            upPolicyVO.setPkMemberList(pkMemberIds);
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            businessCommissionDTO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            upPolicyVO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    memberBalanceList.forEach(itm -> {
                        UpPolicyCurrencyVO plc = BeanUtil.copyProperties(itm, UpPolicyCurrencyVO.class);
                        plc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
                        errorlist.add(plc);
                    });
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            upPolicyVO = cuMemberService.upPolicyCurrency(upPolicyVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(upPolicyVO);
    }

    /**
     * @description: 发起签呈
     * @author: zhang jing
     * @date: 2023/3/22 17:20
     * @param: [upPolicyVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody UpPolicyCurrencyVO upPolicyVO) {
        if (StringUtils.isNull(upPolicyVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(upPolicyVO.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(upPolicyVO.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        //会员业务范围
        if (upPolicyVO.getBusinessScope() == null) {
            upPolicyVO.setBusinessScope(EBusinessScope.MEMBER.getValue());
        }
        List<UpPolicyCurrencyVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(upPolicyVO.getPlculist())) {
            Date date = new Date();
            Integer pkCountry = SecurityUtils.getPkCountry();
            upPolicyVO.setCreationTime(date);
            upPolicyVO.setPkCreator(SecurityUtils.getUserId());
            upPolicyVO.setPkCountry(pkCountry);
            /**
             * 修改政策币集合签呈页面
             */
            Set<Long> pkMemberIds = new HashSet<>();
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EnableStatus.values(),
                    EPopupType.values());
            // 查询国家
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            for (UpPolicyCurrencyVO plc : upPolicyVO.getPlculist()) {
                if (StringUtils.isEmpty(plc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(plc.getPkMember())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isNull(plc.getEnableStatus())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.ENABLE_STATUS_NOT_NULL));
                }
                if (plc.getEnableStatus() == EnableStatus.ENABLE.getValue()) {
                    if (StringUtils.isNull(plc.getDeductMoney())) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.DEDUCT_MONEY_NOT_NULL));
                    }
                    if (StringUtils.isNull(plc.getTransfer())) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.TRANSFER_NOT_NULL));
                    }
                }
                if (StringUtils.isNull(plc.getTransfer())) {
                    plc.setTransfer(EPopupType.STOP.getValue());
                }
                Integer count = cuMemberService.checkmsLogCount(plc.getPkMember(), EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                if (StringUtils.isNotNull(count) && count > 0) {
                    UpPolicyCurrencyVO erplc = BeanUtil.copyProperties(plc, UpPolicyCurrencyVO.class);
                    erplc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(erplc);
                    continue;
                }
                pkMemberIds.add(plc.getPkMember());
                plc.setEnableStatusVal(transactionMap.get(EnumsPrefixConstants.ENABLE_STATUS + plc.getEnableStatus()));
                plc.setTransferVal(transactionMap.get(EnumsPrefixConstants.POPUP_TYPE + plc.getTransfer()));
                if (plc.getBusinessScope() != null && plc.getBusinessScope() == EBusinessScope.MEMBER.getValue()) {
                    plc.setBusinessScopeVal(EBusinessScope.MEMBER.getLabel());
                }
                if (plc.getBusinessScope() != null && plc.getBusinessScope() == EBusinessScope.VERTEX.getValue()) {
                    plc.setBusinessScopeVal(EBusinessScope.VERTEX.getLabel());
                }

                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(plc.getPkMember(),
                        EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
                plc.setChangeNumber(approveNumber + 1);
                if (upPolicyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        upPolicyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.POLICY_CURRENCY_YES_NO.getValue());
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(plc.getPkMember());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    plc.setCost(serviceChargeDTOR.getData().getCost());
                    plc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    upPolicyVO.setMemberAmountDTOList(memberAmountDTOList);
                }
            }

            upPolicyVO.setPkMemberList(pkMemberIds);
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            businessCommissionDTO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            upPolicyVO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    memberBalanceList.forEach(itm -> {
                        UpPolicyCurrencyVO plc = BeanUtil.copyProperties(itm, UpPolicyCurrencyVO.class);
                        plc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
                        errorlist.add(plc);
                    });
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            upPolicyVO = cuMemberService.petition(upPolicyVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(upPolicyVO);
    }


    /**
     * @description: 删除政策币确认
     * @author: zhang jing
     * @date: 2024/4/23 14:42
     * @param: [upPolicyVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SUBMIT)
    @PostMapping("/delConfirm")
    public AjaxResult delConfirm(@RequestBody UpPolicyCurrencyVO upPolicyVO) {
        if (StringUtils.isEmpty(upPolicyVO.getPkIdStr())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_NOT_NULL));
        }
        List<Long> pkIdList = Arrays.stream(upPolicyVO.getPkIdStr().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        upPolicyVO.setPkIdList(pkIdList);
        Integer pkCountry = SecurityUtils.getPkCountry();
        upPolicyVO.setPkCountry(pkCountry);
        upPolicyVO.setApproveStatus(EApproveStatus.FINISH.getValue());
        List<UpPolicyCurrencyVO> list = cuMemberService.upPolicyCurrencyList(upPolicyVO);
        list.forEach(itm -> {
            UpPolicyCurrencyVO upc = JSONObject.parseObject(itm.getNewValue(), UpPolicyCurrencyVO.class);
            itm.setDeductMoney(upc.getDeductMoney());
            itm.setEnableStatus(upc.getEnableStatus());
            itm.setTransfer(upc.getTransfer());
            if (itm.getBusinessScope() != null &&
                    itm.getBusinessScope() == EBusinessScope.VERTEX.getValue()) {
                itm.setBusinessScopeVal(EBusinessScope.VERTEX.getLabel());
            } else {
                itm.setBusinessScopeVal(EBusinessScope.MEMBER.getLabel());
            }
        });

        List<UpPolicyCurrencyVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            Date date = new Date();
            upPolicyVO.setCreationTime(date);
            upPolicyVO.setPkCreator(SecurityUtils.getUserId());
            upPolicyVO.setPkCountry(pkCountry);
            // 查询国家
            for (UpPolicyCurrencyVO plc : list) {
                Integer count = cuMemberService.checkmsLogCount(plc.getPkMember(), EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                if (StringUtils.isNotNull(count) && count > 0) {
                    UpPolicyCurrencyVO erplc = BeanUtil.copyProperties(plc, UpPolicyCurrencyVO.class);
                    erplc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(erplc);
                    continue;
                }
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(plc.getPkMember(),
                        EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
                plc.setChangeNumber(approveNumber + 1);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                if (null == serviceChargeDTOR.getData() ||
                        null == serviceChargeDTOR.getData().getPkAccount()) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                }
                //接口查询金额是否足够
                plc.setPkAccount(serviceChargeDTOR.getData().getPkCountry());
                plc.setPkAccountKey(cuMemberBaseService.translateAccountValue(serviceChargeDTOR.getData().getPkAccount()));
                plc.setCost(serviceChargeDTOR.getData().getCost());
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(list);
    }


    /**
     * @description: 删除政策币发起签呈
     * @author: zhang jing
     * @date: 2024/4/23 14:40
     * @param: [upPolicyVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.UPDATE_POLICY_CURRENCY, method = EOperationMethod.SUBMIT)
    @PostMapping("/delPetition")
    public AjaxResult delPetition(@RequestBody UpPolicyCurrencyVO upPolicyVO) {
        if (StringUtils.isEmpty(upPolicyVO.getPkIdStr())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.POLICY_CURRENCY_NOT_NULL));
        }
        List<Long> pkIdList = Arrays.stream(upPolicyVO.getPkIdStr().split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());
        upPolicyVO.setPkIdList(pkIdList);
        Integer pkCountry = SecurityUtils.getPkCountry();
        upPolicyVO.setPkCountry(pkCountry);
        upPolicyVO.setApproveStatus(EApproveStatus.FINISH.getValue());
        List<UpPolicyCurrencyVO> list = cuMemberService.upPolicyCurrencyList(upPolicyVO);
        list.forEach(itm -> {
            UpPolicyCurrencyVO upc = JSONObject.parseObject(itm.getNewValue(), UpPolicyCurrencyVO.class);
            itm.setDeductMoney(upc.getDeductMoney());
            itm.setEnableStatus(upc.getEnableStatus());
            itm.setTransfer(upc.getTransfer());
            if (itm.getBusinessScope() != null &&
                    itm.getBusinessScope() == EBusinessScope.VERTEX.getValue()) {
                itm.setBusinessScopeVal(EBusinessScope.VERTEX.getLabel());
            } else {
                itm.setBusinessScopeVal(EBusinessScope.MEMBER.getLabel());
            }
        });

        List<UpPolicyCurrencyVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(list)) {
            Date date = new Date();
            upPolicyVO.setCreationTime(date);
            upPolicyVO.setPkCreator(SecurityUtils.getUserId());
            upPolicyVO.setPkCountry(pkCountry);
            Set<Long> pkMemberIds = new HashSet<>();
            // 查询国家
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();

            for (UpPolicyCurrencyVO plc : list) {

                Integer count = cuMemberService.checkmsLogCount(plc.getPkMember(), EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                if (StringUtils.isNotNull(count) && count > 0) {
                    UpPolicyCurrencyVO erplc = BeanUtil.copyProperties(plc, UpPolicyCurrencyVO.class);
                    erplc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(erplc);
                    continue;
                }
                pkMemberIds.add(plc.getPkMember());

                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(plc.getPkMember(),
                        EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue(), EApproveStatus.FINISH.getValue());
                plc.setChangeNumber(approveNumber + 1);
                if (upPolicyVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        upPolicyVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.DEL_POLICY_CURRENCY_YES_NO.getValue());
                    serviceChargeDTO.setQuantity(approveNumber + 1);
                    serviceChargeDTO.setPkCountry(pkCountry);
                    R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                    if (null == serviceChargeDTOR.getData() ||
                            null == serviceChargeDTOR.getData().getPkAccount()) {
                        return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BUSINESS_ACCOUNT_IS_NULL));
                    }
                    //接口查询金额是否足够
                    businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    businessCommissionDTO.setPkCountry(pkCountry);
                    MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                    memberAmountDTO.setPkMember(plc.getPkMember());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    plc.setCost(serviceChargeDTOR.getData().getCost());
                    plc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    upPolicyVO.setMemberAmountDTOList(memberAmountDTOList);
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            //去掉重复数据
            HashSet<MemberAmountDTO> setMemberAmountDTOList = new HashSet<>(memberAmountDTOList);
            memberAmountDTOList = new ArrayList<>(setMemberAmountDTOList);
            upPolicyVO.setPlculist(list);
            upPolicyVO.setPkMemberList(pkMemberIds);
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            businessCommissionDTO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            upPolicyVO.setPkAccount(upPolicyVO.getPlculist().get(0).getPkAccount());
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    memberBalanceList.forEach(itm -> {
                        UpPolicyCurrencyVO plc = BeanUtil.copyProperties(itm, UpPolicyCurrencyVO.class);
                        plc.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT));
                        errorlist.add(plc);
                    });
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            upPolicyVO = cuMemberService.delPolicyCurrency(upPolicyVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(upPolicyVO);
    }


}
