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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.ColumnAuthority;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.NumberUtil;
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.account.CuMemberTransfer;
import com.hzs.common.domain.member.account.CuMemberWithdraw;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.base.CuMember;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.security.service.MemberTokenService;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.account.service.ICuMemberTransferService;
import com.hzs.member.account.service.ICuMemberWithdrawService;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.achieve.service.ICuMemberTreeService;
import com.hzs.member.annuity.service.ICuMemberAnnuityService;
import com.hzs.member.base.dto.LoginMember;
import com.hzs.member.base.dto.MemberBusinessTemplate;
import com.hzs.member.base.param.MemberRealInfoParam;
import com.hzs.member.base.param.MemberSelectParam;
import com.hzs.member.base.param.MemberTeamInfoParam;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.ICuMemberTeamService;
import com.hzs.member.base.vo.*;
import com.hzs.member.login.service.IMemberLoginService;
import com.hzs.system.base.IAreaServiceApi;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
import com.hzs.system.sys.IMenuColumnServiceApi;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.UserAuthorityDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/manager/member")
@RestController
public class CuMemberController extends BaseController {
    @Autowired
    private ICuMemberAnnuityService memberAnnuityService;
    @Autowired
    private ICuMemberWithdrawService memberWithdrawService;
    @Autowired
    private ICuMemberSettlePeriodService memberSettlePeriodService;
    @Autowired
    private ICuMemberTransferService memberTransferService;
    @Autowired
    private ICuMemberService cuMemberService;
    @Autowired
    private ICuMemberTeamService memberTeamService;
    @Autowired
    private ICuMemberTreeService memberTreeService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private IMemberLoginService iMemberLoginService;

    @DubboReference
    IUserServiceApi iUserServiceApi;
    @DubboReference
    IMenuColumnServiceApi iMenuColumnServiceApi;
    @DubboReference
    IAwardsServiceApi awardsServiceApi;
    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    IAreaServiceApi areaServiceApi;

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


    /**
     * 会员 registerAuthority
     *
     * @param memberParam 会员参数
     */
    @ColumnAuthority(perms = "Member")
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFORMATION, method = EOperationMethod.SELECT)
    @GetMapping("/query-member")
    public TableDataInfo queryMember(CuMemberVO memberParam) {
        memberParam.setPkCountry(SecurityUtils.getPkCountry());
        EMemberAccount memberAccountEnum = null;
        if (memberParam.getMemberAccount() != null) {
            Map<Integer, EMemberAccount> memberAccountMap = Arrays.stream(EMemberAccount.values())
                    .collect(Collectors.toMap(EMemberAccount::getValue, e -> e));
            memberAccountEnum = memberAccountMap.getOrDefault(memberParam.getMemberAccount(), null);
        }
        if (memberAccountEnum != null) {
            switch (memberAccountEnum) {
                case NORMAL:
                    memberParam.setIsTransfer(EYesNo.YES.getIntValue());
                    memberParam.setIsWithdraw(EYesNo.YES.getIntValue());
                    memberParam.setIsConsume(EYesNo.YES.getIntValue());
                    break;
                case PROHIBIT_TRANSFER:
                    memberParam.setIsTransfer(EYesNo.NO.getIntValue());
                    break;
                case PROHIBIT_WITHDRAW:
                    memberParam.setIsWithdraw(EYesNo.NO.getIntValue());
                    break;
                case PROHIBIT_CONSUME:
                    memberParam.setIsConsume(EYesNo.NO.getIntValue());
                    memberParam.setIsTransfer(EMemberAccount.PROHIBIT_CONSUME.getIsYesNo());
                    break;
                case WHOLE_TRANSFER:
                    memberParam.setIsTransfer(EYesNo.YES.getIntValue());
                    memberParam.setTransferStatus(ETransferStatus.FREEZE.getValue());
                    break;
                default:
                    break;
            }
        }

        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        memberParam.setVertexList(userAuthorityDTO.getUserVertexList());
        memberParam.setTeamList(userAuthorityDTO.getUserTeamList());

        startPage();
        if (memberParam.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            memberParam.setPkCountry(null);
        }
        List<CuMemberVO> queryCuMemberVoList = cuMemberService.queryCuMemberByCondition(memberParam);
        List<CuMemberVO> cuMemberVOList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(queryCuMemberVoList)) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EMemberAccount.values());


            cuMemberVOList = cuMemberService.queryCuMemberByMemberList(queryCuMemberVoList);
            List<CuMemberVO> cuMemberVOS1 = cuMemberVOList.stream()
                    .filter(cvo -> StringUtils.isNotNull(memberParam.getIsConsume()) &&
                            memberParam.getIsConsume() == EMemberAccount.PROHIBIT_CONSUME.getValue())
                    .peek(cvo -> {
                        cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                        AccountPointOutVO accountPointOutVO = new AccountPointOutVO();
                        accountPointOutVO.setAccountState(cvo.getIsTransfer());
                    }).collect(Collectors.toList());
            cuMemberVOS1.addAll(cuMemberVOList.stream()
                    .filter(cvo -> StringUtils.isNotNull(memberParam.getIsConsume()) &&
                            memberParam.getIsConsume() == EMemberAccount.WHOLE_TRANSFER.getValue())
                    .peek(cvo -> {
                        cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                        AccountPointOutVO accountPointOutVO = new AccountPointOutVO();
                        accountPointOutVO.setAccountState(cvo.getIsTransfer());
                    }).collect(Collectors.toList()));
            cuMemberVOS1.addAll(cuMemberVOList.stream()
                    .peek(cvo -> {
                        if (StringUtils.isNull(cvo.getDirectPushNumber())) {
                            cvo.setDirectPushNumber(0);
                        }
                        if (StringUtils.isNull(cvo.getChangeNumber())) {
                            cvo.setChangeNumber(0);
                        }
                        if (cvo.getCategory() == ECategory.DEAD_POINT.getValue() ||
                                cvo.getCustomerType() == ECustomerType.DEAD_POINT.getValue()) {
                            cvo.setAccountStatus(EAccountStatus.SHUT_DOWN.getValue());
                            cvo.setIsTransfer(EYesNo.NO.getIntValue());
                            cvo.setIsWithdraw(EYesNo.NO.getIntValue());
                            cvo.setIsConsume(EYesNo.NO.getIntValue());
                        }
                        cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                        //剩余天数
                        Long expireDateNumber = 0L;
                        if (cvo.getExpireDate() != null) {
                            expireDateNumber = DateUtil.between(cvo.getExpireDate(), DateUtils.currentDate(), DateUnit.DAY);
                        }
                        cvo.setExpireDateNumber(expireDateNumber + 1);
                    }).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(cuMemberVOS1)) {
                TableDataInfo tableDataInfo = getDataTable(queryCuMemberVoList);
                tableDataInfo.setRows(cuMemberVOList);
                return tableDataInfo;
            }
        }
        TableDataInfo tableDataInfo = getDataTable(queryCuMemberVoList);
        tableDataInfo.setRows(cuMemberVOList);
        return tableDataInfo;
    }

    /**
     * 获取会员账户信息值
     *
     * @param cvo            会员对象
     * @param transactionMap 枚举翻译Map
     * @return 账户信息值
     */
    private String getMemberAccountVal(CuMemberVO cvo, Map<String, String> transactionMap) {
        String memberAccountVal = "";
        if (StringUtils.isNotNull(cvo.getIsTransfer()) && cvo.getIsTransfer() == EYesNo.NO.getIntValue()) {
            memberAccountVal = transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.PROHIBIT_TRANSFER.getValue());
        }
        if (StringUtils.isNotNull(cvo.getIsWithdraw()) && cvo.getIsWithdraw() == EYesNo.NO.getIntValue()) {
            memberAccountVal = memberAccountVal + "/" + transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.PROHIBIT_WITHDRAW.getValue());
            if (StringUtils.isNotNull(cvo.getTransferStatus()) && cvo.getTransferStatus() == ETransferStatus.FREEZE.getValue()) {
                memberAccountVal = memberAccountVal + "/" + transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.WHOLE_TRANSFER.getValue());
            }
        }
        if (StringUtils.isNotNull(cvo.getIsConsume()) && cvo.getIsConsume() == EYesNo.NO.getIntValue()) {
            memberAccountVal = memberAccountVal + "/" + transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.PROHIBIT_CONSUME.getValue());
            if (StringUtils.isNotNull(cvo.getTransferStatus()) && cvo.getTransferStatus() == ETransferStatus.FREEZE.getValue()) {
                memberAccountVal = memberAccountVal + "/" + transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.WHOLE_TRANSFER.getValue());
            }
        }
        if (StringUtils.isNotNull(cvo.getIsTransfer()) && cvo.getIsTransfer() == EYesNo.YES.getIntValue()
                && StringUtils.isNotNull(cvo.getIsWithdraw()) && cvo.getIsWithdraw() == EYesNo.YES.getIntValue()
                && StringUtils.isNotNull(cvo.getIsConsume()) && cvo.getIsConsume() == EYesNo.YES.getIntValue()) {
            memberAccountVal = transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.NORMAL.getValue());
            if (StringUtils.isNotNull(cvo.getTransferStatus()) && cvo.getTransferStatus() == ETransferStatus.FREEZE.getValue()) {
                memberAccountVal = memberAccountVal + "/" + transactionMap.get(EnumsPrefixConstants.MEMBER_ACCOUNT + EMemberAccount.WHOLE_TRANSFER.getValue());
            }
        }
        return memberAccountVal;
    }


    /**
     * 导出会员信息
     *
     * @param response
     * @param memberParam
     */
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFORMATION, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuMemberVO memberParam) {
        memberParam.setPkCountry(SecurityUtils.getPkCountry());
//        if (null == memberParam.getStartDate() || null == memberParam.getEndDate()) {
//            throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.CREATION_TIME_RANGE));
//        }
//        Integer days = DateUtils.betweenDay(memberParam.getStartDate(), memberParam.getEndDate());
//        if (days > 365) {
//            throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.ONE_YEAR_DATA));
//        }
        EMemberAccount memberAccountEnum = null;
        if (memberParam.getMemberAccount() != null) {
            Map<Integer, EMemberAccount> memberAccountMap = Arrays.stream(EMemberAccount.values())
                    .collect(Collectors.toMap(EMemberAccount::getValue, e -> e));
            memberAccountEnum = memberAccountMap.getOrDefault(memberParam.getMemberAccount(), null);
        }
        if (memberAccountEnum != null) {
            switch (memberAccountEnum) {
                case NORMAL:
                    memberParam.setIsTransfer(EYesNo.YES.getIntValue());
                    memberParam.setIsWithdraw(EYesNo.YES.getIntValue());
                    memberParam.setIsConsume(EYesNo.YES.getIntValue());
                    break;
                case PROHIBIT_TRANSFER:
                    memberParam.setIsTransfer(EYesNo.NO.getIntValue());
                    break;
                case PROHIBIT_WITHDRAW:
                    memberParam.setIsWithdraw(EYesNo.NO.getIntValue());
                    break;
                case PROHIBIT_CONSUME:
                    memberParam.setIsConsume(EYesNo.NO.getIntValue());
                    memberParam.setIsTransfer(EMemberAccount.PROHIBIT_CONSUME.getIsYesNo());
                    break;
                case WHOLE_TRANSFER:
                    memberParam.setIsTransfer(EYesNo.YES.getIntValue());
                    memberParam.setTransferStatus(ETransferStatus.FREEZE.getValue());
                    break;
                default:
                    break;
            }
        }
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EMemberAccount.values(), EYesNoAttestation.values(),
                EOrderSource.values(), EYesNoUpLoads.values(), ERegistrationAuthority.values(),
                EAccountStatus.values(), EWalletStatus.values(), ECategory.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        // 获取管理员权限（角色地区范围、体系列表、团队列表）
        UserAuthorityDTO userAuthorityDTO = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        memberParam.setVertexList(userAuthorityDTO.getUserVertexList());
        memberParam.setTeamList(userAuthorityDTO.getUserTeamList());
        if (memberParam.getPkCountry() == CountryConstants.CHINA_COUNTRY) {
            memberParam.setPkCountry(null);
        }
        List<CuMemberVO> cuMemberVOList = cuMemberService.queryCuMemberByMemberListExcel(memberParam);
        List<CuMemberVO> cuMemberVOS1 = cuMemberVOList.stream()
                .filter(cvo -> StringUtils.isNotNull(memberParam.getIsConsume()) &&
                        memberParam.getIsConsume() == EMemberAccount.PROHIBIT_CONSUME.getValue())
                .peek(cvo -> {
                    cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                    AccountPointOutVO accountPointOutVO = new AccountPointOutVO();
                    accountPointOutVO.setAccountState(cvo.getIsTransfer());
                }).collect(Collectors.toList());
        cuMemberVOS1.addAll(cuMemberVOList.stream()
                .filter(cvo -> StringUtils.isNotNull(memberParam.getIsConsume()) &&
                        memberParam.getIsConsume() == EMemberAccount.WHOLE_TRANSFER.getValue())
                .peek(cvo -> {
                    cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                    AccountPointOutVO accountPointOutVO = new AccountPointOutVO();
                    accountPointOutVO.setAccountState(cvo.getIsTransfer());
                }).collect(Collectors.toList()));
        cuMemberVOS1.addAll(cuMemberVOList.stream()
                .peek(cvo -> {
                    if (StringUtils.isNull(cvo.getDirectPushNumber())) {
                        cvo.setDirectPushNumber(0);
                    }
                    if (StringUtils.isNull(cvo.getChangeNumber())) {
                        cvo.setChangeNumber(0);
                    }
                    if (cvo.getCategory() == ECategory.DEAD_POINT.getValue() ||
                            cvo.getCustomerType() == ECustomerType.DEAD_POINT.getValue()) {
                        cvo.setAccountStatus(EAccountStatus.SHUT_DOWN.getValue());
                        cvo.setIsTransfer(EYesNo.NO.getIntValue());
                        cvo.setIsWithdraw(EYesNo.NO.getIntValue());
                        cvo.setIsConsume(EYesNo.NO.getIntValue());
                    }
                    cvo.setCategoryVal(transactionMap.get(EnumsPrefixConstants.ENU_CAT + cvo.getCategory()));
                    cvo.setAccountStatusVal(transactionMap.get(EnumsPrefixConstants.ACCOUNT_STATUS + cvo.getAccountStatus()));
                    cvo.setSystemLevelVal(transactionMap.get(EnumsPrefixConstants.ENUM_SYS_LEV + cvo.getSystemLevel()));
                    cvo.setLecturerLevelVal(transactionMap.get(EnumsPrefixConstants.ENUM_LEC_LEV + cvo.getLecturerLevel()));
                    cvo.setIsMakerSpaceVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getIsMakerSpace()));
                    cvo.setIsBusLicenseVal(transactionMap.get(EnumsPrefixConstants.YES_NO_UPLOADS + cvo.getIsBusLicense()));
                    cvo.setIsRealNameVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getIsRealName()));
                    cvo.setOrderSourceVal(transactionMap.get(EnumsPrefixConstants.ORDER_SOURCE + cvo.getOrderSource()));
                    cvo.setIsDealerVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getIsDealer()));
                    cvo.setAgentGradeVal(transactionMap.get(EnumsPrefixConstants.KEY_GRADE + cvo.getAgentGrade()));
                    cvo.setPkRegisterGradeVal(transactionMap1.get(cvo.getPkRegisterGrade()));
                    cvo.setPkSettleGradeVal(transactionMap1.get(cvo.getPkSettleGrade()));
                    cvo.setPkAwardsVal(transactionMap1.get(cvo.getPkAwards()));
                    cvo.setMemberAccountVal(getMemberAccountVal(cvo, transactionMap));
                    cvo.setWalletStatusVal(transactionMap.get(EnumsPrefixConstants.WALLET_STATUS + cvo.getWalletStatus()));
                    cvo.setAccountStatusVal(transactionMap.get(EnumsPrefixConstants.ACCOUNT_STATUS + cvo.getAccountStatus()));
                    cvo.setRegisterAuthorityVal(transactionMap.get(EnumsPrefixConstants.REGISTRATION_AUTHORITY + cvo.getRegisterAuthority()));
                    cvo.setSuperStudioVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getSuperStudio()));
                    //剩余天数
                    Long expireDateNumber = 0L;
                    if (cvo.getExpireDate() != null) {
                        expireDateNumber = DateUtil.between(cvo.getExpireDate(), DateUtils.currentDate(), DateUnit.DAY);
                    }
                    cvo.setExpireDateNumber(expireDateNumber);
                }).collect(Collectors.toList()));
        if (CollectionUtil.isNotEmpty(cuMemberVOS1)) {
            ExcelUtil<CuMemberVO> util = new ExcelUtil<>(CuMemberVO.class, iMenuColumnServiceApi.queryMenuColumn("Member", SecurityUtils.getUserId()).getData());
            util.exportExcel(response, cuMemberVOList, "会员信息");
        }
        ExcelUtil<CuMemberVO> util = new ExcelUtil<>(CuMemberVO.class, iMenuColumnServiceApi.queryMenuColumn("Member", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, cuMemberVOList, "会员信息");
    }

    /**
     * 会员信息显示隐藏表头列表
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION)
    @GetMapping("/query-theLable")
    public AjaxResult queryTheLable() {
        List<TheLableVO> theLableVOList = new ArrayList<>();
        for (ETheLable value : ETheLable.values()) {
            theLableVOList.add(new TheLableVO(value.getTitel(), value.getProp(), value.getKeyId(), value.getShow()));
        }
        return AjaxResult.success(theLableVOList);
    }

    /**
     * 真实信息显示隐藏表头列表
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION)
    @GetMapping("/real-theLable")
    public AjaxResult realTheLable() {
        List<TheLableVO> theLableVOList = new ArrayList<>();
        for (ERealTheLable value : ERealTheLable.values()) {
            theLableVOList.add(new TheLableVO(value.getTitel(), value.getProp(), value.getKeyId(), value.getShow()));
        }
        return AjaxResult.success(theLableVOList);
    }


    /**
     * 真实信息
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFO_REAL, method = EOperationMethod.SELECT)
    @PostMapping("/real-member")
    public TableDataInfo realMember(@RequestBody CuMemberVO memberParam) {
        memberParam.setPkCountry(SecurityUtils.getPkCountry());
        List<CuMemberVO> cuMemberVOS = cuMemberService.realCuMemberByCondition(memberParam);
        if (CollectionUtil.isNotEmpty(cuMemberVOS)) {
            for (CuMemberVO cvo : cuMemberVOS) {

                if (cvo.getSex() == ESex.MAN.getValue()) {
                    cvo.setSexVal(ESex.MAN.getLabel());
                }
                if (cvo.getSex() == ESex.WOMAN.getValue()) {
                    cvo.setSexVal(ESex.WOMAN.getLabel());
                }
                if (cvo.getCardType() == ECardType.CARD.getValue()) {
                    cvo.setCardTypeVal(ECardType.CARD.getLabel());
                }
                if (cvo.getCardType() == ECardType.OFFICER.getValue()) {
                    cvo.setCardTypeVal(ECardType.OFFICER.getLabel());
                }
                if (cvo.getCardType() == ECardType.STUDENT.getValue()) {
                    cvo.setCardTypeVal(ECardType.STUDENT.getLabel());
                }
                if (cvo.getCardType() == ECardType.DRIVE.getValue()) {
                    cvo.setCardTypeVal(ECardType.DRIVE.getLabel());
                }
                if (cvo.getCardType() == ECardType.PASSPORT.getValue()) {
                    cvo.setCardTypeVal(ECardType.PASSPORT.getLabel());
                }


            }
        }

        return getDataTable(cuMemberVOS);
    }

    /**
     * 根据会员编号查询会员信息
     **/
    @GetMapping("/getOne/{memberCode}")
    public AjaxResult getOne(@PathVariable String memberCode) {
        CuMember cuMember = cuMemberService.getMemberByCode(memberCode);
        return AjaxResult.success(cuMember);
    }

    /**
     * 会员选择
     *
     * @param param
     * @return
     */
    @GetMapping("/member-select")
    public TableDataInfo memberSelect(MemberSelectParam param) {
        // 返回结果
        List<MemberSelectVO> resultList = new ArrayList<>();

        startPage();
        handleMemberSelect(resultList, param);

        return getDataTable(resultList);
    }

    /**
     * 会员选择下载模板
     *
     * @param response
     */
    @PostMapping("/member-select-template")
    public void memberSelectTemplate(HttpServletResponse response) {
        ExcelUtil<MemberBusinessTemplate> util = new ExcelUtil<>(MemberBusinessTemplate.class);
        util.exportExcel(response, null, "会员信息");
    }

    /**
     * 会员选择导入数据
     *
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/member-select-import")
    public AjaxResult memberSelectImport(MultipartFile file) throws Exception {
        ExcelUtil<MemberBusinessTemplate> util = new ExcelUtil<>(MemberBusinessTemplate.class);
        List<MemberBusinessTemplate> templateList = util.importExcel(file.getInputStream());

        // 返回结果
        List<MemberSelectVO> resultList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(templateList)) {
            MemberSelectParam param = new MemberSelectParam();
            param.setMemberCodeList(templateList.stream().map(MemberBusinessTemplate::getMemberCode).collect(Collectors.toList()));

            handleMemberSelect(resultList, param);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 处理选择会员数据
     *
     * @param resultList
     * @param param
     */
    private void handleMemberSelect(List<MemberSelectVO> resultList, MemberSelectParam param) {
        List<CuMemberExt> cuMemberExtList = cuMemberService.queryMemberSelect(param, SecurityUtils.getPkCountry());

        if (CollectionUtil.isNotEmpty(cuMemberExtList)) {
            for (CuMemberExt cuMemberExt : cuMemberExtList) {
                MemberSelectVO memberSelectVO = BeanUtil.copyProperties(cuMemberExt, MemberSelectVO.class);
                // 翻译key值进行处理
                memberSelectVO.setRegisterGrade(cuMemberExt.getRegisterGradeKey());
                memberSelectVO.setSettleGrade(cuMemberExt.getSettleGradeKey());
                memberSelectVO.setAwards(cuMemberExt.getAwardsKey());
                resultList.add(memberSelectVO);
            }
        }
    }


    /**
     * 会员真实信息
     *
     * @return
     */
    @ColumnAuthority(perms = "RealInfo")
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFO_REAL, method = EOperationMethod.SELECT)
    @GetMapping("/member-real-info")
    public TableDataInfo memberRealInfo(MemberRealInfoParam memberRealInfoParam) {
        memberRealInfoParam.setPkCountry(SecurityUtils.getPkCountry());

        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ECardType.values(),
                ESex.values()
        );
        //数据库内容翻译
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        startPage();
        List<MemberRealInfoVO> resultList = cuMemberService.selectByMemberRealInfo(memberRealInfoParam);

        if (CollectionUtil.isNotEmpty(resultList)) {
            R<List<BdAwards>> awardsListDate = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
            // 奖衔
            List<BdAwards> awardsList = awardsListDate.getData();
            R<List<GradeDTO>> gradeListDate = gradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
            // 等级
            List<GradeDTO> gradeList = gradeListDate.getData();
            Map<Integer, String> areaDate = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();

            for (MemberRealInfoVO cuMemberExt : resultList) {
                cuMemberExt.setRegisterGradeVal(transactionMap1.get(cuMemberExt.getPkRegisterGrade()));
                cuMemberExt.setSettleGradeVal(transactionMap1.get(cuMemberExt.getPkSettleGrade()));
                cuMemberExt.setAwardsVal(transactionMap1.get(cuMemberExt.getPkAwards()));
                if (cuMemberExt.getPkProvince() != null) {
                    // 省
                    cuMemberExt.setProvinceName(areaDate.get(cuMemberExt.getPkProvince()));
                }
                if (cuMemberExt.getPkCity() != null) {
                    // 市
                    cuMemberExt.setCityName(areaDate.get(cuMemberExt.getPkCity()));
                }
                if (cuMemberExt.getPkCounty() != null) {
                    // 区县
                    cuMemberExt.setCountyName(areaDate.get(cuMemberExt.getPkCounty()));
                }
                // 证件类型
                if (cuMemberExt.getCardType() != null) {
                    cuMemberExt.setCardTypeVal(transactionMap.get(cuMemberExt.getCardType()));
                }
                // 性别
                if (cuMemberExt.getSex() != null) {
                    cuMemberExt.setSexVal(transactionMap.get(cuMemberExt.getSex()));
                }
                // 注册等级
                if (cuMemberExt.getPkRegisterGrade() != null) {
                    for (GradeDTO grade : gradeList) {
                        if (grade.getPkId().equals(cuMemberExt.getPkRegisterGrade())) {
                            cuMemberExt.setRegisterGradeVal(grade.getGradeName());
                        }
                    }
                }
                // 结算等级
                if (cuMemberExt.getPkSettleGrade() != null) {
                    for (GradeDTO grade : gradeList) {
                        if (grade.getPkId().equals(cuMemberExt.getPkSettleGrade())) {
                            cuMemberExt.setSettleGradeVal(grade.getGradeName());
                        }
                    }
                }
                // 真实奖衔
                if (cuMemberExt.getPkAwards() != null) {
                    for (BdAwards awards : awardsList) {
                        if (awards.getPkId().equals(cuMemberExt.getPkAwards())) {
                            cuMemberExt.setAwardsVal(awards.getAwardsName());
                        }
                    }
                }
                // 生日
                if (StringUtils.isNotBlank(cuMemberExt.getIdCard())) {
                    cuMemberExt.setBirthDate(IdcardUtil.getBirthDate(cuMemberExt.getIdCard()));
                }
                if (cuMemberExt.getIdType() != null) {
                    cuMemberExt.setCardTypeVal(EIdType.getLabel(cuMemberExt.getIdType()));
                }
            }
        }

        return getDataTable(resultList);
    }


    /**
     * 会员团队信息
     *
     * @return
     */
    @GetMapping("member-team-info")
    public TableDataInfo memberTeamInfo(MemberTeamInfoParam memberTeamInfoParam) {
        String time;
        String settleTableName;
        CuMemberSettlePeriod csPeriod;
        List<MemberTeamVo> memberTeamList = new ArrayList<>();
        R<List<BdAwards>> awardsDto = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        if (memberTeamInfoParam.getQueryDate() == null) {

            // 秒结
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtil.offsetDay(new Date(), -1));
            csPeriod = memberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            settleTableName = TableNameConstants.CU_MEMBER_SECOND + csPeriod.getPkId();
        } else {
            String queryDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, memberTeamInfoParam.getQueryDate());
            String currentDate = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtils.currentDate());
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, memberTeamInfoParam.getQueryDate());
            csPeriod = memberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            if (queryDate.equals(currentDate)) {
                settleTableName = TableNameConstants.CU_MEMBER_SECOND + csPeriod.getPkId();
            } else {
                // 历史
                settleTableName = TableNameConstants.CU_MEMBER_SETTLE + csPeriod.getPkId();
            }
        }
        if (StringUtils.isNotBlank(memberTeamInfoParam.getMemberCode())) {
            memberTeamInfoParam.setSettleTableName(settleTableName);
            memberTeamInfoParam.setPeriod(csPeriod.getPkId());
            startPage();
            //           if (memberTeamInfoParam.getRelaType() == null || memberTeamInfoParam.getRelaType().equals(ERealType.XY.getIntValue())){
            memberTeamList = memberTeamService.queryMemberTeamInfoList(memberTeamInfoParam);
//            }else {
//                memberTeamList = memberTeamService.queryMemberByPlaceParentTeamInfoList(memberTeamInfoParam);
//            }
        }
        for (MemberTeamVo memberTeamVo : memberTeamList) {
            // 查询安置层级
            if (memberTeamVo.getPlaceDept() != null) {
                memberTeamVo.setPlaceDept(memberTeamVo.getPlaceDept());
                memberTeamVo.setPlaceDeptStr(EPlaceDept.getEPlaceDept(memberTeamVo.getPlaceDept()));
            }
            if (memberTeamVo.getPkAwards() != null) {
                for (BdAwards date : awardsDto.getData()) {
                    if (memberTeamVo.getPkAwards().equals(date.getPkId())) {
                        memberTeamVo.setPkAwardsStr(date.getAwardsName());
                    }
                }
            }
            if (memberTeamVo.getPkPlaceParent() != null) {
                CuMember member = cuMemberService.getMember(memberTeamVo.getPkPlaceParent());
                if (member != null) {
                    memberTeamVo.setPlaceParentCode(member.getMemberCode());
                }
            }
            memberTeamVo.setResettleLevel(memberTeamVo.getLevel());
            //TODO 血缘代数
            memberTeamVo.setConsanguinityAlgebra("第" + memberTeamVo.getLevel() + "代");
            //TODO 奖金大盘占比
            memberTeamVo.setBonusLargeMarketProportion(BigDecimal.ZERO);
            // 直推人数
            Long directPushPeopleNumber = memberTreeService.queryCuMemberTreeParentTableCount(settleTableName, memberTeamVo.getMemberId());
            memberTeamVo.setDirectPushPeopleNumber(directPushPeopleNumber);
            // 转账次数
            QueryWrapper<CuMemberTransfer> qew = new QueryWrapper<>();
            qew.eq("PK_MEMBER", memberTeamVo.getMemberId());
            int memberTransferCount = memberTransferService.count(qew);
            memberTeamVo.setMemberTransferCount(memberTransferCount);

            // 提现次数
            QueryWrapper<CuMemberWithdraw> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_MEMBER", memberTeamVo.getMemberId());
            int memberWithdrawCount = memberWithdrawService.count(queryWrapper);
            memberTeamVo.setWithdrawalNumber(memberWithdrawCount);
            // 最后一次登录时间
            if (memberTeamVo.getLastLoginTime() != null) {
                // 计算当前时间和 最后一次登陆时间间隔
                memberTeamVo.setLastLoginTimeIntervalDays(DateUtil.betweenDay(DateUtils.currentDate(), memberTeamVo.getLastLoginTime(), true));
            }
        }
        return getDataTable(memberTeamList);
    }

    /**
     * 会员团队信息导出
     */
    @PostMapping("member-team-info-export")
    public void memberTeamInfoExport(MemberTeamInfoParam memberTeamInfoParam, HttpServletResponse response) {
        String time;
        String settleTableName;
        CuMemberSettlePeriod csPeriod;
        List<MemberTeamVo> memberTeamList = new ArrayList<>();
        R<List<BdAwards>> awardsDto = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
        if (memberTeamInfoParam.getQueryDate() == null) {
            // 秒结
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, DateUtil.offsetDay(new Date(), -1));
            csPeriod = memberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            settleTableName = TableNameConstants.CU_MEMBER_SECOND + csPeriod.getPkId();
        } else {
            // 历史
            time = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, memberTeamInfoParam.getQueryDate());
            csPeriod = memberSettlePeriodService.getCuMemberSettlePeriodByDate(time);
            settleTableName = TableNameConstants.CU_MEMBER_SETTLE + csPeriod.getPkId();
        }
        if (StringUtils.isNotBlank(memberTeamInfoParam.getMemberCode())) {
            memberTeamInfoParam.setSettleTableName(settleTableName);
            memberTeamInfoParam.setPeriod(csPeriod.getPkId());
            startPage();
            memberTeamList = memberTeamService.queryMemberTeamInfoList(memberTeamInfoParam);
        }
        for (MemberTeamVo memberTeamVo : memberTeamList) {
            // 查询安置层级

            if (memberTeamVo.getPlaceDept() != null) {
                memberTeamVo.setPlaceDept(memberTeamVo.getPlaceDept());
                memberTeamVo.setPlaceDeptStr(EPlaceDept.getEPlaceDept(memberTeamVo.getPlaceDept()));
            }
            if (memberTeamVo.getPkAwards() != null) {
                for (BdAwards date : awardsDto.getData()) {
                    if (memberTeamVo.getPkAwards().equals(date.getPkId())) {
                        memberTeamVo.setPkAwardsStr(date.getAwardsName());
                    }
                }
            }
            if (memberTeamVo.getPkPlaceParent() != null) {
                CuMember member = cuMemberService.getMember(memberTeamVo.getPkPlaceParent());
                if (member != null) {
                    memberTeamVo.setPlaceParentCode(member.getMemberCode());
                }
            }


            memberTeamVo.setResettleLevel(memberTeamVo.getLevel());

            //TODO 血缘代数
            memberTeamVo.setConsanguinityAlgebra("第" + memberTeamVo.getLevel() + "代");
            //TODO 奖金大盘占比
            memberTeamVo.setBonusLargeMarketProportion(BigDecimal.ZERO);
            // 直推人数
            Long directPushPeopleNumber = memberTreeService.queryCuMemberTreeParentTableCount(settleTableName, memberTeamVo.getMemberId());
            memberTeamVo.setDirectPushPeopleNumber(directPushPeopleNumber);
            // 转账次数
            QueryWrapper<CuMemberTransfer> qew = new QueryWrapper<>();
            qew.eq("PK_MEMBER", memberTeamVo.getMemberId());
            int memberTransferCount = memberTransferService.count(qew);
            memberTeamVo.setMemberTransferCount(memberTransferCount);

            // 提现次数
            QueryWrapper<CuMemberWithdraw> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("PK_MEMBER", memberTeamVo.getMemberId());
            int memberWithdrawCount = memberWithdrawService.count(queryWrapper);
            memberTeamVo.setWithdrawalNumber(memberWithdrawCount);
            // 最后一次登录时间
            if (memberTeamVo.getLastLoginTime() != null) {
                // 计算当前时间和 最后一次登陆时间间隔
                memberTeamVo.setLastLoginTimeIntervalDays(DateUtil.betweenDay(DateUtils.currentDate(), memberTeamVo.getLastLoginTime(), true));
            }
        }
        ExcelUtil<MemberTeamVo> util = new ExcelUtil<>(MemberTeamVo.class);
        util.exportExcel(response, memberTeamList, "会员团队信息");
    }

    /**
     * 免密登录
     **/
    @GetMapping("/password-free")
    public AjaxResult passwordFree(CuMemberVO cuMemberVO) {
        // 免密登录
        LoginMember loginMember = iMemberLoginService.passwordFreelogin(cuMemberVO.getMemberCode());
        // 获取登录token
        return AjaxResult.success(memberTokenService.createToken(loginMember));
    }


    /**
     * 导出真实信息
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFORMATION, method = EOperationMethod.EXPORT)
    @PostMapping("/real-info-export")
    public void realInfoExport(HttpServletResponse response, MemberRealInfoParam memberRealInfoParam) {
        memberRealInfoParam.setPkCountry(SecurityUtils.getPkCountry());
//        if (null == memberRealInfoParam.getStartCreationTime() || null == memberRealInfoParam.getEndCreationTime()) {
//             throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.CREATION_TIME_RANGE));
//        }
//        Integer days = DateUtils.betweenDay(memberRealInfoParam.getStartCreationTime(), memberRealInfoParam.getEndCreationTime());
//        if (days > 365) {
//             throw new ServiceException(TransactionUtils.getContent(ConfigMsgConstants.ONE_YEAR_DATA));
//        }
        List<MemberRealInfoVO> resultList = cuMemberService.selectByMemberRealInfo(memberRealInfoParam);
        // 获取需要翻译的枚举翻译
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(ECardType.values(),
                ESex.values()
        );
        //数据库内容翻译
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE,
                EnumsPrefixConstants.KEY_AWARD);
        if (CollectionUtil.isNotEmpty(resultList)) {
//            R<List<BdAwards>> awardsListDate = awardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
//            // 奖衔
//            List<BdAwards> awardsList = awardsListDate.getData();
//            R<List<GradeDTO>> gradeListDate = gradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
//            // 等级
//            List<GradeDTO> gradeList = gradeListDate.getData();
            Map<Integer, String> areaDate = areaServiceApi.getAreaMap(SecurityUtils.getPkCountry()).getData();
            for (MemberRealInfoVO cuMemberExt : resultList) {
                cuMemberExt.setRegisterGradeVal(transactionMap1.get(cuMemberExt.getPkRegisterGrade()));
                cuMemberExt.setSettleGradeVal(transactionMap1.get(cuMemberExt.getPkSettleGrade()));
                cuMemberExt.setAwardsVal(transactionMap1.get(cuMemberExt.getPkAwards()));
                if (cuMemberExt.getPkProvince() != null) {
                    // 省
                    cuMemberExt.setProvinceName(areaDate.get(cuMemberExt.getPkProvince()));
                }
                if (cuMemberExt.getPkCity() != null) {
                    // 市
                    cuMemberExt.setCityName(areaDate.get(cuMemberExt.getPkCity()));
                }
                if (cuMemberExt.getPkCounty() != null) {
                    // 区县
                    cuMemberExt.setCountyName(areaDate.get(cuMemberExt.getPkCounty()));
                }
                // 证件类型
                if (cuMemberExt.getCardType() != null) {
                    cuMemberExt.setCardTypeVal(transactionMap.get(cuMemberExt.getCardType()));
                }
                // 性别
                if (cuMemberExt.getSex() != null) {
                    cuMemberExt.setSexVal(transactionMap.get(cuMemberExt.getSex()));
                }
                // 生日
                if (StringUtils.isNotBlank(cuMemberExt.getIdCard())) {
                    cuMemberExt.setBirthDate(IdcardUtil.getBirthDate(cuMemberExt.getIdCard()));
                }
                if (cuMemberExt.getIdType() != null) {
                    cuMemberExt.setCardTypeVal(EIdType.getLabel(cuMemberExt.getIdType()));
                }
            }
        }
        ExcelUtil<MemberRealInfoVO> util = new ExcelUtil<>(MemberRealInfoVO.class, iMenuColumnServiceApi.queryMenuColumn("RealInfo", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, resultList, "真实信息");
    }

    /**
     * 奖金年金明细列表
     *
     * @return
     */
    @GetMapping("get-member-annuity-list")
    public TableDataInfo getMemberAnnuityList(String memberCode, String memberName, Integer pkAwards, Integer pkGrade, Date startDate, Date endDate) {
        startPage();
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (endDate != null) {
            endDate = DateUtils.getEndTime(endDate);
        }
        List<MemberAnnuityVo> list = memberAnnuityService.selectByList(memberCode, memberName, pkAwards, pkGrade, startDate, endDate, pkCountry);
        return getDataTable(list);
    }

    /**
     * 奖金年金明细列表 导出
     */
    @PostMapping("get-member-annuity-list-export")
    public void getMemberAnnuityListExport(String memberCode, String memberName, Integer pkAwards, Integer pkGrade, Date startDate, Date endDate, HttpServletResponse response) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        if (endDate != null) {
            endDate = DateUtils.getEndTime(endDate);
        }
        List<MemberAnnuityVo> resultList = memberAnnuityService.selectByList(memberCode, memberName, pkAwards, pkGrade, startDate, endDate, pkCountry);

        ExcelUtil<MemberAnnuityVo> util = new ExcelUtil<>(MemberAnnuityVo.class);
        util.exportExcel(response, resultList, "奖金年金明细列表");
    }


    /**
     * 查询会员部门
     *
     * @return
     */
    @GetMapping("get-member-dept")
    public AjaxResult getMemberDept(Long pkMember) {

        Set<Integer> resultList = new HashSet<>();
        // 根据会员编号查询会员的最大部门
        Integer memberMaxDept = cuMemberService.getMaxMemberDept(pkMember);
        if (memberMaxDept != null) {
            resultList.add(memberMaxDept + 1);
        } else {
            // 如果没有部门则默认从1 开始
            resultList.add(EYesNo.NO.getIntValue());
        }
        // 查询未撤单
        List<CuMemberExt> rsList = cuMemberService.getNotDelPlaceParentMember(pkMember);
        Set<Integer> memberDeptSet = new HashSet<>();
        for (CuMemberExt cuMemberExt : rsList) {
            memberDeptSet.add(cuMemberExt.getPlaceDept());
        }
        // 查询丢失部门
        Set<Integer> missingSet = NumberUtil.findMissing(memberDeptSet);

        // 排序
        TreeSet<Integer> set = new TreeSet<>((Comparator.naturalOrder()));
        set.addAll(resultList);
        set.addAll(missingSet);
        return AjaxResult.success(set);
    }
}
