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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.MemberBonusFieldConstants;
import com.hzs.common.core.constant.MemberFieldConstants;
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.domain.member.bonus.CuMemberBonus;
import com.hzs.common.domain.system.base.BdCountry;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.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.ICuMemberBankService;
import com.hzs.member.account.service.ICuMemberBaseService;
import com.hzs.member.account.service.ICuMemberTradeService;
import com.hzs.member.account.vo.CuMemberBankVO;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.ImportSettleCountryVO;
import com.hzs.member.base.vo.UpdateSettleCountryVO;
import com.hzs.member.bonus.service.ICuMemberBonusService;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.member.detail.vo.CuMemberServiceLogVO;
import com.hzs.system.base.ICountryServiceApi;
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.util.*;

/**
 * @description: 特殊配置-修改结算国
 * @author: zhang jing
 * @date: 2022/12/29 11:39
 * @param:
 * @return:
 **/
@RequestMapping("/manage/update-settle-country")
@RestController
public class UpdateSettleCountryController extends BaseController {

    @Autowired
    private ICuMemberService cuMemberService;

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

    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IServiceChargeServiceApi serviceChargeServiceApi;
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @Autowired
    private ICuMemberBonusService memberBonusService;
    @Autowired
    private ICuMemberBankService cuMemberBankService;
    @DubboReference
    private ICountryServiceApi countryServiceApi;
    @Autowired
    private ICuMemberBaseService cuMemberBaseService;


    /**
     * @description: 特殊业务-修改结算国列表
     * @author: zhang jing
     * @date: 2022/11/17 15:39
     * @param: []
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.SELECT)
    @GetMapping("/upseCountryList")
    public TableDataInfo upseCountryList(UpdateSettleCountryVO upseCountryVO) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        upseCountryVO.setPkCountry(pkCountry);
        upseCountryVO.setApproveStatus(EApproveStatus.FINISH.getValue());
        List<UpdateSettleCountryVO> list = cuMemberService.upsettleCountryList(upseCountryVO);
        return getDataTable(list);
    }

    /**
     * 导出
     *
     * @param response
     * @param upseCountryVO
     */
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UpdateSettleCountryVO upseCountryVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        upseCountryVO.setPkCountry(pkCountry);
        List<UpdateSettleCountryVO> list = cuMemberService.upsettleCountryList(upseCountryVO);
        ExcelUtil<UpdateSettleCountryVO> util = new ExcelUtil<>(UpdateSettleCountryVO.class);
        util.exportExcel(response, list, "导出修改结算国");
    }

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

    /**
     * @description: 查询选中的会员信息
     * @author: zhang jing
     * @date: 2023/3/30 11:19
     * @param: [upseCountryVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.SELECT)
    @PostMapping("/selected")
    public AjaxResult selected(@RequestBody UpdateSettleCountryVO upseCountryVO) {
        if (CollectionUtil.isEmpty(upseCountryVO.getPkMemberList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
        }
        List<UpdateSettleCountryVO> newlist = new ArrayList<>();
        R<Map<Integer, BdCountry>> countryAllMap = countryServiceApi.getAllCountryMap();
        Integer pkCountry = SecurityUtils.getPkCountry();
        for (Long pkId : upseCountryVO.getPkMemberList()) {
            CuMember cuMember = cuMemberService.getMember(pkId);
            if (StringUtils.isNull(cuMember)) {
                UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(cuMember, UpdateSettleCountryVO.class);
                countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            } else {
                UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(cuMember, UpdateSettleCountryVO.class);
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(countryVO.getPkId(),
                        EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue(), EApproveStatus.FINISH.getValue());
                countryVO.setChangeNumber(approveNumber + 1);
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.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());
                BdCountry oldCountry = countryAllMap.getData().get(countryVO.getPkSettleCountry());
                countryVO.setOldValue(oldCountry.getShortName());
                newlist.add(countryVO);
            }
        }
        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.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<ImportSettleCountryVO> util = new ExcelUtil<>(ImportSettleCountryVO.class);
        List<ImportSettleCountryVO> list = util.importExcel(file.getInputStream());
        List<UpdateSettleCountryVO> errorlist = new ArrayList<>();
        List<UpdateSettleCountryVO> newlist = new ArrayList<>();
        List<Long> pkMemberList = new ArrayList<>();
        R<Map<Integer, BdCountry>> countryAllMap = countryServiceApi.getAllCountryMap();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (CollectionUtil.isNotEmpty(list)) {
            for (ImportSettleCountryVO ucv : list) {
                if (StringUtils.isNull(ucv.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(ucv.getNewValue())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_COUNTRY_NEW_NOT_NULL));
                }
                if (StringUtils.isNotNull(countryAllMap.getData())) {
                    // 1.通过keySet
                    for (Integer key : countryAllMap.getData().keySet()) {
                        BdCountry value = countryAllMap.getData().get(key);
                        if (value.getShortName().equals(ucv.getNewValue())) {
                            ucv.setNewValue(key.toString());
                            break;
                        }
                    }
                }
                CuMember cuMember = cuMemberService.getMember(ucv.getMemberCode());
                if (StringUtils.isNull(cuMember)) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(ucv, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
                    errorlist.add(countryVO);
                } else {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(cuMember, UpdateSettleCountryVO.class);
                    //当前最大次数
                    Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(countryVO.getPkId(),
                            EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue(), EApproveStatus.FINISH.getValue());
                    countryVO.setChangeNumber(approveNumber + 1);
                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.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());
                    BdCountry oldCountry = countryAllMap.getData().get(countryVO.getPkSettleCountry());
                    countryVO.setShortName(oldCountry.getShortName());
                    countryVO.setOldValue(oldCountry.getShortName());
                    countryVO.setNewPkSettleCountry(Integer.parseInt(ucv.getNewValue()));
                    newlist.add(countryVO);
                    pkMemberList.add(countryVO.getPkId());
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR, errorlist));
            }
            CuMemberServiceLogVO cuMemberServiceLogVO = new CuMemberServiceLogVO();
            cuMemberServiceLogVO.setPkMemberList(pkMemberList);
            cuMemberServiceLogVO.setEditType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
            List<CuMemberServiceLogVO> cslList = memberServiceLogService.selectServiceLogList(cuMemberServiceLogVO);
            if (CollectionUtil.isNotEmpty(cslList)) {
                cslList.forEach(itm -> {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(itm, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(countryVO);
                });
            }
        }
        if (CollectionUtil.isNotEmpty(errorlist)) {
            return AjaxResult.error(504, TransactionUtils.getContent(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.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.SUBMIT)
    @PostMapping("/updateSettleCountry")
    public AjaxResult updateSettleCountry(@RequestBody UpdateSettleCountryVO upseCountryVO) {

        if (StringUtils.isNull(upseCountryVO.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        List<UpdateSettleCountryVO> errorlist = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(upseCountryVO.getUpstcyVOList())) {
            Integer pkCountry = SecurityUtils.getPkCountry();
            /**
             * 修改结算国集合签呈页面
             */
            List<UpdateSettleCountryVO> upstcyVOWebList = new ArrayList<>();
            Set<Long> pkMemberIds = new HashSet<>();
            // 查询国家
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            R<Map<Integer, BdCountry>> countryAllMap = countryServiceApi.getAllCountryMap();
            for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
                if (StringUtils.isEmpty(uc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getNewPkSettleCountry())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_COUNTRY_NEW_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkSettleCountry())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_COUNTRY_OLD_NOT_NULL));
                }
                pkMemberIds.add(uc.getPkId());
                QueryWrapper<CuMemberBonus> queryWrapper = new QueryWrapper();
                List<Integer> grantStatus = new ArrayList<>();
                grantStatus.add(EGrantStatus.SETTLED.getValue());
                grantStatus.add(EGrantStatus.PUBLISHED.getValue());
                queryWrapper.eq(MemberFieldConstants.PK_MEMBER, uc.getPkId());
                queryWrapper.in(MemberBonusFieldConstants.GRANT_STATUS, grantStatus);
                queryWrapper.gt("REAL_INCOME_TOTAL", BigDecimal.ZERO);
                List<CuMemberBonus> listBonus = memberBonusService.list(queryWrapper);
                if (CollectionUtil.isNotEmpty(listBonus)) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.BONUS_SETTLE_NOT_COMPLETED));
                    errorlist.add(countryVO);
                    continue;
                }
                Integer checkMemberAchieveCount = cuMemberService.checkMemberAchieveCount(uc.getPkId());
                if (checkMemberAchieveCount > 0) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_ACHIEVE_REPEAT));
                    errorlist.add(countryVO);
                    continue;
                }
                Integer mslogCount = cuMemberService.checkmsLogCount(uc.getPkId(), EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
                if (mslogCount > 0) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                    errorlist.add(countryVO);
                    continue;
                }
                Integer accountCount = cuMemberService.checkAccount(uc.getPkId());
                if (accountCount > 0) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_ACCOUNT_NOT_ZERO));
                    errorlist.add(countryVO);
                    continue;
                }
                Integer cechargeCount = cuMemberService.checkCecharge(uc.getPkId());
                if (cechargeCount > 0) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CECHARGE_REPEAT));
                    errorlist.add(countryVO);
                    continue;
                }
                Integer withdrawCount = cuMemberService.checkWithdraw(uc.getPkId());
                if (withdrawCount > 0) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_WITHDRAW_REPEAT));
                    errorlist.add(countryVO);
                    continue;
                }
                CuMemberBankVO memberBankVO = cuMemberBankService.isBindBank(uc.getPkId(), pkCountry);
                if (null != memberBankVO && null != memberBankVO.getPkId()) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BINDING_BANK));
                    errorlist.add(countryVO);
                    continue;
                }
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkId(),
                        EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue(), EApproveStatus.FINISH.getValue());
                uc.setChangeNumber(approveNumber + 1);
                if (upseCountryVO.getProcessType() == EProcessType.AVOIDSIGNING.getValue() ||
                        upseCountryVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {

                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.UPDATE_SETTLE_COUNTRY.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(uc.getPkId());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    uc.setCost(serviceChargeDTOR.getData().getCost());
                    uc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                    upseCountryVO.setMemberAmountDTOList(memberAmountDTOList);
                }
                UpdateSettleCountryVO upstcyVOWeb = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                BdCountry oldCountry = countryAllMap.getData().get(uc.getPkSettleCountry());
                BdCountry newCountry = countryAllMap.getData().get(uc.getNewPkSettleCountry());
                upstcyVOWeb.setNewValue(newCountry.getShortName());
                upstcyVOWeb.setOldValue(oldCountry.getShortName());
                upstcyVOWebList.add(upstcyVOWeb);
            }

            upseCountryVO.setUpdateParentParamList(upstcyVOWebList);
            upseCountryVO.setPkMemberList(pkMemberIds);
            businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
            businessCommissionDTO.setPkAccount(upseCountryVO.getUpstcyVOList().get(0).getPkAccount());
            upseCountryVO.setPkAccount(upseCountryVO.getUpstcyVOList().get(0).getPkAccount());
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }
            if (CollectionUtil.isNotEmpty(errorlist)) {
                return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
            }
            upseCountryVO = cuMemberService.updateSettleCountry(upseCountryVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(upseCountryVO);
    }

    /**
     * @description: 发起签呈
     * @author: zhang jing
     * @date: 2023/3/22 17:20
     * @param: [upseCountryVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_SETTLE_COUNTRY, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody UpdateSettleCountryVO upseCountryVO) {
        UpdateSettleCountryVO updateCodeNewVO;

        if (CollectionUtil.isNotEmpty(upseCountryVO.getUpstcyVOList())) {
            Integer pkCountry = SecurityUtils.getPkCountry();
            if (StringUtils.isNull(upseCountryVO.getProcessType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
            }
            if (CollectionUtil.isEmpty(upseCountryVO.getUserIdList())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
            }
            if (StringUtils.isNull(upseCountryVO.getSignType())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
            }

            List<UpdateSettleCountryVO> errorlist = new ArrayList<>();
            BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
            List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
            for (UpdateSettleCountryVO uc : upseCountryVO.getUpstcyVOList()) {
                if (StringUtils.isEmpty(uc.getMemberCode())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getNewPkSettleCountry())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_COUNTRY_NEW_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkId())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PKID_NOT_NULL));
                }
                if (StringUtils.isNull(uc.getPkSettleCountry())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SETTLE_COUNTRY_OLD_NOT_NULL));
                }
                QueryWrapper<CuMemberBonus> queryWrapper = new QueryWrapper();
                queryWrapper.eq(MemberFieldConstants.PK_MEMBER, uc.getPkId());
                queryWrapper.ne(MemberBonusFieldConstants.GRANT_STATUS, EGrantStatus.SETTLED.getValue());
                queryWrapper.gt("REAL_INCOME_TOTAL", BigDecimal.ZERO);
                List<CuMemberBonus> listBonus = memberBonusService.list(queryWrapper);
                if (CollectionUtil.isNotEmpty(listBonus)) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.BONUS_SETTLE_NOT_COMPLETED));
                }
                Integer checkMemberAchieveCount = cuMemberService.checkMemberAchieveCount(uc.getPkId());
                if (checkMemberAchieveCount > 0) {
                    return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_ACHIEVE_REPEAT));
                }
                Integer mslogCount = cuMemberService.checkmsLogCount(uc.getPkId(), EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue());
                if (mslogCount > 0) {
                    return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
                }
                Integer accountCount = cuMemberService.checkAccount(uc.getPkId());
                if (accountCount > 0) {
                    return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_ACCOUNT_NOT_ZERO));
                }
                Integer cechargeCount = cuMemberService.checkCecharge(uc.getPkId());
                if (cechargeCount > 0) {
                    return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CECHARGE_REPEAT));
                }
                Integer withdrawCount = cuMemberService.checkWithdraw(uc.getPkId());
                if (withdrawCount > 0) {
                    return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_WITHDRAW_REPEAT));
                }
                CuMemberBankVO memberBankVO = cuMemberBankService.isBindBank(uc.getPkId(), pkCountry);
                if (StringUtils.isNotNull(memberBankVO)) {
                    UpdateSettleCountryVO countryVO = BeanUtil.copyProperties(uc, UpdateSettleCountryVO.class);
                    countryVO.setErrorMsg(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BINDING_BANK));
                    errorlist.add(countryVO);
                    continue;
                }
                if (CollectionUtil.isNotEmpty(errorlist)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_ERROR), errorlist);
                }
                //当前最大次数
                Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkId(),
                        EApprovalBusiness.UPDATE_SETTLE_COUNTRY.getValue(), EApproveStatus.FINISH.getValue());
                uc.setChangeNumber(approveNumber + 1);
                if (upseCountryVO.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {

                    //查询扣费金额，账户信息
                    ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                    serviceChargeDTO.setType(EApprovalBusiness.CHANGE_MEMBER_CODE.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(uc.getPkId());
                    memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                    uc.setCost(serviceChargeDTOR.getData().getCost());
                    uc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    upseCountryVO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                    memberAmountDTOList.add(memberAmountDTO);
                }
            }
            if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                upseCountryVO.setMemberAmountDTOList(memberAmountDTOList);
                //接口查询金额是否足够
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }
            updateCodeNewVO = cuMemberService.petition(upseCountryVO);
        } else {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        return AjaxResult.success(updateCodeNewVO);
    }


}
