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

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.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.HttpStatus;
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.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
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.sale.order.ISaOrderServiceApi;
import com.hzs.sale.order.dto.MemberFirstOrderDTO;
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: 修改安置关系控制器
 */
@RequestMapping("/manage/update-place-parent")
@RestController
public class UpdatePlaceParentController extends BaseController {

    @Autowired
    private ICuMemberTradeService iCuMemberTradeService;
    @Autowired
    private ICuMemberServiceLogService iCuMemberServiceLogService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    IServiceChargeServiceApi iServiceChargeServiceApi;
    @DubboReference
    IAccountServiceApi iAccountServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    IVertexServiceApi iVertexServiceApi;
    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;
    @DubboReference
    IBusinessCommission iBusinessCommission;

    /**
     * 安置关系记录列表
     *
     * @return
     */
    @AccessPermissions("ModifyPlacement")
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_RESETTLE, method = EOperationMethod.SELECT)
    @GetMapping("/list")
    public TableDataInfo list(String memberCode, String memberName, Integer approveStatus) {
        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);

        startPage();
        List<CuMemberServiceLog> list = iCuMemberServiceLogService.selectByList(memberServiceLogExt);

        List<UpdatePlaceParentVo> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());
            // 奖衔
            R<List<BdAwards>> awardsData = iAwardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
            Map<Integer, BdAwards> awardsMap = awardsData.getData().stream().collect(Collectors.toMap(BdAwards::getPkId, Function.identity()));
            // 体系
            R<List<VertexDTO>> vertexDto = iVertexServiceApi.findAll();
            Map<Long, VertexDTO> vertexMap = vertexDto.getData().stream().collect(Collectors.toMap(VertexDTO::getPkId, Function.identity()));

            List<CuMember> pkIdMemberList = iCuMemberService.listByIds(list.stream().map(CuMemberServiceLog::getPkMember).collect(Collectors.toSet()));
            Map<Long, CuMember> pkMemberMap = pkIdMemberList.stream().collect(Collectors.toMap(CuMember::getPkId, val -> val));

            for (CuMemberServiceLog cuMemberServiceLog : list) {
                CuMember member = pkMemberMap.get(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()) != null) {
                        updatePlaceParentVo.setVertexVal(vertexMap.get(member.getPkVertex()).getVertexName());
                    }
                }

                if (StringUtils.isNotBlank(cuMemberServiceLog.getOldValue()) && JSONUtil.isJson(cuMemberServiceLog.getOldValue())) {
                    JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getOldValue());
                    String placeMemberCode = jsonObject.getString("placeMemberCode");
                    CuMemberExt memberByCode = iCuMemberService.getMemberByCode(placeMemberCode);
                    if (memberByCode != null) {
                        updatePlaceParentVo.setParMemberCode(memberByCode.getMemberCode());
                        if (member.getPlaceDept() != null) {
                            updatePlaceParentVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(jsonObject.getInteger("placeDept")));
                        }
                        updatePlaceParentVo.setParMemberName(memberByCode.getMemberName());
                    }
                }
                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 = iCuMemberService.getMember(placeMemberCode);
                    if (newMember != null) {
                        updatePlaceParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                        if (placeDept != null) {
                            updatePlaceParentVo.setEditNewPlaceDeptStr(EPlaceDept.getEPlaceDept(placeDept));
                        }
                    }
                }

                updatePlaceParentVo.setPlaceDept(member.getPlaceDept());
                updatePlaceParentVo.setEditNumber(cuMemberServiceLog.getApproveNumber());
                updatePlaceParentVo.setEditDate(cuMemberServiceLog.getCreationTime());
                resultList.add(updatePlaceParentVo);
            }

        }

        TableDataInfo tableDataInfo = getDataTable(list);
        tableDataInfo.setRows(resultList);
        return tableDataInfo;
    }

    /**
     * 导出
     *
     * @param
     * @return
     */
    @PostMapping("/export")
    public void export(String memberCode, String memberName, Integer approveStatus, HttpServletResponse response) {

        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<CuMemberServiceLog> list = iCuMemberServiceLogService.selectByList(memberServiceLogExt);

        List<UpdatePlaceParentVo> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(list)) {
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());
            // 奖衔
            R<List<BdAwards>> awardsData = iAwardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
            Map<Integer, BdAwards> awardsMap = awardsData.getData().stream().collect(Collectors.toMap(BdAwards::getPkId, Function.identity()));
            // 体系
            R<List<VertexDTO>> vertexDto = iVertexServiceApi.findAll();
            Map<Long, VertexDTO> vertexMap = vertexDto.getData().stream().collect(Collectors.toMap(VertexDTO::getPkId, Function.identity()));

            List<CuMember> pkIdMemberList = iCuMemberService.listByIds(list.stream().map(CuMemberServiceLog::getPkMember).collect(Collectors.toSet()));
            Map<Long, CuMember> pkMemberMap = pkIdMemberList.stream().collect(Collectors.toMap(CuMember::getPkId, val -> val));

            for (CuMemberServiceLog cuMemberServiceLog : list) {
                CuMember member = pkMemberMap.get(cuMemberServiceLog.getPkMember());
                if (member != null) {
                    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()) != null) {
                            updatePlaceParentVo.setVertexVal(vertexMap.get(member.getPkVertex()).getVertexName());
                        }
                    }
                    if (StringUtils.isNotBlank(cuMemberServiceLog.getOldValue()) && JSONUtil.isJson(cuMemberServiceLog.getOldValue())) {
                        JSONObject jsonObject = JSONObject.parseObject(cuMemberServiceLog.getOldValue());
                        String placeMemberCode = jsonObject.getString("placeMemberCode");
                        CuMemberExt memberByCode = iCuMemberService.getMemberByCode(placeMemberCode);
                        if (memberByCode != null) {
                            updatePlaceParentVo.setParMemberCode(memberByCode.getMemberCode());
                            if (member.getPlaceDept() != null) {
                                updatePlaceParentVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(jsonObject.getInteger("placeDept")));
                            }
                            updatePlaceParentVo.setParMemberName(memberByCode.getMemberName());
                        }
                    }
                    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 = iCuMemberService.getMember(placeMemberCode);
                        if (newMember != null) {
                            updatePlaceParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                            if (placeDept != null) {
                                updatePlaceParentVo.setEditNewPlaceDept(placeDept);
                                updatePlaceParentVo.setEditNewPlaceDeptStr(EPlaceDept.getEPlaceDept(placeDept));
                            }
                        }

                    }
                    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()) {

            CuMember member = iCuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = iCuMemberService.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 = iCuMemberService.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 = iCuMemberServiceLogService.count(query);
            if (ct > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
            //当前最大次数
            Integer approveNumber = iCuMemberServiceLogService.selectByMaxApproveNumber(member.getPkId(),
                    EApprovalBusiness.CU_MEMBER_PLACE_PARENT.getValue(), EApproveStatus.FINISH.getValue());
            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 = iServiceChargeServiceApi.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 = iBusinessCommission.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList.getData())) {
                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList.getData());
                }
            }

        }
        iCuMemberService.updatePlaceParent(placeParentParam);
        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 = iCuMemberService.getMember(memberChargingDetailVo.getPkMember());
            // 安置
            CuMember placeParentMember = iCuMemberService.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 = iCuMemberService.getMember(memberChargingDetailVo.getEditNewPlaceMemberCode());
            updatePlaceParentVo.setEditNewPlaceMemberCode(newPlaceParentMember.getMemberCode());
            updatePlaceParentVo.setEditNewPlaceMemberName(newPlaceParentMember.getMemberName());
            updatePlaceParentVo.setEditNewPlaceDept(newPlaceParentMember.getPlaceDept());
            updatePlaceParentVo.setEditNewPlaceDeptStr(EPlaceDept.getEPlaceDept(newPlaceParentMember.getPlaceDept()));
            //  TODO 扣款
            Integer quantity = iCuMemberServiceLogService.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 = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            R<BdAccount> account = iAccountServiceApi.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 = iCuMemberService.getMember(memberServiceLogVo.getMemberCode());
                memberServiceLogVo.setMemberName(member.getMemberName());
                // 变更前安置编号
                CuMember changeMember = iCuMemberService.getMember(member.getPkPlaceParent());
                memberServiceLogVo.setPlaceMemberName(changeMember.getMemberName());
                memberServiceLogVo.setPlaceMemberCode(changeMember.getMemberCode());
                memberServiceLogVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(member.getPlaceDept()));
                Integer quantity = iCuMemberServiceLogService.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 = iServiceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
                R<BdAccount> account = iAccountServiceApi.getAccount(serviceCharge.getData().getPkAccount());
                memberServiceLogVo.setPkAccount(serviceCharge.getData().getPkAccount());
                memberServiceLogVo.setPkAccountKeyVal(account.getData().getAccountName());
                memberServiceLogVo.setCost(serviceCharge.getData().getCost());
                CuMember newMember = iCuMemberService.getMember(memberServiceLogVo.getEditNewPlaceMemberCode());
                memberServiceLogVo.setEditNewPlaceMemberName(newMember.getMemberName());
                resultList.add(memberServiceLogVo);
            }
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 查询修改后编号是否在安置人伞下
     *
     * @param placeParentParam
     * @return
     */
    @PostMapping("/check-place-member")
    public AjaxResult checkPlaceMember(@RequestBody PlaceParentParam placeParentParam) {
        for (UpdatePlaceParentParam updateParentParam : placeParentParam.getUpdatePlaceParentList()) {
            CuMember member = iCuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            //查询修改后编号是否在安置人伞下
            Long count = iCuMemberService.checkPlaceMemberList(member.getPkParent(), updateParentParam.getEditNewPlaceMemberCode());
            // 查询推荐人安置伞下
            if (count == 0) {
                // TODO 让前端弹窗展示返回信息
                return AjaxResult.error(HttpStatus.FORBIDDEN, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_RECOMMENDED));
            }
        }
        return AjaxResult.success();
    }

    /**
     * 首单校验变为弹窗展示
     */
    @PostMapping("/check-member-first-order")
    public AjaxResult checkMemberFirstOrder(@RequestBody PlaceParentParam placeParentParam) {
        // 校验编号是否存在
        List<String> editNewMemberCodeList = new ArrayList<>();
        for (UpdatePlaceParentParam updateParentParam : placeParentParam.getUpdatePlaceParentList()) {
            if (updateParentParam.getEditNewPlaceDept().equals(EPlaceDept.RIGHT_DEPT.getValue())) {
                // 如果是安置右区 检验首单
                editNewMemberCodeList.add(updateParentParam.getEditNewPlaceMemberCode());
            }
        }
        if (editNewMemberCodeList.size() > 0) {
            // 如果是安置到右区 校验是否首单
            List<MemberFirstOrderDTO> memberFirstOrderDTOList = iSaOrderServiceApi.checkMemberIsFirstOrder(editNewMemberCodeList);
            for (MemberFirstOrderDTO memberFirstOrderDTO : memberFirstOrderDTOList) {
                if (memberFirstOrderDTO.getOrderCount() == 0) {
                    // 没有首单 校验
                    return AjaxResult.success(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_FIRST_ORDER));
                }
            }
        }
        return AjaxResult.success("");
    }

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

            CuMember member = iCuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = iCuMemberService.getMember(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 = iCuMemberService.checkPlaceDeptAndMemberCode(editNewPlaceMemberCode, editNewPlaceDept);
            if (placeDeptCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PLACE_PARENT_OCCUPY));
            }

            // 不能是自己的安置伞下
            Long checkCount = iCuMemberService.checkPlaceMemberList(member.getPkId(), updateParentParam.getEditNewPlaceMemberCode());
            if (checkCount >= 1) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CAN_ONLY_BE_PLACE_PARENT));
            }
//            if (updateParentParam.getEditNewPlaceDept().equals(EPlaceDept.RIGHT_DEPT.getValue())){
//                // 如果是安置右区 检验首单
//                editNewMemberCodeList.add(updateParentParam.getEditNewPlaceMemberCode());
//            }

            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 = iCuMemberServiceLogService.count(query);
            if (ct > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
        }

        //安置右区 是否存在首个注册单校验
//        if (editNewMemberCodeList.size() > 0){
//            // 如果是安置到右区 校验是否首单
//            List<MemberFirstOrderDTO> memberFirstOrderDTOList = iSaOrderServiceApi.checkMemberIsFirstOrder(editNewMemberCodeList);
//            for (MemberFirstOrderDTO memberFirstOrderDTO : memberFirstOrderDTOList) {
//                if (memberFirstOrderDTO.getOrderCount() == 0){
//                    // 没有首单 校验
//                    return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_FIRST_ORDER));
//                }
//            }
//        }

        return AjaxResult.success();
    }

    /**
     * 安置关系弹窗提交
     *
     * @return AjaxResult
     * @throws Exception
     */
    @PostMapping("/import-member-code")
    public AjaxResult importMemberCode(@RequestBody MemberServiceLogParam memberServiceLogParam) {
        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 = iCuMemberService.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);
        }
        iCuMemberServiceLogService.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: 发起签呈 免付，需要签呈需要付费
     **/
    @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 = iCuMemberService.getMemberByCode(uc.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = iCuMemberService.getMemberByCode(uc.getEditNewPlaceMemberCode());
            if (parentMember == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            // 变更后安置编号
            String editNewPlaceMemberCode = uc.getEditNewPlaceMemberCode();
            Integer editNewPlaceDept = uc.getEditNewPlaceDept();
            if (editNewPlaceDept == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PLACE_DEPT_NOT_NULL));
            }
            //校验新安置部门和安置编号下是否已存在节点
            Long placeDeptCount = iCuMemberService.checkPlaceDeptAndMemberCode(editNewPlaceMemberCode, editNewPlaceDept);
            if (placeDeptCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PLACE_PARENT_OCCUPY));
            }


            // 添加 修改安置编号不能是安置伞下校验
//            List<CuMemberExt> cuMemberExts = iCuMemberService.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));
//            }
            if (uc.getEditNewPlaceDept() == null) {
                // 安置部门
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PLACE_DEPT_NOT_NULL));
            }

            // 会员安置编号信息
            CuMember placeParentMember = iCuMemberService.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());
            if (EPlaceDept.LEFT_DEPT.getLabel().equals(uc.getEditNewPlaceDeptStr())) {
                uc.setEditNewPlaceDept(EPlaceDept.LEFT_DEPT.getValue());
            } else if (EPlaceDept.RIGHT_DEPT.getLabel().equals(uc.getEditNewPlaceDeptStr())) {
                uc.setEditNewPlaceDept(EPlaceDept.RIGHT_DEPT.getValue());
            }
            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 = iCuMemberService.checkmsLogCount(uc.getPkMember(), EApproveStatus.ALREADY_SUBMIT.getValue());
            if (count > 0) {
                return AjaxResult.error(uc.getMemberCode(), TransactionUtils.getContent(ConfigMsgConstants.MEMBER_UPDATE_CODE_REPEAT));
            }
            //当前最大次数
            Integer approveNumber = iCuMemberServiceLogService.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 = iServiceChargeServiceApi.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 = iCuMemberTradeService.selectBalanceNotEnoughMember(businessCommissionDTO);
                if (CollectionUtil.isNotEmpty(memberBalanceList)) {
                    return AjaxResult.error(504, TransactionUtils.getContent(ConfigMsgConstants.MEMBER_BALANCE_INSUFFICIENT), memberBalanceList);
                }
            }
        }
        iCuMemberService.petitionUpdatePlaceParent(updatePlaceParentPetitionParam);

        return AjaxResult.success();
    }

}
