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.ext.CuMemberExt;
import com.hzs.common.domain.member.ext.CuMemberTeamExt;
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.core.utils.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.IMemberTeamServiceApi;
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 lombok.extern.slf4j.Slf4j;
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.*;

/**
 * @Description: 修改直推
 * @Author: yuhui
 * @Time: 2023/1/5 10:32
 * @Classname: UpdateParentController
 * @PackageName: com.hzs.member.base.controller.manager
 */
@RequestMapping("/manage/update-parent")
@RestController
@Slf4j
public class UpdateParentController extends BaseController {
    @Autowired
    private ICuMemberTradeService cuMemberTradeService;
    @DubboReference
    private IAccountServiceApi accountServiceApi;
    @Autowired
    private ICuMemberServiceLogService memberServiceLogService;
    @DubboReference
    private IServiceChargeServiceApi serviceChargeServiceApi;
    @DubboReference
    private IBusinessCommission businessCommission;
    @DubboReference
    private IAwardsServiceApi awardsServiceApi;
    @DubboReference
    private IVertexServiceApi vertexServiceApi;
    @DubboReference
    private IMemberTeamServiceApi memberTeamServiceApi;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    /**
     * 查询直推修改数据
     *
     * @return
     */
    @GetMapping("list")
    public TableDataInfo list(String memberCode, String memberName) {
        startPage();
        // 奖衔
        R<List<BdAwards>> listR = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        List<BdAwards> awardsList = listR.getData();
        // 体系
        R<List<VertexDTO>> vertexDto = vertexServiceApi.findAll();
        List<VertexDTO> vertexAll = vertexDto.getData();
        // 团队
        R<List<CuMemberTeamExt>> memberTeamDto = memberTeamServiceApi.queryCuMemberTeam(SecurityUtils.getPkCountry());
        List<CuMemberTeamExt> memberTeamList = memberTeamDto.getData();
//        QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PARENT.getValue());
//        if (StringUtils.isNotBlank(memberCode)){
//            queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PARENT.getValue());
//        }
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EApproveStatus.values());
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuMemberServiceLog> list = memberServiceLogService.queryList(EApprovalBusiness.CU_MEMBER_PARENT.getValue(), memberCode, memberName, pkCountry);
        //   List<CuMemberServiceLog> list = memberServiceLogService.list(queryWrapper);
        List<MemberParentVo> resultList = new ArrayList<>();
        for (CuMemberServiceLog cuMemberServiceLog : list) {
            CuMember member = cuMemberService.getMemberById(cuMemberServiceLog.getPkMember());
            if (member != null) {
                // 安置
                CuMember parentMember = cuMemberService.getMemberByCode(cuMemberServiceLog.getOldValue());
                MemberParentVo memberParentVo = new MemberParentVo();
                memberParentVo.setApproveStatusVal(transactionMap.get(EnumsPrefixConstants.APPROVE_STATUS + cuMemberServiceLog.getApproveStatus()));
                memberParentVo.setPkMember(member.getPkId());
                memberParentVo.setMemberCode(member.getMemberCode());
                memberParentVo.setMemberName(member.getMemberName());
                if (parentMember != null) {
                    memberParentVo.setParMemberCode(parentMember.getMemberCode());
                    memberParentVo.setParMemberName(parentMember.getMemberName());
                }

                if (StringUtils.isNotBlank(cuMemberServiceLog.getNewValue())) {
                    boolean isJson = JSONUtil.isTypeJSON(cuMemberServiceLog.getNewValue());
                    if (isJson) {
                        // 直推修改之后的新值 //是否json  老数据为json 数据 新数据为值
                        JSONObject newjson = JSONObject.parseObject(cuMemberServiceLog.getNewValue());
                        CuMember newMember = cuMemberService.getMember(newjson.getString("memberCode"));
                        if (newMember != null) {
                            memberParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                            memberParentVo.setEditNewPlaceMemberCode(newMember.getMemberCode());
                        }

                    } else {
                        CuMember newMember = cuMemberService.getMember(cuMemberServiceLog.getNewValue());
                        if (newMember != null) {
                            memberParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                            memberParentVo.setEditNewPlaceMemberCode(newMember.getMemberCode());
                        }
                    }

                }
                memberParentVo.setEditNumber(cuMemberServiceLog.getApproveNumber());
                memberParentVo.setPkAwards(member.getPkAwards());
                // 奖衔
                for (BdAwards bdAwards : awardsList) {
                    if (bdAwards.getPkId().equals(member.getPkAwards())) {
                        memberParentVo.setAwardsStr(bdAwards.getAwardsName());
                    }
                }
                // 体系
                for (VertexDTO vertex : vertexAll) {
                    if (vertex.getPkId().equals(member.getPkVertex())) {
                        // 体系名称
                        memberParentVo.setVertexName(vertex.getVertexName());
                    }
                }
                // 团队
                for (CuMemberTeamExt cuMemberTeamExt : memberTeamList) {
                    if (cuMemberTeamExt.getPkId().equals(member.getPkTeamCode())) {
                        memberParentVo.setTeamCode(cuMemberTeamExt.getTeamName());
                    }
                }
                memberParentVo.setEditDate(cuMemberServiceLog.getCreationTime());
                resultList.add(memberParentVo);
            }
        }
        return getDataTable(resultList);
    }

    /**
     * 查询直推修改数据
     *
     * @param memberCode
     * @param memberName
     * @return
     */
    @PostMapping("export-list")
    public void exportList(String memberCode, String memberName, HttpServletResponse response) {
        // 奖衔
        R<List<BdAwards>> listR = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        List<BdAwards> awardsList = listR.getData();
        // 体系
        R<List<VertexDTO>> vertexDto = vertexServiceApi.findAll();
        List<VertexDTO> vertexAll = vertexDto.getData();
        // 团队
        R<List<CuMemberTeamExt>> memberTeamDto = memberTeamServiceApi.queryCuMemberTeam(SecurityUtils.getPkCountry());
        List<CuMemberTeamExt> memberTeamList = memberTeamDto.getData();
        List<CuMemberServiceLog> list = memberServiceLogService.queryList(EApprovalBusiness.CU_MEMBER_PARENT.getValue(), memberCode, memberName, SecurityUtils.getPkCountry());
        List<MemberParentExportVo> resultList = new ArrayList<>();
        for (CuMemberServiceLog cuMemberServiceLog : list) {
            CuMember member = cuMemberService.getMember(cuMemberServiceLog.getPkMember());
            // 安置
            CuMember parentMember = cuMemberService.getMember(member.getPkParent());
            MemberParentExportVo memberParentVo = new MemberParentExportVo();
            memberParentVo.setPkMember(member.getPkId());
            memberParentVo.setMemberCode(member.getMemberCode());
            memberParentVo.setMemberName(member.getMemberName());
            memberParentVo.setEditOldParentMemberCode(parentMember.getMemberCode());
            memberParentVo.setEditOldParentMemberName(parentMember.getMemberName());
            if (StringUtils.isNotBlank(cuMemberServiceLog.getNewValue())) {
                boolean isJson = JSONUtil.isTypeJSON(cuMemberServiceLog.getNewValue());
                if (isJson) {
                    // 直推修改之后的新值 //是否json  老数据为json 数据 新数据为值
                    JSONObject newjson = JSONObject.parseObject(cuMemberServiceLog.getNewValue());
                    CuMember newMember = cuMemberService.getMember(newjson.getString("memberCode"));
                    memberParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                    memberParentVo.setEditNewPlaceMemberCode(newMember.getMemberCode());
                } else {
                    CuMember newMember = cuMemberService.getMember(cuMemberServiceLog.getNewValue());
                    memberParentVo.setEditNewPlaceMemberName(newMember.getMemberName());
                    memberParentVo.setEditNewPlaceMemberCode(newMember.getMemberCode());
                }

            }
            memberParentVo.setEditNumber(cuMemberServiceLog.getApproveNumber());
            memberParentVo.setPkAwards(member.getPkAwards());
            // 奖衔
            for (BdAwards bdAwards : awardsList) {
                if (bdAwards.getPkId().equals(member.getPkAwards())) {
                    memberParentVo.setAwardsStr(bdAwards.getAwardsName());
                }
            }
            // 体系
            for (VertexDTO vertex : vertexAll) {
                if (vertex.getPkId().equals(member.getPkVertex())) {
                    // 体系名称
                    memberParentVo.setVertexName(vertex.getVertexName());
                }
            }
            // 团队
            for (CuMemberTeamExt cuMemberTeamExt : memberTeamList) {
                if (cuMemberTeamExt.getPkId().equals(member.getPkTeamCode())) {
                    memberParentVo.setTeamCode(cuMemberTeamExt.getTeamName());
                }
            }
            memberParentVo.setEditDate(cuMemberServiceLog.getCreationTime());
            resultList.add(memberParentVo);
        }
        ExcelUtil<MemberParentExportVo> util = new ExcelUtil<MemberParentExportVo>(MemberParentExportVo.class);
        util.exportExcel(response, resultList, "修改直推");
    }


    /**
     * 修改直推
     *
     * @return
     */
    @PostMapping("update-parent")
    public AjaxResult updateParent(@RequestBody ParentParam parentParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        Set<Long> pkMemberIds = new HashSet<>();
        for (UpdateParentParam updateParentParam : parentParam.getUpdateParentParamList()) {
            CuMember member = cuMemberService.getMemberByCode(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            updateParentParam.setPkParent(member.getPkParent());
            CuMember parentMember = cuMemberService.getMember(updateParentParam.getEditNewPlaceMemberCode());
            if (parentMember == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            /**
             * 校验修改直推 变更后推荐编号不能是自己本身
             * 不能是自己的血缘伞下
             */
            Long parentCount = cuMemberService.checkMemberParent(member.getPkId(), updateParentParam.getEditNewPlaceMemberCode());
            if (updateParentParam.getMemberCode().equals(updateParentParam.getEditNewPlaceMemberCode()) || parentCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_THIS_OR_PARENT));
            }

            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            queryWrapper.eq("PK_MEMBER", member.getPkId());
            int count = memberServiceLogService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(),
                    EApprovalBusiness.CU_MEMBER_PARENT.getValue(), EApproveStatus.FINISH.getValue());
            updateParentParam.setChangeNumber(approveNumber + 1);
            updateParentParam.setPkMember(member.getPkId());
            //查询扣费金额，账户信息
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_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 (parentParam.getProcessType() == EProcessType.DOUBLEPAY.getValue() || parentParam.getProcessType() == EProcessType.AVOIDSIGNING.getValue()) {
                BusinessCommissionDTO businessCommissionDTO = new BusinessCommissionDTO();
                businessCommissionDTO.setPkAccount(serviceChargeDTOR.getData().getPkAccount());
                businessCommissionDTO.setPkCountry(pkCountry);
                businessCommissionDTO.setPkAccount(updateParentParam.getPkAccount());
                businessCommissionDTO.setTradeType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
                List<MemberAmountDTO> memberAmountDTOList = new ArrayList<>();
                MemberAmountDTO memberAmountDTO = MemberAmountDTO.builder()
                        .pkMember(member.getPkId())
                        .tradeAmount(serviceChargeDTOR.getData().getCost()).pkAccount(serviceChargeDTOR.getData().getPkAccount())
                        .businessType(serviceChargeDTOR.getData().getType()).build();
                memberAmountDTOList.add(memberAmountDTO);
                businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
                parentParam.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());
                }
            }
            pkMemberIds.add(member.getPkId());
        }
        parentParam.setPkMemberList(pkMemberIds);
        cuMemberService.updateParent(parentParam);
        return AjaxResult.success();
    }

    /**
     * 校验修改安置关系数据问题
     */
    @PostMapping("check-member-parent")
    public AjaxResult checkMemberParent(@RequestBody ParentParam parentParam) {
        for (UpdateParentParam updateParentParam : parentParam.getUpdateParentParamList()) {
            CuMember member = cuMemberService.getMember(updateParentParam.getMemberCode());
            if (member == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            CuMember parentMember = cuMemberService.getMember(updateParentParam.getEditNewPlaceMemberCode());
            if (parentMember == null) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_VALID));
            }
            /**
             * 校验修改直推 变更后推荐编号不能是自己本身
             * 不能是自己的血缘伞下
             */
            Long parentCount = cuMemberService.checkMemberParent(member.getPkId(), updateParentParam.getEditNewPlaceMemberCode());
            if (updateParentParam.getMemberCode().equals(updateParentParam.getEditNewPlaceMemberCode()) || parentCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_THIS_OR_PARENT));
            }
            QueryWrapper<CuMemberServiceLog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("APPROVE_STATUS", EApproveStatus.ALREADY_SUBMIT.getValue());
            queryWrapper.eq("EDIT_TYPE", EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            queryWrapper.eq("PK_MEMBER", member.getPkId());
            int count = memberServiceLogService.count(queryWrapper);
            if (count > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_PARENT_UPDATE));
            }
        }

        return AjaxResult.success();
    }

    /**
     * @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_RECOMMEND, method = EOperationMethod.SUBMIT)
    @PostMapping("/petition")
    public AjaxResult petition(@RequestBody UpdateParentPetitionParam updateParentPetitionParam) {
        if (StringUtils.isEmpty(updateParentPetitionParam.getUpdateParentParamList())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_DATA_NOT_NULL));
        }
        if (StringUtils.isNull(updateParentPetitionParam.getProcessType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.PROCESS_TYPE_NOT_NULL));
        }
        if (StringUtils.isNull(updateParentPetitionParam.getSignType())) {
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.SIGN_TYPE_NOT_NULL));
        }
        if (CollectionUtil.isEmpty(updateParentPetitionParam.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 (UpdateParentParam uc : updateParentPetitionParam.getUpdateParentParamList()) {
            if (StringUtils.isEmpty(uc.getMemberCode())) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_CODE_NOT_NULL));
            }
            CuMember member = cuMemberService.getMemberByCode(uc.getMemberCode());
            uc.setPkMember(member.getPkId());

            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));
            }
            /**
             * 校验修改直推 变更后推荐编号不能是自己本身
             * 不能是自己的血缘伞下
             */
            Long parentCount = cuMemberService.checkMemberParent(member.getPkId(), uc.getEditNewPlaceMemberCode());
            if (uc.getMemberCode().equals(uc.getEditNewPlaceMemberCode()) || parentCount > 0) {
                return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_THIS_OR_PARENT));
            }

            //当前最大次数
            Integer approveNumber = memberServiceLogService.selectByMaxApproveNumber(uc.getPkMember(),
                    EApprovalBusiness.CU_MEMBER_PARENT.getValue(), null);
            uc.setChangeNumber(approveNumber + 1);
            if (updateParentPetitionParam.getProcessType() == EProcessType.DOUBLEPAY.getValue()) {
                //查询扣费金额，账户信息
                ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
                serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_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);
            }
        }
        updateParentPetitionParam.setPkMemberList(pkMemberIds);
        updateParentPetitionParam.setMemberAmountDTOList(memberAmountDTOList);
        businessCommissionDTO.setMemberAmountDTOList(memberAmountDTOList);
        if (CollectionUtil.isNotEmpty(memberAmountDTOList)) {
            //接口查询金额是否足够
            if (updateParentPetitionParam.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.petitionUpdateParent(updateParentPetitionParam);
        return AjaxResult.success();
    }

    /**
     * 获取用户扣费详情   TODO   用户信息弹窗
     *
     * @return
     */
    @PostMapping("get-member-charging-detail")
    public AjaxResult getMemberChargingDetail(@RequestBody MemberChargingDetailParam memberChargingDetailParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<MemberParentVo> resultList = new ArrayList<>();
        for (MemberChargingDetailVo memberChargingDetailVo : memberChargingDetailParam.getMemberChargingDetailList()) {
            CuMember member = cuMemberService.getMember(memberChargingDetailVo.getPkMember());
            // 安置
            CuMember parentMember = cuMemberService.getMember(member.getPkParent());
            MemberParentVo memberChargingVo = new MemberParentVo();

            memberChargingVo.setMemberCode(member.getMemberCode());
            memberChargingVo.setMemberName(member.getMemberName());
            memberChargingVo.setParMemberCode(parentMember.getMemberCode());
            memberChargingVo.setParMemberName(parentMember.getMemberName());

            // 变更后
            CuMember newPlaceParentMember = cuMemberService.getMember(memberChargingDetailVo.getEditNewPlaceMemberCode());
            memberChargingVo.setEditNewPlaceMemberCode(newPlaceParentMember.getMemberCode());
            memberChargingVo.setEditNewPlaceMemberName(newPlaceParentMember.getMemberName());

            //  TODO 扣款
            Integer quantity = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(), EApprovalBusiness.CU_MEMBER_PARENT.getValue(), EApproveStatus.FINISH.getValue());
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setPkCountry(pkCountry);
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            serviceChargeDTO.setQuantity(quantity + 1);
            R<ServiceChargeDTO> serviceCharge = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            R<BdAccount> account = accountServiceApi.getAccount(serviceCharge.getData().getPkAccount());
            memberChargingVo.setPkAccount(serviceCharge.getData().getPkAccount());
            memberChargingVo.setPkAccountKeyVal(account.getData().getAccountName());

            memberChargingVo.setCost(serviceCharge.getData().getCost());
            resultList.add(memberChargingVo);
        }
        return AjaxResult.success(resultList);
    }


    /**
     * 导入(前端展示使用)
     *
     * @param file
     */
    @PostMapping("/import-service-log")
    public AjaxResult importServiceLog(MultipartFile file) throws Exception {
        Integer pkCountry = SecurityUtils.getPkCountry();
        ExcelUtil<MemberParentVo> util = new ExcelUtil<>(MemberParentVo.class);
        List<MemberParentVo> list = util.importExcel(file.getInputStream());
        for (MemberParentVo updateParentVo : list) {

            // 会员
            CuMember member = cuMemberService.getMember(updateParentVo.getMemberCode());
            // 变更后 推荐编号
            CuMember newMember = cuMemberService.getMember(updateParentVo.getEditNewPlaceMemberCode());
            // 查询是否在安置人伞下
            List<CuMemberExt> cuMemberLoginExts = cuMemberService.queryPlaceSponsorUnderUmbrella(newMember.getPkId(), member.getMemberCode());
            if (cuMemberLoginExts.size() == 0) {
                return AjaxResult.error(updateParentVo.getMemberCode() + "不在安置人编号" + updateParentVo.getEditNewPlaceMemberCode() + "伞下");
            }
            updateParentVo.setPkMember(member.getPkId());
            // 会员名称
            updateParentVo.setMemberName(member.getMemberName());
            // 变更前安置编号
            CuMember changeMember = cuMemberService.getMember(member.getPkParent());
            updateParentVo.setParMemberCode(changeMember.getMemberCode());
            updateParentVo.setParMemberName(changeMember.getMemberName());

            updateParentVo.setEditNewPlaceMemberCode(updateParentVo.getEditNewPlaceMemberCode());
            updateParentVo.setEditNewPlaceMemberName(newMember.getMemberName());


            Integer quantity = memberServiceLogService.selectByMaxApproveNumber(member.getPkId(), EApprovalBusiness.CU_MEMBER_PARENT.getValue(), EApproveStatus.FINISH.getValue());
            ServiceChargeDTO serviceChargeDTO = new ServiceChargeDTO();
            serviceChargeDTO.setPkCountry(pkCountry);
            serviceChargeDTO.setType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            serviceChargeDTO.setQuantity(quantity + 1);
            R<ServiceChargeDTO> serviceCharge = serviceChargeServiceApi.getServiceChargeByType(serviceChargeDTO);
            R<BdAccount> account = accountServiceApi.getAccount(serviceCharge.getData().getPkAccount());
            updateParentVo.setPkAccount(serviceCharge.getData().getPkAccount());
            updateParentVo.setPkAccountKeyVal(account.getData().getAccountName());
            updateParentVo.setCost(serviceCharge.getData().getCost());

        }
        return AjaxResult.success(list);
    }

    /**
     * 修改直推导出基础表格
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response) {
        List<UpdateParentExport> resultList = new ArrayList<>();
        ExcelUtil<UpdateParentExport> util = new ExcelUtil<UpdateParentExport>(UpdateParentExport.class);
        util.exportExcel(response, resultList, "修改直推");
    }

    /**
     * 直推关系弹窗提交
     *
     * @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_PARENT.getValue());

            String memberCode = memberService.getMemberCode();
            CuMember member = cuMemberService.getMember(memberCode);
            CuMemberServiceLog cuMemberServiceLog = new CuMemberServiceLog();
            cuMemberServiceLog.setPkMember(member.getPkId());
            cuMemberServiceLog.setEditType(EApprovalBusiness.CU_MEMBER_PARENT.getValue());
            JSONObject oldJson = new JSONObject();
            oldJson.put("changeMemberCode", memberService.getEditOldPlaceMemberCode());
            cuMemberServiceLog.setOldValue(oldJson.toJSONString());
            JSONObject newJson = new JSONObject();
            newJson.put("newChangeMemberCode", memberService.getEditNewPlaceMemberCode());

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

    /**
     * 查询会员信息列表
     *
     * @return
     */
    @GetMapping("get-member-info-list")
    public AjaxResult getMemberInfoList() {


        return AjaxResult.success();
    }
}
