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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.CommonUtil;
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.domain.member.base.CuMember;
import com.hzs.common.domain.member.detail.CuMemberServiceLog;
import com.hzs.common.domain.member.detail.CuMemberServiceLogExt;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.system.config.BdAccount;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.account.IBusinessCommission;
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.ICuMemberTradeService;
import com.hzs.member.base.param.*;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.*;
import com.hzs.member.detail.service.ICuMemberServiceLogService;
import com.hzs.system.config.IAccountServiceApi;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IServiceChargeServiceApi;
import com.hzs.system.config.IVertexServiceApi;
import com.hzs.system.config.dto.ServiceChargeDTO;
import com.hzs.system.config.dto.VertexDTO;
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.function.Function;
import java.util.stream.Collectors;

/**
 * @Description: 修改安置关系控制器
 * @Author: yuhui
 * @Time: 2023/1/4 15:40
 * @Classname: UpdatePlaceParentController
 * @PackageName: com.hzs.member.base.controller.manager
 */
@RequestMapping("/manage/update-place-parent")
@RestController
public class UpdatePlaceParentController extends BaseController {
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @DubboReference
    private IServiceChargeServiceApi serviceChargeServiceApi;
    @DubboReference
    private IAccountServiceApi accountServiceApi;
    @Autowired
    private ICuMemberServiceLogService cuMemberServiceLogService;
    @Autowired
    private ICuMemberService cuMemberService;
    @DubboReference
    private IBusinessCommission businessCommission;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IAwardsServiceApi awardsServiceApi;
    @DubboReference
    private IVertexServiceApi vertexServiceApi;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    /**
     * 安置关系记录列表
     *
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(String memberCode, String memberName, Integer approveStatus) {
        startPage();
        // 奖衔
        R<List<BdAwards>> awardsData = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        Map<Integer, BdAwards> awardsMap = awardsData.getData().stream().collect(Collectors.toMap(BdAwards::getPkId, Function.identity()));
        // 体系
        R<List<VertexDTO>> vertexDto = vertexServiceApi.findAll();
        Map<Integer, VertexDTO> vertexMap = vertexDto.getData().stream().collect(Collectors.toMap(VertexDTO::getPkId, Function.identity()));
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());

        CuMemberServiceLogExt memberServiceLogExt = new CuMemberServiceLogExt();
        memberServiceLogExt.setEditType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
        memberServiceLogExt.setPkCountry(SecurityUtils.getPkCountry());
        memberServiceLogExt.setMemberCode(memberCode);
        memberServiceLogExt.setMemberName(memberName);
        memberServiceLogExt.setApproveStatus(approveStatus);
        List<CuMemberServiceLogExt> list = cuMemberServiceLogService.selectByList(memberServiceLogExt);

        List<UpdatePlaceParentVo> resultList = new ArrayList<>();
        for (CuMemberServiceLog cuMemberServiceLog : list) {
            CuMember member = cuMemberService.getMemberById(cuMemberServiceLog.getPkMember());
            if (member == null) {
                member = new CuMember();
            }

            UpdatePlaceParentVo updatePlaceParentVo = new UpdatePlaceParentVo();
            updatePlaceParentVo.setApproveStatusVal(transactionMap.get(EnumsPrefixConstants.APPROVE_STATUS + cuMemberServiceLog.getApproveStatus()));
            updatePlaceParentVo.setPkMember(cuMemberServiceLog.getPkMember());
            updatePlaceParentVo.setMemberCode(member.getMemberCode());
            updatePlaceParentVo.setMemberName(member.getMemberName());
            updatePlaceParentVo.setTeamCode(member.getPkTeamCode());
            updatePlaceParentVo.setPhone(member.getPhone());
            // 奖衔
            if (awardsMap.get(member.getPkAwards()) != null) {
                updatePlaceParentVo.setAwardsVal(awardsMap.get(member.getPkAwards()).getAwardsName());
            }
            // 体系
            if (member.getPkVertex() != null) {
                if (vertexMap.get(member.getPkVertex().intValue()) != null) {
                    updatePlaceParentVo.setVertexVal(vertexMap.get(member.getPkVertex().intValue()).getVertexName());
                }
            }

            if (StringUtils.isNotBlank(cuMemberServiceLog.getOldValue()) && JSONUtil.isJson(cuMemberServiceLog.getOldValue())) {
                JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getOldValue());
                String placeMemberCode = jsonObject.getString("placeMemberCode");
                //  CuMemberExt memberByCode = cuMemberService.getMemberByCode(placeMemberCode);
                // TODO 查询 修改为 批量查询 煎炒 查询次数
                CuMemberExt memberByCode = cuMemberService.getMemberByCodeNotDel(placeMemberCode);
                if (memberByCode != null) {
                    updatePlaceParentVo.setParMemberCode(memberByCode.getMemberCode());
                    updatePlaceParentVo.setParMemberName(memberByCode.getMemberName());
                }
                if (member.getPlaceDept() != null) {
                    updatePlaceParentVo.setPlaceDeptVal(jsonObject.getString("placeDept"));
                }

            }
            if (StringUtils.isNotBlank(cuMemberServiceLog.getNewValue()) && JSONUtil.isJson(cuMemberServiceLog.getNewValue())) {
                JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getNewValue());
                String placeMemberCode = jsonObject.getString("placeMemberCode");
                Integer placeDept = jsonObject.getInteger("placeDept");
                updatePlaceParentVo.setEditNewPlaceMemberCode(placeMemberCode);
                CuMember newMember = cuMemberService.getMemberByCode(placeMemberCode);
                if (newMember != null) {
                    updatePlaceParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                    if (placeDept != null) {
                        updatePlaceParentVo.setEditNewPlaceDeptStr(placeDept.toString());
                    }
                }

            }

            updatePlaceParentVo.setPlaceDept(member.getPlaceDept());


            updatePlaceParentVo.setEditNumber(cuMemberServiceLog.getApproveNumber());
            updatePlaceParentVo.setEditDate(cuMemberServiceLog.getCreationTime());
            resultList.add(updatePlaceParentVo);
        }
        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
        //  return getDataTable(resultList);
    }

    /**
     * 导出
     *
     * @param
     * @return
     */
    @PostMapping("export")
    public void export(HttpServletResponse response) {
        // 奖衔
        R<List<BdAwards>> awardsData = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        Map<Integer, BdAwards> awardsMap = awardsData.getData().stream().collect(Collectors.toMap(BdAwards::getPkId, Function.identity()));
        // 体系
        R<List<VertexDTO>> vertexDto = vertexServiceApi.findAll();
        Map<Integer, VertexDTO> vertexMap = vertexDto.getData().stream().collect(Collectors.toMap(VertexDTO::getPkId, Function.identity()));
        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
        List<CuMemberServiceLog> list = cuMemberServiceLogService.list(queryWrapper);
        List<UpdatePlaceParentVo> resultList = new ArrayList<>();
        for (CuMemberServiceLog cuMemberServiceLog : list) {
            CuMember member = cuMemberService.getMemberById(cuMemberServiceLog.getPkMember());
            UpdatePlaceParentVo updatePlaceParentVo = new UpdatePlaceParentVo();
            updatePlaceParentVo.setPkMember(cuMemberServiceLog.getPkMember());
            updatePlaceParentVo.setMemberCode(member.getMemberCode());
            updatePlaceParentVo.setMemberName(member.getMemberName());
            updatePlaceParentVo.setTeamCode(member.getPkTeamCode());
            updatePlaceParentVo.setPhone(member.getPhone());
            // 奖衔
            if (awardsMap.get(member.getPkAwards()) != null) {
                updatePlaceParentVo.setAwardsVal(awardsMap.get(member.getPkAwards()).getAwardsName());
            }
            // 体系
            if (member.getPkVertex() != null) {
                if (vertexMap.get(member.getPkVertex().intValue()) != null) {
                    updatePlaceParentVo.setVertexVal(vertexMap.get(member.getPkVertex().intValue()).getVertexName());
                }
            }
            if (StringUtils.isNotBlank(cuMemberServiceLog.getOldValue())) {
                JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getOldValue());
                updatePlaceParentVo.setParMemberCode(jsonObject.getString("placeMemberCode"));
                updatePlaceParentVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(member.getPlaceDept()));
            }
            if (StringUtils.isNotBlank(cuMemberServiceLog.getNewValue())) {
                JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getNewValue());
                String placeMemberCode = jsonObject.getString("placeMemberCode");
                Integer placeDept = jsonObject.getInteger("placeDept");
                updatePlaceParentVo.setEditNewPlaceMemberCode(placeMemberCode);
                CuMember newMember = cuMemberService.getMember(cuMemberServiceLog.getPkMember());
                updatePlaceParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                if (placeDept != null) {
                    updatePlaceParentVo.setEditNewPlaceDept(placeDept);
                    updatePlaceParentVo.setEditNewPlaceDeptStr(EPlaceDept.getEPlaceDept(placeDept));
                }
            }
            updatePlaceParentVo.setParMemberName(member.getMemberName());
            updatePlaceParentVo.setPlaceDept(member.getPlaceDept());
            updatePlaceParentVo.setEditNumber(cuMemberServiceLog.getApproveNumber());
            updatePlaceParentVo.setEditDate(cuMemberServiceLog.getCreationTime());
            resultList.add(updatePlaceParentVo);
        }
        ExcelUtil<UpdatePlaceParentVo> util = new ExcelUtil<>(UpdatePlaceParentVo.class);
        util.exportExcel(response, resultList, "修改安置导出");
    }

    /**
     * 修改安置关系
     *
     * @return
     */
    @PostMapping("update-place-parent")
    public AjaxResult updatePlaceParent(@RequestBody PlaceParentParam placeParentParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 校验编号是否存在
        for (UpdatePlaceParentParam updateParentParam : placeParentParam.getUpdatePlaceParentList()) {
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            CuMember member = cuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = cuMemberService.getMemberByCode(updateParentParam.getEditNewPlaceMemberCode());
            if (parentMember == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            // 安置位置需要从下向上可以找到安置树订单 如果找不到顶点则不可添加节点
            // 变更后安置编号
            String editNewPlaceMemberCode = updateParentParam.getEditNewPlaceMemberCode();
            Integer editNewPlaceDept = updateParentParam.getEditNewPlaceDept();
            if (editNewPlaceDept == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PLACE_DEPT_NOT_NULL));
            }
            //校验新安置部门和安置编号下是否已存在节点
            Long placeDeptCount = cuMemberService.checkPlaceDeptAndMemberCode(editNewPlaceMemberCode, editNewPlaceDept);
            if (placeDeptCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PLACE_PARENT_OCCUPY));
            }
            // 安置位置需要从下向上可以找到安置树订单 如果找不到顶点则不可添加节点
            queryWrapper.eq("PK_MEMBER", member.getPkId());
            int count = cuMemberServiceLogService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
            QueryWrapper<CuMemberServiceLog> query = new QueryWrapper<>();
            query.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            query.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            query.eq("PK_MEMBER", member.getPkId());
            int ct = memberServiceLogService.count(query);
            if (ct > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(),
                    EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), null);
            updateParentParam.setChangeNumber(approveNumber + 1);
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            serviceChargeDTO.setQuantity(approveNumber + 1);
            serviceChargeDTO.setPkCountry(pkCountry);
            R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            updateParentParam.setCost(serviceChargeDTOR.getData().getCost());
            updateParentParam.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
            if (placeParentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue() || placeParentParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                memberAmountDTO.setPkMember(member.getPkId());
                memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                memberAmountDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                memberAmountDTO.setBusinessType(serviceChargeDTOR.getData().getType());
                memberAmountDTOList.add(memberAmountDTO);
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                placeParentParam.setMemberAmountDTOList(memberAmountDTOList);
                //接口查询金额是否足够
                R<List<MemberBalanceDTO>> memberBalanceList = businessCommission.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList.getData())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList.getData());
                }
            }

        }
        cuMemberService.updatePlaceParent(placeParentParam);
        return AjaxResult.success();
    }

    /**
     * 校验会员安置数据
     *
     * @param placeParentParam
     * @return
     */
    @PostMapping("check-member-place-parent")
    public AjaxResult checkMemberPlaceParent(@RequestBody PlaceParentParam placeParentParam) {
        // 校验编号是否存在
        for (UpdatePlaceParentParam updateParentParam : placeParentParam.getUpdatePlaceParentList()) {

            CuMember member = cuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = cuMemberService.getMemberByCode(updateParentParam.getEditNewPlaceMemberCode());
            if (parentMember == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            // 会员编号 和变更后会员编号存在重复
            if (updateParentParam.getMemberCode().equals(updateParentParam.getEditNewPlaceMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.UPDATE_MEMBER_CODE_REPEAT));
            }
            // 安置位置需要从下向上可以找到安置树订单 如果找不到顶点则不可添加节点
            // 变更后安置编号
            String editNewPlaceMemberCode = updateParentParam.getEditNewPlaceMemberCode();
            Integer editNewPlaceDept = updateParentParam.getEditNewPlaceDept();
            if (editNewPlaceDept == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PLACE_DEPT_NOT_NULL));
            }
            //校验新安置部门和安置编号下是否已存在节点
            Long placeDeptCount = cuMemberService.checkPlaceDeptAndMemberCode(editNewPlaceMemberCode, editNewPlaceDept);
            if (placeDeptCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PLACE_PARENT_OCCUPY));
            }

            QueryWrapper<CuMemberServiceLog> query = new QueryWrapper<>();
            query.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            query.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            query.eq("PK_MEMBER", member.getPkId());
            int ct = memberServiceLogService.count(query);
            if (ct > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取用户扣费详情
     *
     * @return
     */
    @PostMapping("get-member-charging-detail")
    public AjaxResult getMemberChargingDetail(@RequestBody MemberChargingDetailParam memberChargingDetailParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<UpdatePlaceParentVo> resultList = new ArrayList<>();
        for (MemberChargingDetailVo memberChargingDetailVo : memberChargingDetailParam.getMemberChargingDetailList()) {
            CuMember member = cuMemberService.getMember(memberChargingDetailVo.getPkMember());
            // 安置
            CuMember placeParentMember = cuMemberService.getMember(member.getPkPlaceParent());
            UpdatePlaceParentVo updatePlaceParentVo = new UpdatePlaceParentVo();
            updatePlaceParentVo.setMemberCode(member.getMemberCode());
            updatePlaceParentVo.setMemberName(member.getMemberName());
            updatePlaceParentVo.setParMemberCode(placeParentMember.getMemberCode());
            updatePlaceParentVo.setParMemberName(placeParentMember.getMemberName());
            updatePlaceParentVo.setPlaceDept(placeParentMember.getPlaceDept());
            updatePlaceParentVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(placeParentMember.getPlaceDept()));
            // 变更后
            CuMember newPlaceParentMember = cuMemberService.getMember(memberChargingDetailVo.getEditNewPlaceMemberCode());
            updatePlaceParentVo.setEditNewPlaceMemberCode(newPlaceParentMember.getMemberCode());
            updatePlaceParentVo.setEditNewPlaceMemberName(newPlaceParentMember.getMemberName());
            updatePlaceParentVo.setEditNewPlaceDept(newPlaceParentMember.getPlaceDept());
            updatePlaceParentVo.setEditNewPlaceDeptStr(EPlaceDept.getEPlaceDept(newPlaceParentMember.getPlaceDept()));
            //  TODO 扣款
            Integer quantity = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(), EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), EApproveStatus.FINISH.getValue());
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setPkCountry(pkCountry);
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            serviceChargeDTO.setQuantity(quantity + 1);
            R<ServiceChargeDTO> serviceCharge = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            R<BdAccount> account = accountServiceApi.getAccount(serviceCharge.getData().getPkAccount());
            updatePlaceParentVo.setPkAccount(serviceCharge.getData().getPkAccount());
            updatePlaceParentVo.setAccountName(account.getData().getAccountName());

            updatePlaceParentVo.setAccountAmount(serviceCharge.getData().getCost());
            resultList.add(updatePlaceParentVo);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 导入(前端展示使用)
     */
    @PostMapping("/import-service-log")
    public AjaxResult importServiceLog(MultipartFile file) throws Exception {
        Integer pkCountry = SecurityUtils.getPkCountry();
        ExcelUtil<MemberPlaceParentServiceLogVo> util = new ExcelUtil<>(MemberPlaceParentServiceLogVo.class);
        List<MemberPlaceParentServiceLogVo> list = util.importExcel(file.getInputStream());
        List<MemberPlaceParentServiceLogVo> resultList = new ArrayList<>();
        for (MemberPlaceParentServiceLogVo memberServiceLogVo : list) {
            if (StringUtils.isNotBlank(memberServiceLogVo.getMemberCode())) {
                CuMember member = cuMemberService.getMember(memberServiceLogVo.getMemberCode());
                memberServiceLogVo.setMemberName(member.getMemberName());
                // 变更前安置编号
                CuMember changeMember = cuMemberService.getMember(member.getPkPlaceParent());
                memberServiceLogVo.setPlaceMemberName(changeMember.getMemberName());
                memberServiceLogVo.setPlaceMemberCode(changeMember.getMemberCode());
                memberServiceLogVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(member.getPlaceDept()));
                Integer quantity = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(), EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), EApproveStatus.FINISH.getValue());
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setPkCountry(pkCountry);
                serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
                serviceChargeDTO.setQuantity(quantity + 1);
                R<ServiceChargeDTO> serviceCharge = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                R<BdAccount> account = accountServiceApi.getAccount(serviceCharge.getData().getPkAccount());
                memberServiceLogVo.setPkAccount(serviceCharge.getData().getPkAccount());
                memberServiceLogVo.setPkAccountKeyVal(account.getData().getAccountName());
                memberServiceLogVo.setCost(serviceCharge.getData().getCost());
                CuMember newMember = cuMemberService.getMember(memberServiceLogVo.getEditNewPlaceMemberCode());
                memberServiceLogVo.setEditNewPlaceMemberName(newMember.getMemberName());
                resultList.add(memberServiceLogVo);
            }
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 安置关系弹窗提交
     *
     * @return AjaxResult
     * @throws Exception
     */
    @PostMapping("/import-member-code")
    public AjaxResult importMemberCode(@RequestBody MemberServiceLogParam memberServiceLogParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuMemberServiceLog> resultList = new ArrayList<>();
        for (MemberServiceLogVo memberService : memberServiceLogParam.getMemberServiceLogList()) {
            String businessNo = CommonUtil.createSerialNumber(EOrderPrefix.UPDATE_PLACE_PARENT.getValue());

            String memberCode = memberService.getMemberCode();
            CuMember member = cuMemberService.getMember(memberCode);
            CuMemberServiceLog cuMemberServiceLog = new CuMemberServiceLog();
            cuMemberServiceLog.setPkMember(member.getPkId());
            cuMemberServiceLog.setEditType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
            JSONObject oldJson = new JSONObject();
            oldJson.put("changeMemberCode", memberService.getEditOldPlaceMemberCode());
            if (EPlaceDept.LEFT_DEPT.getLabel().equals(memberService.getEditOldPlaceDeptStr())) {
                oldJson.put("placeDept", EPlaceDept.LEFT_DEPT.getValue());
            } else if (EPlaceDept.RIGHT_DEPT.getLabel().equals(memberService.getEditOldPlaceDeptStr())) {
                oldJson.put("placeDept", EPlaceDept.RIGHT_DEPT.getValue());
            }

            cuMemberServiceLog.setOldValue(oldJson.toJSONString());
            JSONObject newJson = new JSONObject();
            newJson.put("newChangeMemberCode", memberService.getEditNewPlaceMemberCode());
            if (EPlaceDept.LEFT_DEPT.getLabel().equals(memberService.getEditNewPlaceDeptStr())) {
                newJson.put("newPlaceDept", EPlaceDept.LEFT_DEPT.getValue());
            } else if (EPlaceDept.RIGHT_DEPT.getLabel().equals(memberService.getEditNewPlaceDeptStr())) {
                newJson.put("newPlaceDept", EPlaceDept.RIGHT_DEPT.getValue());
            }
            //    newJson.put("newPlaceDept",memberService.getNewPlaceDept());
            cuMemberServiceLog.setNewValue(newJson.toJSONString());
            cuMemberServiceLog.setCreationTime(DateUtils.currentDateTime());
            cuMemberServiceLog.setPkCountry(SecurityUtils.getPkCountry());
            cuMemberServiceLog.setPkCreator(SecurityUtils.getUserId());
            cuMemberServiceLog.setBusinessNo(businessNo);
            cuMemberServiceLog.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());

            resultList.add(cuMemberServiceLog);
        }
        memberServiceLogService.saveBatch(resultList);
        return AjaxResult.success();
    }


    /**
     * 导出模板
     *
     * @param response
     */
    @PostMapping("get-service-export")
    public void getOrderListExport(HttpServletResponse response) {
        ExcelUtil<UpdatePlaceImport> util = new ExcelUtil<>(UpdatePlaceImport.class);
        util.exportExcel(response, new ArrayList<>(), "修改安置导出");
    }

    /**
     * @description: 发起签呈 免付，需要签呈需要付费
     * @author: yh
     * @date: 2023/3/4 11:06
     * @param: [updateCodeVO]
     * @return: com.hzs.common.core.web.domain.AjaxResult
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_RESETTLE, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody UpdatePlaceParentPetitionParam updatePlaceParentPetitionParam) {
        if (StringUtils.isEmpty(updatePlaceParentPetitionParam.getUpdateParentParamList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isNull(updatePlaceParentPetitionParam.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(updatePlaceParentPetitionParam.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(updatePlaceParentPetitionParam.getUserIdList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.EXAMINE_AND_APPROVE_NOT_NULL));
        }
        Integer pkCountry = SecurityUtils.getPkCountry();


        Set<Long> pkMemberIds = new HashSet<>();
        BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
        List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
        for (UpdatePlaceParentParam uc : updatePlaceParentPetitionParam.getUpdateParentParamList()) {
            if (StringUtils.isEmpty(uc.getMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
            }
            // 修改会员
            CuMember member = cuMemberService.getMemberByCode(uc.getMemberCode());
            // 添加 修改安置编号不能是安置伞下校验
            List<CuMemberExt> cuMemberExts = cuMemberService.queryPlaceSponsorUnderUmbrella(member.getPkId());
            Map<String, CuMemberExt> memberMap = cuMemberExts.stream().collect(Collectors.toMap(CuMemberExt::getMemberCode, Function.identity()));
            CuMemberExt cuMemberExt = memberMap.get(uc.getEditNewPlaceMemberCode());
            if (cuMemberExt != null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_EXIST_RELATION));
            }
            // 会员安置编号信息
            CuMember placeParentMember = cuMemberService.getMemberById(member.getPkPlaceParent());
            uc.setPkMember(member.getPkId());
            JSONObject oldJson = new JSONObject();
            oldJson.put("placeDept", member.getPlaceDept());
            if (placeParentMember != null) {
                oldJson.put("placeMemberCode", placeParentMember.getMemberCode());
            }

            uc.setOldValue(oldJson.toJSONString());

            uc.setEditNewPlaceDept(uc.getEditNewPlaceDept());

            JSONObject newJson = new JSONObject();
            newJson.put("placeDept", uc.getEditNewPlaceDept());
            newJson.put("placeMemberCode", uc.getEditNewPlaceMemberCode());
            uc.setNewValue(newJson.toJSONString());
            pkMemberIds.add(member.getPkId());
            if (StringUtils.isEmpty(uc.getEditNewPlaceMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NEW_NOT_NULL));
            }

            uc.setApproveStatus(EApproveStatus.ALREADY_SUBMIT.getValue());
            Integer count = cuMemberService.checkmsLogCount(uc.getPkMember(), EApproveStatus.ALREADY_SUBMIT.getValue());
            if (count > 0) {
                return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
            }
            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkMember(),
                    EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), null);
            uc.setChangeNumber(approveNumber + 1);
            if (updatePlaceParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {

                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue());
                serviceChargeDTO.setQuantity(approveNumber + 1);
                serviceChargeDTO.setPkCountry(pkCountry);
                R<ServiceChargeDTO> serviceChargeDTOR = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                //接口查询金额是否足够
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                MemberAmountDTO memberAmountDTO = new MemberAmountDTO();
                memberAmountDTO.setPkMember(uc.getPkMember());
                memberAmountDTO.setTradeAmount(serviceChargeDTOR.getData().getCost());
                uc.setCost(serviceChargeDTOR.getData().getCost());
                uc.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                memberAmountDTOList.add(memberAmountDTO);
            }
        }
        updatePlaceParentPetitionParam.setPkMemberList(pkMemberIds);
        updatePlaceParentPetitionParam.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
            //接口查询金额是否足够
            if (updatePlaceParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                List<MemberBalanceDTO> memberBalanceList = cuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }
        }
        cuMemberService.petitionUpdatePlaceParent(updatePlaceParentPetitionParam);

        return AjaxResult.success();
    }

}
