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

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hzs.common.core.annotation.RepeatSubmitSimple;
import com.hzs.common.core.config.BdConfig;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.constant.msg.ConfigMsgConstants;
import com.hzs.common.core.constant.msg.MemberMsgConstants;
import com.hzs.common.core.domain.FileResult;
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.reflect.ReflectUtils;
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.CuMemberChangeLog;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.system.config.BdAgreementRenewalWhite;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.base.param.MemberDataParam;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.IMemberInfoService;
import com.hzs.common.core.utils.UploadFileUtil;
import com.hzs.member.base.vo.*;
import com.hzs.member.detail.service.ICuMemberChangeLogService;
import com.hzs.member.param.MemberParam;
import com.hzs.member.sms.service.IApiAliSmsService;
import com.hzs.system.base.ICountryServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CountryDTO;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.config.IAgreementRenewalWhiteServiceApi;
import com.hzs.system.config.IAwardsServiceApi;
import com.hzs.system.config.IGradeServiceApi;
import com.hzs.system.config.dto.GradeDTO;
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 java.math.BigDecimal;
import java.util.*;

/**
 * 会员控制器
 */
@Slf4j
@RequestMapping("/api/member")
@RestController
public class ApiMemberController extends BaseController {

    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private IMemberInfoService iMemberInfoService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberChangeLogService iCuMemberChangeLogService;
    @Autowired
    private IApiAliSmsService iApiAliSmsService;

    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    IAwardsServiceApi iAwardsServiceApi;
    @DubboReference
    ICountryServiceApi iCountryServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    IAgreementRenewalWhiteServiceApi iAgreementRenewalWhiteServiceApi;

    /**
     * 获取登录会员信息
     *
     * @return
     */
    @GetMapping("/get-info")
    public AjaxResult getInfo() {
        MemberInfoVO memberInfo = iMemberInfoService.getMemberInfo(SecurityUtils.getUserId());
        if (null == memberInfo) {
            return AjaxResult.error();
        }
        return AjaxResult.success(memberInfo);
    }

    /**
     * 获取个人资料
     *
     * @return
     */
    @GetMapping("/get-data")
    public AjaxResult getData() {
        return AjaxResult.success(iMemberInfoService.queryMemberData(SecurityUtils.getUserId()));
    }

    /**
     * 获取电子会员卡图
     *
     * @return
     */
    @GetMapping("/get-card")
    public AjaxResult getCard() {
        return AjaxResult.success(iMemberInfoService.queryMemberCard(SecurityUtils.getUserId()));
    }

    /**
     * 更新个人资料（昵称）
     *
     * @param param
     * @return
     */
    @PutMapping("/update-data")
    public AjaxResult updateData(@RequestBody MemberDataParam param) {
        if (StringUtils.isEmpty(param.getNickName())) {
            return AjaxResult.error("缺少参数");
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setNickName(param.getNickName());
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.NICK_NAME.getValue())
                .changeFront(member.getNickName())
                .changeAfter(param.getNickName())
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
        return AjaxResult.success();
    }

    /**
     * 更新头像
     *
     * @param file
     * @return
     */
    @PostMapping("/update-head")
    public AjaxResult updateHead(MultipartFile file) {
        if (null == file) {
            return AjaxResult.error("缺少参数");
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        FileResult fileResult = UploadFileUtil.upload(file, "head");
        if (null != fileResult) {
            // 会员修改信息
            CuMember cuMember = new CuMember();
            cuMember.setPkId(memberId);
            cuMember.setHeadPath(fileResult.getUrl());
            cuMember.setPkModified(memberId);
            cuMember.setModifiedTime(new Date());
            // 会员修改记录信息
            CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                    .pkMember(memberId)
                    .changeType(EMemberChangeType.HEAD.getValue())
                    .changeFront(member.getHeadPath())
                    .changeAfter(fileResult.getUrl())
                    .build();
            iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
            return AjaxResult.success(fileResult);
        }
        return AjaxResult.error();
    }

    /**
     * 更新密码
     *
     * @param param
     * @return
     */
    @PutMapping("/update-password")
    public AjaxResult updatePassword(@RequestBody MemberDataParam param) {
        if (StringUtils.isEmpty(param.getOldPassword())
                || StringUtils.isAllEmpty(param.getLoginPassword(), param.getPayPassword())) {
            return AjaxResult.error("缺少参数");
        }
        Long memberId = SecurityUtils.getUserId();
        CuMember member = iCuMemberService.getMemberById(memberId);
        if (null == member) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
        }

        if (StringUtils.isNotEmpty(param.getLoginPassword())) {
            // 修改登录密码
            if (SecurityUtils.matchesPassword(param.getOldPassword(), member.getLoginPwd())) {
                // 会员修改信息
                CuMember cuMember = new CuMember();
                cuMember.setPkId(memberId);
                cuMember.setLoginPwd(SecurityUtils.encryptPassword(param.getLoginPassword()));
                cuMember.setLoginPassword(param.getLoginPassword());
                cuMember.setPkModified(memberId);
                cuMember.setModifiedTime(new Date());
                // 会员修改记录信息
                CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                        .pkMember(memberId)
                        .changeType(EMemberChangeType.LOGIN_PWD.getValue())
                        .changeFront(member.getLoginPassword())
                        .changeAfter(param.getLoginPassword())
                        .build();
                iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
                return AjaxResult.success();
            } else {
                // 旧密码错误
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PASSWORD_ERROR));
            }
        } else if (StringUtils.isNotEmpty(param.getPayPassword())) {
            // 修改支付密码
            if (SecurityUtils.matchesPassword(param.getOldPassword(), member.getPayPwd())) {
                // 会员修改信息
                CuMember cuMember = new CuMember();
                cuMember.setPkId(memberId);
                cuMember.setPayPwd(SecurityUtils.encryptPassword(param.getPayPassword()));
                cuMember.setPayPassword(param.getPayPassword());
                cuMember.setPkModified(memberId);
                cuMember.setModifiedTime(new Date());
                // 会员修改记录信息
                CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                        .pkMember(memberId)
                        .changeType(EMemberChangeType.PAY_PWD.getValue())
                        .changeFront(member.getPayPassword())
                        .changeAfter(param.getPayPassword())
                        .build();
                iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
                return AjaxResult.success();
            } else {
                // 旧密码错误
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PASSWORD_ERROR));
            }
        }
        return AjaxResult.error();
    }

//    /**
//     * 更新邮箱
//     *
//     * @param param
//     * @return
//     */
//    @PutMapping("/update-email")
//    public AjaxResult updateEmail(@RequestBody MemberDataParam param) {
//        if (StringUtils.isEmpty(param.getEmail())) {
//            // 缺少参数
//            return AjaxResult.error("缺少参数");
//        }
//        if (StringUtils.isEmpty(param.getCode())) {
//            // 验证码不能为空
//            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.VERIFICATION_CODE_CANNOT_EMPTY));
//        }
//
//        Long memberId = SecurityUtils.getUserId();
//        CuMember member = iCuMemberService.getMemberById(memberId);
//        if (null == member) {
//            // 会员不存在
//            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_EXITS));
//        }
//
//        // 短信校验码校验
//        String checkStr = iApiSmsService.checkSms(ESmsTemplate.VERIFICATION.getCache() + memberId, param.getCode());
//        if (null != checkStr) {
//            return AjaxResult.error(checkStr);
//        }
//
//        // 会员修改信息
//        CuMember cuMember = new CuMember();
//        cuMember.setPkId(memberId);
//        cuMember.setEmail(param.getEmail());
//        cuMember.setPkModified(memberId);
//        cuMember.setModifiedTime(new Date());
//        // 会员修改记录信息
//        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
//                .pkMember(memberId)
//                .changeType(EMemberChangeType.EMAIL.getValue())
//                .changeFront(member.getEmail())
//                .changeAfter(param.getEmail())
//                .build();
//        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));
//        return AjaxResult.success();
//    }

    /**
     * 忘记密码更新
     *
     * @param param
     * @return
     */
    @PutMapping("/forget-password")
    public AjaxResult forgetPassword(@RequestBody MemberDataParam param) {
        if (StringUtils.isAnyEmpty(param.getMemberCode(), param.getCode(), param.getLoginPassword())) {
            return AjaxResult.error("缺少参数");
        }
        String loginPassword = param.getLoginPassword();
        CuMemberExt cuMemberExt = iCuMemberService.getMemberByCode(param.getMemberCode());
        if (null == cuMemberExt) {
            // 会员不存在，或者手机号不相同
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_INFO_ERROR));
        }
        Long memberId = cuMemberExt.getPkId();

        // 短信校验码校验
        String checkStr = iApiAliSmsService.checkRecoverCode(cuMemberExt.getPhone(), param.getCode(), cuMemberExt.getPkId());
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setLoginPwd(SecurityUtils.encryptPassword(loginPassword));
        cuMember.setLoginPassword(loginPassword);
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.LOGIN_PWD.getValue())
                .changeFront(cuMemberExt.getLoginPassword())
                .changeAfter(loginPassword)
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));

        return AjaxResult.success();
    }

    /**
     * 忘记支付密码更新
     *
     * @param param 入参
     * @return
     */
    @PutMapping("/forget-pay-password")
    public AjaxResult forgetPayPassword(@RequestBody MemberDataParam param) {
        if (StringUtils.isAnyEmpty(param.getCode(), param.getPayPassword())) {
            return AjaxResult.error("缺少参数");
        }
        String payPassword = param.getPayPassword();
        CuMemberExt cuMemberExt = iCuMemberService.getMemberById(SecurityUtils.getUserId());
        if (null == cuMemberExt) {
            // 会员不存在
            return AjaxResult.error(TransactionUtils.getContent(ConfigMsgConstants.MEMBER_NOT_EXIST));
        }
        Long memberId = cuMemberExt.getPkId();

        // 短信校验码校验
        String checkStr = iApiAliSmsService.checkPayPasswordCode(cuMemberExt.getPhone(), param.getCode(), memberId);
        if (null != checkStr) {
            return AjaxResult.error(checkStr);
        }

        // 会员修改信息
        CuMember cuMember = new CuMember();
        cuMember.setPkId(memberId);
        cuMember.setPayPwd(SecurityUtils.encryptPassword(payPassword));
        cuMember.setPayPassword(payPassword);
        cuMember.setPkModified(memberId);
        cuMember.setModifiedTime(new Date());
        // 会员修改记录信息
        CuMemberChangeLog cuMemberChangeLog = CuMemberChangeLog.builder()
                .pkMember(memberId)
                .changeType(EMemberChangeType.PAY_PWD.getValue())
                .changeFront(cuMemberExt.getPayPassword())
                .changeAfter(payPassword)
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));

        return AjaxResult.success();
    }

//    /**
//     * @param memberParam 订单参数
//     * @Description: 确认注册订单，生成待支付订单,只有注册订单有待支付订单
//     * @return: AjaxResult
//     * @Author: sui q
//     * @Date: 2022/8/27 16:47
//     */
//    @RepeatSubmit
//    @PostMapping("/reg-share-member")
//    public AjaxResult confirmRegisterOrder(@RequestBody MemberParam memberParam) {
//        if (EEnv.TEST.getValue().equals(BdConfig.getEnv())) {
//            if (new Date().getTime() >= SysConstants.CLOSE_ZERO_DATE_TEST) {
//                return AjaxResult.error("二维码已停用，请联系相应亲友协助办理注册");
//            }
//        } else {
//            if (new Date().getTime() >= SysConstants.CLOSE_ZERO_DATE_ONLINE) {
//                return AjaxResult.error("二维码已停用，请联系相应亲友协助办理注册");
//            }
//        }
//
//        // 验证必输项
//        if (validateFieldNotNull(memberParam, memberParam.getValidConfirmField())) {
//            return AjaxResult.error(MemberMsgConstants.REQUIRED_NOT_EMPTY);
//        }
//        // 验证CN后是否全部数字
//        String memberCode = memberParam.getMemberCode();
//        AjaxResult memberCodeResult = validateMemberCode(memberCode);
//        if (memberCodeResult != null) {
//            return memberCodeResult;
//        }
//        // 上级编码（推荐人）
//        Long pkParent = Long.parseLong(new String(Base64Decoder.decode(memberParam.getParent())));
//        memberParam.setPkParent(pkParent);
//        // 验证推荐人
//        CuMember cuMember = iCuMemberService.getMember(memberParam.getPkParent());
//        if (cuMember == null) {
//            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.PARENT_NOT_EXISTS));
//        }
//
//        // 验证一个手机号可以注册多少次
//        // 验证手机号注册次数
//        List<CuMemberExt> cuMemberExtList = iCuMemberService.getMemberInfoByCondition(CuMember.builder().phone(memberParam.getPhone()).pkSettleGrade(EGrade.START_UP.getValue()).pkSettleCountry(cuMember.getPkSettleCountry()).build());
//        // 系统中存在该手机号走的验证
//        if (cuMemberExtList.size() > 0) {
//            // 手机号注册次数
//            String value = iSystemConfigServiceApi.getBonusSystemConfig(cuMember.getPkSettleCountry(), ESystemConfig.HA_FUN_REGISTER_NUMBER.getKey()).getData();
//            if (cuMemberExtList.size() >= Integer.parseInt(value)) {
//                // 手机注册次数已达系统上限
//                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.SYSTEM_REGISTER_COUNT));
//            }
//        }
//        memberParam.setMemberCode(SysConstants.HAI_FUN_PREFIX + memberParam.getMemberCode());
//        if (StringUtils.isNotEmpty(memberParam.getMemberCode())) {
//            CuMember existCuMember = iCuMemberService.getMemberByCode(memberParam.getMemberCode());
//            // 验证该编号是否存在会员系统中
//            if (existCuMember != null) {
//                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_REPEAT_1));
//            }
//        }
//
//        // 短信校验码校验
//        String checkStr = iApiSmsService.checkSms(ESmsTemplate.VERIFICATION.getCache() + memberParam.getPhone(), memberParam.getCode());
//        if (null != checkStr) {
//            return AjaxResult.error(checkStr);
//        }
//        CuMember newCuMember = iCuMemberService.confirmShareMemberByMemberParam(memberParam);
//        if (newCuMember != null) {
//            MemberShare memberShare = MemberShare.builder().memberCode(newCuMember.getMemberCode())
//                    .memberName(newCuMember.getMemberName())
//                    .phone(newCuMember.getPhone())
//                    .loginPassword(newCuMember.getLoginPassword())
//                    .payPassword(newCuMember.getPayPassword())
//                    .urlAddress(BdConfig.getPc())
//                    .gzh(BdConfig.getGzh())
//                    .ios(BdConfig.getIos())
//                    .android(BdConfig.getAndroid())
//                    .build();
//            return AjaxResult.success(memberShare);
//        } else {
//            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.TOKEN_REPEAT_SUBMIT));
//        }
//    }

    private AjaxResult validateMemberCode(String memberCode) {
        boolean result = memberCode.matches("[0-9]+");
        if (!result || memberCode.length() < 10 || memberCode.length() > 20) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_CODE_MUST_NUMBER));
        }
        // 验证是否存在连续3个连续数字
        if (compareConDigits(memberCode)) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_CODE_CON_NUMBER));
        }
        return null;
    }

    /**
     * @Description: 确认注册订单，生成待支付订单,只有注册订单有待支付订单
     * @return: AjaxResult
     * @Author: sui q
     * @Date: 2022/8/27 16:47
     */
    @GetMapping("/validate-share-member/{memberCode}")
    public AjaxResult validateShareMemberCode(@PathVariable("memberCode") String memberCode) {
        // 验证必输项
        if (StringUtils.isEmpty(memberCode)) {
            return AjaxResult.error(MemberMsgConstants.REQUIRED_NOT_EMPTY);
        }
        // 验证CN后是否全部数字
        AjaxResult memberCodeResult = validateMemberCode(memberCode);
        if (memberCodeResult != null) {
            return memberCodeResult;
        }
        return AjaxResult.success();
    }

    /**
     * @Description: 获得推荐人国家前缀
     * @return: AjaxResult
     * @Author: sui q
     * @Date: 2022/8/27 16:47
     */
    @GetMapping("/query-country-prefix/{pkParent}")
    public AjaxResult queryCountryPrefix(@PathVariable("pkParent") String pkParent) {
        // 验证必输项
        if (pkParent == null) {
            return AjaxResult.error(MemberMsgConstants.REQUIRED_NOT_EMPTY);
        }
        CountryDTO countryDTO = getCountryDTO(pkParent);
        return AjaxResult.success(countryDTO.getCode());
    }

    private CountryDTO getCountryDTO(String pkParent) {
        Long pkParentId = Long.parseLong(new String(Base64Decoder.decode(pkParent)));
        CuMember cuMember = iCuMemberService.getMember(pkParentId);
        return iCountryServiceApi.getCountry(cuMember.getPkSettleCountry()).getData();
    }

    /**
     * 查询推荐人编号
     *
     * @param pkParent 推荐人（加密）
     * @return
     */
    @GetMapping("/fans-convert-code/{pkParent}")
    public AjaxResult fansConvertCode(@PathVariable("pkParent") String pkParent) {
        // 验证必输项
        if (pkParent == null) {
            return AjaxResult.error(MemberMsgConstants.REQUIRED_NOT_EMPTY);
        }
        CuMember cuMember = iCuMemberService.getMemberById(Long.parseLong(new String(Base64Decoder.decode(pkParent))));
        if (null != cuMember) {
            return AjaxResult.success(cuMember.getMemberCode());
        }
        return AjaxResult.error();
    }

    /**
     * 根据订单查询会员信息
     *
     * @param orderCode 订单编号
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/fans-order/{orderCode}")
    public AjaxResult fansOrder(@PathVariable("orderCode") String orderCode) {
        CuMemberExt cuMemberExt = iCuMemberService.queryFansOrder(orderCode);
        if (null == cuMemberExt) {
            return AjaxResult.error("注册会员失败，请联系客服处理");
        }

        return AjaxResult.success(MemberShare.builder()
                .memberName(cuMemberExt.getMemberName())
                .memberCode(cuMemberExt.getMemberCode())
                .phone(cuMemberExt.getPhone())
                .loginPassword(cuMemberExt.getLoginPassword())
                .payPassword(cuMemberExt.getPayPassword())
                .urlAddress(BdConfig.getPc())
                .gzh(BdConfig.getGzh())
                .ios(BdConfig.getIos())
                .android(BdConfig.getAndroid())
                .build());
    }

    /**
     * 查询会员注册信息
     *
     * @param orderCode 订单编号
     * @return
     */
    @RepeatSubmitSimple
    @GetMapping("/register-order/{orderCode}")
    public AjaxResult registerOrder(@PathVariable("orderCode") String orderCode) {
        CuMemberExt cuMemberExt = iCuMemberService.queryRegisterOrder(orderCode, SecurityUtils.getUserId());
        if (null == cuMemberExt) {
            return AjaxResult.success("暂未查询到会员信息,稍微再试!", null);
        }

        return AjaxResult.success(MemberShare.builder()
                .memberName(cuMemberExt.getMemberName())
                .memberCode(cuMemberExt.getMemberCode())
                .phone(cuMemberExt.getPhone())
                .loginPassword(cuMemberExt.getLoginPassword())
                .payPassword(cuMemberExt.getPayPassword())
                .urlAddress(BdConfig.getPc())
                .gzh(BdConfig.getGzh())
                .ios(BdConfig.getIos())
                .android(BdConfig.getAndroid())
                .build());
    }

    /*
     * 验证是否连续数字
     **/
    private Boolean compareConDigits(String memberCode) {
        String[] codeList = memberCode.split("");
        for (int i = 0; i < codeList.length; i++) {
            if (i >= codeList.length - 6) {
                break;
            }
            // 验证不能连续6个相同的数字
            int conCount = 0;
            int compareNumber = Integer.parseInt(codeList[i]);
            for (int j = i + 1; j < codeList.length; j++) {
                int beCompareNumber = Integer.parseInt(codeList[j]);
                if (compareNumber == beCompareNumber) {
                    conCount++;
                    if (conCount >= 5) {
                        return true;
                    }
                } else {
                    break;
                }
            }
        }

        for (int i = 0; i < codeList.length; i++) {
            if (i >= codeList.length - 6) {
                break;
            }
            // 验证不能连续5个递增的数字
            int incCount = 0;
            int compareNumber = Integer.parseInt(codeList[i]);
            for (int j = i + 1; j < codeList.length; j++) {
                int beCompareNumber = Integer.parseInt(codeList[j]);
                if (beCompareNumber == compareNumber + 1 + incCount) {
                    incCount++;
                    if (incCount >= 5) {
                        return true;
                    }
                } else {
                    break;
                }
            }
        }

        for (int i = 0; i < codeList.length; i++) {
            if (i >= codeList.length - 6) {
                break;
            }
            // 验证不能连续3个递减的数字
            int incCount = 0;
            int compareNumber = Integer.parseInt(codeList[i]);
            for (int j = i + 1; j < codeList.length; j++) {
                int beCompareNumber = Integer.parseInt(codeList[j]);
                if (beCompareNumber == compareNumber - 1 - incCount) {
                    incCount++;
                    if (incCount >= 5) {
                        return true;
                    }
                } else {
                    break;
                }
            }
        }

        return false;
    }

    /**
     * @param fieldList 需要验证的字段
     * @Description: 验证字段是否必输
     * @return: boolean
     * @Author: sui q
     * @Date: 2022/8/29 11:13
     */
    private boolean validateFieldNotNull(MemberParam memberParam, List<String> fieldList) {
        return fieldList.stream().anyMatch(field -> {
            Object obj = ReflectUtils.invokeGetter(memberParam, field);
            return obj == null || "".equals(obj);
        });
    }

    /**
     * 会员 推荐列表（直推列表）
     *
     * @return
     */
    @GetMapping("/parent-list")
    public TableDataInfo parentList(String memberCode, String memberName, Date startCreateTime, Date endCreateTime, String memberInfo) {
        Long memberId = SecurityUtils.getUserId();

        // 查询等级
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<List<GradeDTO>> grderDate = iGradeServiceApi.findAll();
        List<GradeDTO> grderList = grderDate.getData();

        if (endCreateTime != null) {
            endCreateTime = DateUtils.getEndTime(endCreateTime);
        }

        startPage();
        List<ParentMemberVo> list = iCuMemberService.parentList(memberId, memberCode, memberName, startCreateTime, endCreateTime, memberInfo);

        if (CollectionUtil.isNotEmpty(list)) {
            Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE);
            R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

            for (ParentMemberVo cuMember : list) {

                cuMember.setMemberCode(CommonUtil.getMemberCode(cuMember.getMemberCode(), cuMember.getServiceCode()));
                cuMember.setMemberName(CommonUtil.getMemberName(cuMember.getPkVertex(), cuMember.getMemberName(), cuMember.getNickName()));

                for (GradeDTO gradeDTO : grderList) {
                    if (gradeDTO.getPkId().equals(cuMember.getPkRegisterGrade())) {
                        cuMember.setPkRegisterGradeStr(transactionMap.get(gradeDTO.getPkTransaction()));
                    }
                }
                for (GradeDTO gradeDTO : grderList) {
                    if (gradeDTO.getPkId().equals(cuMember.getPkSettleGrade())) {
                        cuMember.setPkSettleGradeStr(transactionMap.get(gradeDTO.getPkTransaction()));
                    }
                }
                if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                    if (cuMember.getConsumeAchieve() != null) {
                        cuMember.setConsumeAchieve(cuMember.getConsumeAchieve().multiply(inExchangeRate));
                    }
                }
            }
        }

        return getDataTable(list);
    }

    /**
     * 查询是否首次登录 需要弹出修改密码弹窗
     */
    @GetMapping("/get-member-is-updatepassword")
    public AjaxResult getMemberIsUpdatePassword() {
        Long memberId = SecurityUtils.getUserId();
        // 查询是否首次登录 需要修改密码
        LambdaUpdateWrapper<CuMemberChangeLog> qw = new LambdaUpdateWrapper<>();
        qw.eq(CuMemberChangeLog::getPkMember, memberId);
        qw.eq(CuMemberChangeLog::getChangeType, EMemberChangeType.LOGIN_PWD.getValue());
        int count = iCuMemberChangeLogService.count(qw);
        return AjaxResult.success(count);
    }

    /**
     * 服务协议有效期（0=不需要，1=需要）
     */
    @GetMapping("/agreement_expire")
    public AjaxResult agreementExpire() {
        if (CountryConstants.CHINA_COUNTRY.equals(SecurityUtils.getPkCountry())) {
            // 中国会员才进行校验
            CuMember cuMember = iCuMemberService.getMemberById(SecurityUtils.getUserId());

            // 校验会员是否添加到白名单
            BdAgreementRenewalWhite agreementRenewalWhite = null;
            R<BdAgreementRenewalWhite> whiteR = iAgreementRenewalWhiteServiceApi.getInfo(SecurityUtils.getUserId(), EAgreementWhiteType.RENEW_NOT_REAL.getValue());
            if (whiteR.isSuccess()) {
                if (null != whiteR.getData()) {
                    agreementRenewalWhite = whiteR.getData();
                }
            }

            if (EExpireStatus.REST.getValue() == cuMember.getExpireStatus()) {
                // 会员【休止期】处理（首页弹窗提示）
                if (EYesNo.YES.getIntValue() == cuMember.getIsRealName() || null != agreementRenewalWhite) {
                    // 已实名认证 或 免实名认证，跳转续约专区
                    return AjaxResult.success(AgreementExpireVO.builder()
                            .promptFlag(EYesNo.YES.getIntValue())
                            .promptMsg("您的会员身份到期日至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getExpireDate()) + "，请及时办理续约，续约截止日期至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getStopDate()) + "，祝您生活愉快，谢谢！")
                            .jumpPage(2)
                            .build());
                } else {
                    // 未实名认证，跳转实名认证
                    // 2025.02.12 添加需求，未实名认证，也能进行续约
                    int jumpPage = 2;

//                    // 校验爱美视顶点下，续约不需要实名
//                    if (iCuMemberService.checkPlaceParent(SysConstants.AIMEI_VISION_TOP, SecurityUtils.getUserId()) > 0) {
//                        jumpPage = 2;
//                    }

                    return AjaxResult.success(AgreementExpireVO.builder()
                            .promptFlag(EYesNo.YES.getIntValue())
                            .promptMsg("您的会员身份到期日至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getExpireDate()) + "，请及时办理续约，续约截止日期至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getStopDate()) + "，祝您生活愉快，谢谢！")
                            .jumpPage(jumpPage)
                            .build());
                }
            } else if (EExpireStatus.EXPIRE.getValue() == cuMember.getExpireStatus()) {
                // 会员【有效期】处理
                if (DateUtils.addMonths(new Date(), 3).compareTo(cuMember.getExpireDate()) > 0) {
                    // 会员还有3月到期（首页弹窗提示）
                    if (EYesNo.YES.getIntValue() == cuMember.getIsRealName() || null != agreementRenewalWhite) {
                        // 已实名认证 或 免实名认证，跳转续约专区
                        return AjaxResult.success(AgreementExpireVO.builder()
                                .promptFlag(EYesNo.YES.getIntValue())
                                .promptMsg("您的会员身份到期日至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getExpireDate()) + "，请及时办理续约，续约截止日期至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getStopDate()) + "，祝您生活愉快，谢谢！")
                                .jumpPage(2)
                                .build());
                    } else {
                        // 未实名认证，跳转实名认证
                        // 2025.02.12 添加需求，未实名认证，也能进行续约
                        int jumpPage = 2;

//                        // 校验爱美视顶点下，续约不需要实名
//                        if (iCuMemberService.checkPlaceParent(SysConstants.AIMEI_VISION_TOP, SecurityUtils.getUserId()) > 0) {
//                            jumpPage = 2;
//                        }

                        return AjaxResult.success(AgreementExpireVO.builder()
                                .promptFlag(EYesNo.YES.getIntValue())
                                .promptMsg("您的会员身份到期日至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getExpireDate()) + "，请及时办理续约，续约截止日期至" + DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD_CHINA, cuMember.getStopDate()) + "，祝您生活愉快，谢谢！")
                                .jumpPage(jumpPage)
                                .build());
                    }
                }
            }
        }
        // 正常状态（首页不弹窗）
        return AjaxResult.success(AgreementExpireVO.builder()
                .promptFlag(EYesNo.NO.getIntValue())
                .build());
    }

    /**
     * 获取用户奖衔信息
     *
     * @return
     */
    @GetMapping("/member-awards-info")
    public AjaxResult memberAwardsInfo() {
        Long pkMember = SecurityUtils.getUserId();

        MemberAwardsInfoVO memberAwardsInfoVO = new MemberAwardsInfoVO();

//        Integer pkCountry = SecurityUtils.getPkCountry();
//        // 最高奖衔（取cu_member 中的max_awards和本月实时奖衔进行对比，哪个高用哪个）
//        CuMemberAwardsUnderVO cuMemberAwardsUnderVO = iCuMemberAchieveService.getPkAwardBySmallAchieve(pkMember, pkCountry, false);
//        // 奖衔列表
//        List<BdAwards> awardsList = cuMemberAwardsUnderVO.getAwardsList();
//        Map<Integer, BdAwards> awardsMap = new HashMap<>();
//        for (BdAwards bdAwards : awardsList) {
//            awardsMap.put(bdAwards.getPkId(), bdAwards);
//        }
//
//        // 会员信息
//        CuMemberExt cuMember = iCuMemberService.getMemberById(pkMember);
//        if (null == cuMember.getPkMaxAwards()) {
//            // 当月奖衔
//            BdAwards nowAwards = awardsMap.get(cuMemberAwardsUnderVO.getPkAwards());
//            memberAwardsInfoVO.setMaxAwardsName(nowAwards.getAwardsName());
//        } else {
//            // 当月奖衔
//            BdAwards nowAwards = awardsMap.get(cuMemberAwardsUnderVO.getPkAwards());
//            // 新制度最高奖衔
//            BdAwards maxAwards = awardsMap.get(cuMember.getPkMaxAwards());
//
//            if (maxAwards.getAwardsValue().compareTo(nowAwards.getAwardsValue()) >= 0) {
//                memberAwardsInfoVO.setMaxAwardsName(maxAwards.getAwardsName());
//            } else {
//                memberAwardsInfoVO.setMaxAwardsName(nowAwards.getAwardsName());
//            }
//        }

//        // 查询历史荣誉奖衔
//        CuMemberHistroyAwardsExt memberHistroyAwards = iCuMemberHistroyAwardsService.getOldAwards(pkMember);
//        if (null != memberHistroyAwards) {
//            memberAwardsInfoVO.setHistoryAwards(memberHistroyAwards.getAwardsName());
//            memberAwardsInfoVO.setHistoryAwardsImg(memberHistroyAwards.getImage());
//        }

        // 会员信息
        CuMemberExt cuMember = iCuMemberService.getMemberById(pkMember);

        BdAwards memberAwards = iAwardsServiceApi.getAwardsOne(cuMember.getPkAwards()).getData();
        memberAwardsInfoVO.setAwardsName(memberAwards.getAwardsName());

        return AjaxResult.success(memberAwardsInfoVO);
    }

}
