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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hzs.common.core.annotation.AccessPermissions;
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.VertexConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
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.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.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.common.util.TransactionUtils;
import com.hzs.member.base.dto.LoginMember;
import com.hzs.member.base.dto.MemberBusinessTemplate;
import com.hzs.member.base.param.*;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.vo.*;
import com.hzs.member.login.service.IMemberLoginService;
import com.hzs.member.swing.param.CuMemberSwingNetParam;
import com.hzs.member.swing.vo.CuMemberRetVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
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.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/manager/member")
@RestController
public class CuMemberController extends BaseController {

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private MemberTokenService memberTokenService;
    @Autowired
    private IMemberLoginService iMemberLoginService;

    @DubboReference
    IUserServiceApi iUserServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IMenuColumnServiceApi iMenuColumnServiceApi;

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


    /**
     * 导入批量查询会员信息
     **/
    @Log(module = EOperationModule.SPECIAL_BUSINESS, business = EOperationBusiness.MODIFY_CODE, method = EOperationMethod.IMPORT)
    @PostMapping("/batch-importData")
    public AjaxResult batchImportData(MultipartFile file) throws Exception {
        ExcelUtil<CuMemberImportVO> util = new ExcelUtil<>(CuMemberImportVO.class);
        StringBuilder memberCodeStr = new StringBuilder();
        List<CuMemberImportVO> memberCodeList = util.importExcel(file.getInputStream());
        if (CollectionUtil.isNotEmpty(memberCodeList)) {
            List<CuMemberImportVO> distinctList = new ArrayList<>(memberCodeList.stream()
                    .collect(Collectors.toMap(CuMemberImportVO::getMemberCode,
                            vo -> vo,
                            (existing, replacement) -> existing))
                    .values());
            for (CuMemberImportVO cu : distinctList) {
                memberCodeStr.append(cu.getMemberCode()).append(",");
            }
        }
        return AjaxResult.success(memberCodeStr.toString());
    }

    /**
     * 获取会员账户信息值
     *
     * @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;
    }


    /**
     * 真实信息
     **/
    @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 = iCuMemberService.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());
                }
            }
        }
        return getDataTable(cuMemberVOS);
    }

    /**
     * 根据会员编号查询会员信息
     **/
    @GetMapping("/getOne/{memberCode}")
    public AjaxResult getOne(@PathVariable String memberCode) {
        CuMember cuMember = iCuMemberService.getMember(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 = iCuMemberService.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
     */
    @AccessPermissions("RealInfo")
    @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());
        memberRealInfoParam.setSystemType(SecurityUtils.getSystemType());

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

        startPage();
        List<MemberRealInfoVO> resultList = iCuMemberService.selectByMemberRealInfo(memberRealInfoParam);
        if (CollectionUtil.isNotEmpty(resultList)) {
            // 奖衔
            R<List<BdAwards>> awardsListDate = iAwardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
            List<BdAwards> awardsList = awardsListDate.getData();
            // 等级
            R<List<GradeDTO>> gradeListDate = iGradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
            List<GradeDTO> gradeList = gradeListDate.getData();

            for (MemberRealInfoVO cuMemberExt : resultList) {
                // 注册等级
                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());
                        }
                    }
                }
                cuMemberExt.setCardTypeVal(EIdType.getLabelByValue(cuMemberExt.getIdType()));
                cuMemberExt.setSexVal(ESex.getLabelByValue(cuMemberExt.getSex()));
            }
        }

        return getDataTable(resultList);
    }

    /**
     * 导出真实信息
     **/
    @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());
        memberRealInfoParam.setSystemType(SecurityUtils.getSystemType());

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

        List<MemberRealInfoVO> resultList = iCuMemberService.selectByMemberRealInfo(memberRealInfoParam);
        if (CollectionUtil.isNotEmpty(resultList)) {
            // 奖衔
            R<List<BdAwards>> awardsListDate = iAwardsServiceApi.queryAwards(SecurityUtils.getPkCountry());
            List<BdAwards> awardsList = awardsListDate.getData();
            // 等级
            R<List<GradeDTO>> gradeListDate = iGradeServiceApi.queryGradeList(SecurityUtils.getPkCountry());
            List<GradeDTO> gradeList = gradeListDate.getData();

            for (MemberRealInfoVO cuMemberExt : resultList) {
                // 注册等级
                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 (cuMemberExt.getPkMaxAwards() != null) {
                    for (BdAwards awards : awardsList) {
                        if (awards.getPkId().equals(cuMemberExt.getPkMaxAwards())) {
                            cuMemberExt.setAwardsVal(awards.getAwardsName());
                        }
                    }
                }
                cuMemberExt.setCardTypeVal(EIdType.getLabelByValue(cuMemberExt.getIdType()));
                cuMemberExt.setSexVal(ESex.getLabelByValue(cuMemberExt.getSex()));
            }
        }
        ExcelUtil<MemberRealInfoVO> util = new ExcelUtil<>(MemberRealInfoVO.class, iMenuColumnServiceApi.queryMenuColumn("RealInfo", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, resultList, "真实信息");
    }


    /**
     * 下载模板
     *
     * @param response
     * @param
     */
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.MEMBER_INFORMATION, method = EOperationMethod.DOWNLOAD)
    @PostMapping("/download")
    public void download(HttpServletResponse response) {
        List<CuMemberImportVO> list = new ArrayList<>();
        ExcelUtil<CuMemberImportVO> util = new ExcelUtil<>(CuMemberImportVO.class);
        util.exportExcel(response, list, "会员编号");
    }

    /**
     * 查询顶点会员
     *
     * @return
     */
    @GetMapping("/query-top-member")
    public AjaxResult queryTopMember() {
        List<TopMemberVO> resultList = new ArrayList<>();
        List<CuMemberExt> list = iCuMemberService.queryPlaceMemberList(VertexConstants.GJ30720200CODE, SecurityUtils.getPkCountry());
        if (CollectionUtil.isNotEmpty(list)) {
            resultList = BeanUtil.copyToList(list, TopMemberVO.class);
        }
        return AjaxResult.success(resultList);
    }

    /**
     * 用户消费统计
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_CONSUMPTION, method = EOperationMethod.SELECT)
    @GetMapping("/member_consumption_stat")
    public TableDataInfo getMemberConsumptionStat(MemberConsumptionStatParam memberConsumptionStatParam) {
        if (StringUtils.isNotBlank(memberConsumptionStatParam.getPkProducts())) {
            String[] productId = memberConsumptionStatParam.getPkProducts().split(",");
            memberConsumptionStatParam.setPkProductList(Arrays.asList(productId));
        }
        if (memberConsumptionStatParam.getStartPayTime() != null) {
            memberConsumptionStatParam.setStartPayTime(DateUtils.getStartTime(memberConsumptionStatParam.getStartPayTime()));
        }
        if (memberConsumptionStatParam.getEndPayTime() != null) {
            memberConsumptionStatParam.setEndPayTime(DateUtils.getEndTime(memberConsumptionStatParam.getEndPayTime()));
        }
        // 中国汇率
        R<CurrencyDTO> chinaCurrency = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
        BigDecimal chinaInExchangeRate = chinaCurrency.getData().getInExchangeRate();
        startPage();
        memberConsumptionStatParam.setPkCountry(SecurityUtils.getPkCountry());
        List<MemberConsumptionStatVo> memberConsumptionStatVoList = iCuMemberService.getMemberConsumptionStat(memberConsumptionStatParam);
        for (MemberConsumptionStatVo memberConsumptionStatVo : memberConsumptionStatVoList) {
            memberConsumptionStatVo.setOrderAchieve(memberConsumptionStatVo.getOrderAchieve().multiply(chinaInExchangeRate).setScale(2, BigDecimal.ROUND_HALF_UP));
        }

        return getDataTable(memberConsumptionStatVoList);
    }

    /**
     * 用户消费统计
     */
    @Log(module = EOperationModule.STATISTIC_ANALYSIS, business = EOperationBusiness.MEMBER_CONSUMPTION, method = EOperationMethod.EXPORT)
    @PostMapping("member_consumption_stat_export")
    public void getMemberConsumptionStatExport(MemberConsumptionStatParam memberConsumptionStatParam, HttpServletResponse response) {
        if (StringUtils.isNotBlank(memberConsumptionStatParam.getPkProducts())) {
            String[] productId = memberConsumptionStatParam.getPkProducts().split(",");
            memberConsumptionStatParam.setPkProductList(Arrays.asList(productId));
        }
        if (memberConsumptionStatParam.getStartPayTime() != null) {
            memberConsumptionStatParam.setStartPayTime(DateUtils.getStartTime(memberConsumptionStatParam.getStartPayTime()));
        }
        if (memberConsumptionStatParam.getEndPayTime() != null) {
            memberConsumptionStatParam.setEndPayTime(DateUtils.getEndTime(memberConsumptionStatParam.getEndPayTime()));
        }
        // 中国汇率
        R<CurrencyDTO> chinaCurrency = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY);
        BigDecimal chinaInExchangeRate = chinaCurrency.getData().getInExchangeRate();
        memberConsumptionStatParam.setPkCountry(SecurityUtils.getPkCountry());
        List<MemberConsumptionStatVo> memberConsumptionStatVoList = iCuMemberService.getMemberConsumptionStat(memberConsumptionStatParam);
        for (MemberConsumptionStatVo memberConsumptionStatVo : memberConsumptionStatVoList) {
            memberConsumptionStatVo.setOrderAchieve(memberConsumptionStatVo.getOrderAchieve().multiply(chinaInExchangeRate).setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        ExcelUtil<MemberConsumptionStatVo> util = new ExcelUtil<>(MemberConsumptionStatVo.class);
        util.exportExcel(response, memberConsumptionStatVoList, "用户消费统计");
    }

    /**
     * 会员奖衔查询
     */
    @AccessPermissions("memberFind")
    @GetMapping("/member_awards_query")
    public TableDataInfo memberAwardsQuery(MemberAwardsQueryParam param) {
        startPage();
        List<MemberAwardsQueryVO> memberAwardsList = iCuMemberService.listMemberAwards(param, SecurityUtils.getPkCountry());
        if (CollectionUtil.isNotEmpty(memberAwardsList)) {
            // 中国汇率
            CurrencyDTO currency = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY).getData();

            for (MemberAwardsQueryVO vo : memberAwardsList) {
                if (vo.getPkAwards() > vo.getPkMaxAwards()) {
                    // 当月奖衔 大于 最高奖衔，最高奖衔就为当月奖衔
                    vo.setPkMaxAwards(vo.getPkAwards());
                    vo.setMaxAwardsName(vo.getAwardsName());
                }
                if (null != vo.getNewPv()) {
                    vo.setNewPv(vo.getNewPv().multiply(currency.getInExchangeRate()));
                }
            }
        }
        return getDataTable(memberAwardsList);
    }

    /**
     * 会员奖衔导出
     */
    @PostMapping("/member_awards_query_export")
    public void memberAwardsQueryExport(MemberAwardsQueryParam param, HttpServletResponse response) {
        List<MemberAwardsQueryVO> memberAwardsList = iCuMemberService.listMemberAwards(param, SecurityUtils.getPkCountry());
        if (CollectionUtil.isNotEmpty(memberAwardsList)) {
            // 中国汇率
            CurrencyDTO currency = iCurrencyServiceApi.getCurrency(CountryConstants.CHINA_COUNTRY).getData();

            for (MemberAwardsQueryVO vo : memberAwardsList) {
                if (vo.getPkAwards() > vo.getPkMaxAwards()) {
                    // 当月奖衔 大于 最高奖衔，最高奖衔就为当月奖衔
                    vo.setPkMaxAwards(vo.getPkAwards());
                    vo.setMaxAwardsName(vo.getAwardsName());
                }
                if (null != vo.getNewPv()) {
                    vo.setNewPv(vo.getNewPv().multiply(currency.getInExchangeRate()));
                }
            }
        }
        ExcelUtil<MemberAwardsQueryVO> util = new ExcelUtil<>(MemberAwardsQueryVO.class);
        util.exportExcel(response, memberAwardsList, "会员奖衔查询");
    }


    /**
     * 新零售会员信息
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.RETAIL_MEMBER_INFO, method = EOperationMethod.SELECT)
    @GetMapping("/query-member")
    public TableDataInfo retailMember(RetailMemberVO memberParam) {
        memberParam.setPkCountry(SecurityUtils.getPkCountry());

        List<String> memberCodeList = new ArrayList<>();
        List<RetailMemberVO> memberCodeList1 = new ArrayList<>();
        if (StringUtils.isNotEmpty(memberParam.getMemberCodeStr())) {
            memberCodeList = Arrays.asList(memberParam.getMemberCodeStr().split(","));
            if (CollectionUtil.isNotEmpty(memberCodeList)) {
                memberParam.setMemberCodeList(memberCodeList);
            }
            for (String st : memberCodeList) {
                RetailMemberVO cu = new RetailMemberVO();
                cu.setMemberCode(st);
                memberCodeList1.add(cu);
            }
        }

        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();
        List<RetailMemberVO> cuMemberVOList = iCuMemberService.retailMemberList(memberParam);

        if (CollectionUtil.isNotEmpty(cuMemberVOList)) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(
                    EMemberAccount.values(), EYesNoAttestation.values(), EOrderSource.values()
                    , EAccountStatus.values(), EWalletStatus.values(), ECategory.values(), EIncomeStatus.values()
                    , EDealerYesNo.values());

            cuMemberVOList.forEach(cvo -> {
                CuMemberVO cmvo = BeanUtil.copyProperties(cvo, CuMemberVO.class);
                if (StringUtils.isNotNull(memberParam.getIsConsume()) &&
                        (memberParam.getIsConsume() == EMemberAccount.PROHIBIT_CONSUME.getValue()
                                || memberParam.getIsConsume() == EMemberAccount.WHOLE_TRANSFER.getValue())) {
                    cvo.setMemberAccountVal(getMemberAccountVal(cmvo, transactionMap));
                }

                if (StringUtils.isNull(cvo.getDirectPushNumber())) {
                    cvo.setDirectPushNumber(0);
                }
                if (StringUtils.isNull(cvo.getChangeNumber())) {
                    cvo.setChangeNumber(0);
                }
                if ((cvo.getCategory() != null && cvo.getCategory() == ECategory.DEAD_POINT.getValue()) ||
                        (cvo.getCustomerType() != null && 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.setIsRealNameVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getIsRealName()));
                cvo.setOrderSourceVal(transactionMap.get(EnumsPrefixConstants.ORDER_SOURCE + cvo.getOrderSource()));
                cvo.setMemberAccountVal(getMemberAccountVal(cmvo, transactionMap));
                cvo.setWalletStatusVal(transactionMap.get(EnumsPrefixConstants.WALLET_STATUS + cvo.getWalletStatus()));
                cvo.setAccountStatusVal(transactionMap.get(EnumsPrefixConstants.ACCOUNT_STATUS + cvo.getAccountStatus()));
                cvo.setIncomeStatusVal(transactionMap.get(EnumsPrefixConstants.INCOME_STATUS + cvo.getIncomeStatus()));
                cvo.setIsActivateVal(transactionMap.get(EnumsPrefixConstants.DEALER_YES_NO + cvo.getIsActivate()));
            });
        }
        if (CollectionUtil.isNotEmpty(cuMemberVOList) && CollectionUtil.isNotEmpty(memberCodeList) &&
                cuMemberVOList.size() != memberCodeList.size()) {
            Set<String> bFieldSet = cuMemberVOList.stream()
                    .map(RetailMemberVO::getMemberCode)  // 假设Item类中有一个名为getField的方法来获取某个字段
                    .collect(Collectors.toSet());
            List<RetailMemberVO> result = memberCodeList1.stream()
                    .filter(item -> !bFieldSet.contains(item.getMemberCode()))
                    .collect(Collectors.toList());
            cuMemberVOList.addAll(result);
        }
        TableDataInfo tableDataInfo = getDataTable(cuMemberVOList);
        tableDataInfo.setRows(cuMemberVOList);
        return tableDataInfo;
    }


    /**
     * 导出新零售
     **/
    @Log(module = EOperationModule.MEMBER_INFORMATION, business = EOperationBusiness.RETAIL_MEMBER_INFO, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void excelRetailMember(HttpServletResponse response, RetailMemberVO memberParam) {
        memberParam.setPkCountry(SecurityUtils.getPkCountry());
        memberParam.setSystemType(SecurityUtils.getSystemType());

        List<String> memberCodeList = new ArrayList<>();
        List<RetailMemberVO> memberCodeList1 = new ArrayList<>();
        if (StringUtils.isNotEmpty(memberParam.getMemberCodeStr())) {
            memberCodeList = Arrays.asList(memberParam.getMemberCodeStr().split(","));
            if (CollectionUtil.isNotEmpty(memberCodeList)) {
                memberParam.setMemberCodeList(memberCodeList);
            }
            for (String st : memberCodeList) {
                RetailMemberVO cu = new RetailMemberVO();
                cu.setMemberCode(st);
                memberCodeList1.add(cu);
            }
        }
        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());

        List<RetailMemberVO> cuMemberVOList = iCuMemberService.retailMemberList(memberParam);

        if (CollectionUtil.isNotEmpty(cuMemberVOList)) {
            // 获取需要翻译的枚举翻译
            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(
                    EMemberAccount.values(), EYesNoAttestation.values(), EOrderSource.values()
                    , EAccountStatus.values(), EWalletStatus.values(), ECategory.values(), EIncomeStatus.values()
                    , EDealerYesNo.values());

            cuMemberVOList.forEach(cvo -> {
                CuMemberVO cmvo = BeanUtil.copyProperties(cvo, CuMemberVO.class);
                if (StringUtils.isNotNull(memberParam.getIsConsume()) &&
                        (memberParam.getIsConsume() == EMemberAccount.PROHIBIT_CONSUME.getValue()
                                || memberParam.getIsConsume() == EMemberAccount.WHOLE_TRANSFER.getValue())) {
                    cvo.setMemberAccountVal(getMemberAccountVal(cmvo, transactionMap));
                }

                if (StringUtils.isNull(cvo.getDirectPushNumber())) {
                    cvo.setDirectPushNumber(0);
                }
                if (StringUtils.isNull(cvo.getChangeNumber())) {
                    cvo.setChangeNumber(0);
                }
                if ((cvo.getCategory() != null && cvo.getCategory() == ECategory.DEAD_POINT.getValue()) ||
                        (cvo.getCustomerType() != null && 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.setIsRealNameVal(transactionMap.get(EnumsPrefixConstants.YES_NO_ATTESTATION + cvo.getIsRealName()));
                cvo.setOrderSourceVal(transactionMap.get(EnumsPrefixConstants.ORDER_SOURCE + cvo.getOrderSource()));
                cvo.setMemberAccountVal(getMemberAccountVal(cmvo, transactionMap));
                cvo.setWalletStatusVal(transactionMap.get(EnumsPrefixConstants.WALLET_STATUS + cvo.getWalletStatus()));
                cvo.setAccountStatusVal(transactionMap.get(EnumsPrefixConstants.ACCOUNT_STATUS + cvo.getAccountStatus()));
                cvo.setIncomeStatusVal(transactionMap.get(EnumsPrefixConstants.INCOME_STATUS + cvo.getIncomeStatus()));
                cvo.setIsActivateVal(transactionMap.get(EnumsPrefixConstants.DEALER_YES_NO + cvo.getIsActivate()));
            });
        }
        if (CollectionUtil.isNotEmpty(cuMemberVOList) && CollectionUtil.isNotEmpty(memberCodeList) &&
                cuMemberVOList.size() != memberCodeList.size()) {
            Set<String> bFieldSet = cuMemberVOList.stream()
                    .map(RetailMemberVO::getMemberCode)  // 假设Item类中有一个名为getField的方法来获取某个字段
                    .collect(Collectors.toSet());
            List<RetailMemberVO> result = memberCodeList1.stream()
                    .filter(item -> !bFieldSet.contains(item.getMemberCode()))
                    .collect(Collectors.toList());
            cuMemberVOList.addAll(result);
        }
        ExcelUtil<RetailMemberVO> util = new ExcelUtil<>(RetailMemberVO.class, iMenuColumnServiceApi.queryMenuColumn("Member", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, cuMemberVOList, "新零售会员信息");
    }

    /**
     * 查询会员信息
     *
     * @param param
     * @return
     */
    @PostMapping("/query-member-info")
    public AjaxResult queryMember(@RequestBody CuMemberSwingNetParam param) {
        if (StringUtils.isEmpty(param.getMemberCode())) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }
        CuMember cuMember = iCuMemberService.getMember(param.getMemberCode());
        if (cuMember == null) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }
        return AjaxResult.success(BeanUtil.copyProperties(cuMember, CuMemberRetVO.class));
    }

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

    /**
     * 复制密码
     *
     * @return
     */
    @GetMapping("/copy-pwd")
    public AjaxResult copyPwd(@RequestParam Long pkId) {
        CuMember cuMember = iCuMemberService.getOne(Wrappers.<CuMember>lambdaQuery()
                .eq(CuMember::getPkId, pkId)
        );
        String tmpPwd = DateUtils.parseDateToFormat(DateUtils.MM_DD, new Date()) + cuMember.getLoginPassword();
        return AjaxResult.success("", Base64Encoder.encode(tmpPwd.getBytes(StandardCharsets.UTF_8)));
    }

}
