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

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzs.common.core.annotation.RepeatSubmit;
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.SysConstants;
import com.hzs.common.core.constant.msg.CommonMsgConstants;
import com.hzs.common.core.constant.msg.FinanceMsgConstants;
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.EMemberChangeType;
import com.hzs.common.core.enums.EYesNo;
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.account.CuMemberAccount;
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.ext.BdGradeExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.common.core.utils.TransactionUtils;
import com.hzs.member.account.service.ICuMemberAccountService;
import com.hzs.member.base.param.ExchangeAnnuityPurchaseParam;
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.sale.order.ISaOrderServiceApi;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
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 memberChangeLogService;
    @Autowired
    private ICuMemberAccountService memberAccountService;

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;
    @DubboReference
    ISaOrderServiceApi orderServiceApi;


    /**
     * 获取登录会员信息
     *
     * @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(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        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(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        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(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        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(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        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));
        }

        // 会员修改信息
        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.isAllEmpty(param.getMemberCode(), param.getCode(), param.getLoginPassword())) {
            return AjaxResult.error(TransactionUtils.getContent(CommonMsgConstants.MISSING_PARAM));
        }
        CuMemberExt cuMemberExt = iCuMemberService.getMemberByCode(param.getMemberCode());
        if (null == cuMemberExt) {
            // 会员不存在，或者手机号不相同
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_INFO_ERROR));
        }
        Long memberId = cuMemberExt.getPkId();

        // 会员修改信息
        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(cuMemberExt.getLoginPassword())
                .changeAfter(param.getLoginPassword())
                .build();
        iMemberInfoService.updateMemberInfo(cuMember, Collections.singletonList(cuMemberChangeLog));

        return AjaxResult.success();
    }

    /**
     * @param memberParam 订单参数
     *                    确认注册订单，生成待支付订单,只有注册订单有待支付订单
     * @return: AjaxResult
     * @Author: sui q
     * @Date: 2022/8/27 16:47
     */
    @PostMapping("/reg-share-member")
    @RepeatSubmit
    public AjaxResult confirmRegisterOrder(@RequestBody MemberParam memberParam) {
        // 验证必输项
        if (validateFieldNotNull(memberParam, memberParam.getValidConfirmField())) {
            return AjaxResult.error(TransactionUtils.getContent(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()).pkSettleCountry(cuMember.getPkSettleCountry()).build());
//        // 系统中存在该手机号走的验证
//        if (cuMemberExtList.size() > 0) {
//            // 手机号注册次数
//            String value = systemConfigServiceApi.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.getMember(memberParam.getMemberCode());
            // 验证该编号是否存在会员系统中
            if (existCuMember != null) {
                return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.EMPTY_MEMBER_REPEAT_1));
            }
        }

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

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

    /*
     *  验证是否连续数字
     **/
    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 需要验证的字段
     */
    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 = gradeServiceApi.findAll();
        List<GradeDTO> grderList = grderDate.getData();
        startPage();
        if (endCreateTime != null) {
            endCreateTime = DateUtils.getEndTime(endCreateTime);
        }
        Map<Integer, String> transactionMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE);
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
        List<ParentMemberVo> list = iCuMemberService.parentList(memberId, memberCode, memberName, startCreateTime, endCreateTime, memberInfo);
        for (ParentMemberVo cuMember : list) {
            for (GradeDTO gradeDTO : grderList) {
                if (gradeDTO.getPkId().equals(cuMember.getPkRegisterGrade())) {
                    cuMember.setPkRegisterGradeStr(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();
        // 查询是否首次登录 需要修改密码
        QueryWrapper<CuMemberChangeLog> qw = new QueryWrapper<>();
        qw.eq("PK_MEMBER", memberId);
        qw.eq("CHANGE_TYPE", EMemberChangeType.LOGIN_PWD.getValue());
        int count = memberChangeLogService.count(qw);
        return AjaxResult.success(count);
    }


    /**
     * 获取会员年金剩余时间
     */
    @GetMapping("get-member-annuity-time")
    public AjaxResult getMemberAnnuityTime() {
        CuMember member = iCuMemberService.getMemberByCode(SecurityUtils.getMemberCode());
        long expireDateNumber = 0L;
        if (member.getExpireDate() != null) {
            expireDateNumber = DateUtil.between(member.getExpireDate(), DateUtils.currentDate(), DateUnit.DAY);
        }
        // 汇率
        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        BigDecimal inExchangeRate = currencyDto.getData().getInExchangeRate();
        CuMemberVO cuMemberVO = new CuMemberVO();
        // 复消剩余收益奖金
        cuMemberVO.setResaleIncomeBonus(member.getResaleIncomeBonus().multiply(inExchangeRate));
        // 到期日期
        if (member.getExpireDate() != null) {
            if (member.getExpireDate().getTime() < DateUtils.currentDate().getTime()) {
                cuMemberVO.setExpireDateNumber(0L);
            } else {
                cuMemberVO.setExpireDateNumber(expireDateNumber + 1);
            }
        } else {
            cuMemberVO.setExpireDateNumber(0L);
        }
        return AjaxResult.success(cuMemberVO);
    }


    /**
     * 获取年金金额
     *
     * @return
     */
    @GetMapping("get-exchange-annuity-money")
    public AjaxResult getExchangeAnnuity() {
        String memberCode = SecurityUtils.getMemberCode();
        // 会员
        CuMember member = iCuMemberService.getMember(memberCode);
        return AjaxResult.success(getExchangeAnnuityMoney(member));
    }


    /**
     * 兑换年金
     */
    @PostMapping("exchange-annuity-purchase")
    public AjaxResult exchangeAnnuityPurchase(@RequestBody ExchangeAnnuityPurchaseParam exchangeAnnuityPurchaseParam) {
        String memberCode = SecurityUtils.getMemberCode();
        // 会员
        CuMember member = iCuMemberService.getMember(memberCode);
        //校验支付密码
        String payPwd = exchangeAnnuityPurchaseParam.getPayPassword();
        if (StringUtils.isEmpty(payPwd) || !SecurityUtils.matchesPassword(payPwd, member.getPayPwd())) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.PAYMENT_PASSWORD_ERROR));
        }
        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());

        Integer pkRate = currencyDto.getData().getPkId();
        BigDecimal inExchangeRate = currencyDto.getData().getInExchangeRate();

        R<GradeDTO> gradeDto = gradeServiceApi.getGrade(member.getPkSettleGrade());
        GradeDTO grade = gradeDto.getData();
        if (grade.getStartValue().compareTo(BigDecimal.ZERO) == 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_GRADE_CANNOT_PURCHASE));
        }

        BigDecimal renewAmount = grade.getRenewAmount().multiply(inExchangeRate);
        CuMemberAccount cemberAccount = memberAccountService.getOne(new QueryWrapper<CuMemberAccount>().eq("PK_MEMBER", member.getPkId()));
        // 消费 + 奖金  总余额
        Integer number = exchangeAnnuityPurchaseParam.getNumber();
        BigDecimal account = cemberAccount.getAccount1().add(cemberAccount.getAccount4());
        int flag = renewAmount.multiply(new BigDecimal(number)).compareTo(account);
        if (flag > 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_BALANCE));
        }
        // 年金购买
        Date expireDate = member.getExpireDate();
        //支付购买时间
        Date payTime = member.getPayTime();
        Integer pkAwards = member.getPkAwards();
        Integer pkSettleGrade = member.getPkSettleGrade();
        iCuMemberService.exchangeAnnuity(renewAmount, number, member.getPkId(), pkRate, expireDate, cemberAccount, member.getMemberCode(), pkAwards, pkSettleGrade, payTime);
        return AjaxResult.success();
    }

    /**
     * 获取奖金年金单价
     *
     * @return
     */
    @GetMapping("/get-member-renew-amount")
    public AjaxResult getMemberRenewAmount() {
        String memberCode = SecurityUtils.getMemberCode();
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 汇率
        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(pkCountry);
        BigDecimal inExchangeRate = currencyDto.getData().getInExchangeRate();
        CuMember member = iCuMemberService.getMember(memberCode);
        R<GradeDTO> gradeDto = gradeServiceApi.getGrade(member.getPkSettleGrade());
        GradeDTO grade = gradeDto.getData();
        BigDecimal renewAmount = grade.getRenewAmount().multiply(inExchangeRate);

        return AjaxResult.success(renewAmount);
    }

    /**
     * 获取奖金年金支付币种
     */
    @PostMapping("/get-currency-type")
    public AjaxResult getCurrencyType(@RequestBody ExchangeAnnuityPurchaseParam exchangeAnnuityPurchaseParam) {
        // 奖金年金支付币种获取
        String memberCode = SecurityUtils.getMemberCode();
        Integer pkCountry = SecurityUtils.getPkCountry();
        // 会员
        CuMember member = iCuMemberService.getMember(memberCode);
        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(pkCountry);
        // 汇率
        BigDecimal inExchangeRate = currencyDto.getData().getInExchangeRate();
        R<GradeDTO> gradeDto = gradeServiceApi.getGrade(member.getPkSettleGrade());
        GradeDTO grade = gradeDto.getData();
        if (grade.getStartValue().compareTo(BigDecimal.ZERO) == 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_GRADE_CANNOT_PURCHASE));
        }
        /**
         * #消费 + 奖金扣款
         * #优先扣除消费  奖金账户要扣除 奖金账户 和 可提现账户
         * 生成 trade 记录
         */
        CuMemberAccount cemberAccount = memberAccountService.getOne(new QueryWrapper<CuMemberAccount>().eq("PK_MEMBER", member.getPkId()));
        BigDecimal renewAmount = grade.getRenewAmount().multiply(inExchangeRate);
        // 购买数
        Integer number = exchangeAnnuityPurchaseParam.getNumber();
        // 消费 + 奖金  总余额
        BigDecimal account = cemberAccount.getAccount1().add(cemberAccount.getAccount4());
        int flag = renewAmount.multiply(new BigDecimal(number)).compareTo(account);
        if (flag > 0) {
            return AjaxResult.error(TransactionUtils.getContent(MemberMsgConstants.MEMBER_NOT_BALANCE));
        }
        // 单价 * 数量
        BigDecimal relaseIncomeBonus = new BigDecimal(number).multiply(renewAmount);

        return AjaxResult.success(getAccount(relaseIncomeBonus, cemberAccount));
    }

    /**
     * 获取各币种支付数
     */
    private MemberAccountVo getAccount(BigDecimal relaseIncomeBonus, CuMemberAccount cemberAccount) {
        BigDecimal account1 = cemberAccount.getAccount1();
        if (cemberAccount.getAccount1().compareTo(relaseIncomeBonus) < 0) {
            /**
             * #消费 + 奖金扣款
             * #优先扣除消费  奖金账户要扣除 奖金账户 和 可提现账户
             * 生成 trade 记录
             */
            //   BigDecimal tradeBeforeAccount4 = cemberAccount.getAccount4();
            BigDecimal account4 = relaseIncomeBonus.subtract(account1);
            return MemberAccountVo.builder().account1(cemberAccount.getAccount1())
                    .account4(cemberAccount.getAccount4())
                    .payAccount1(account1)
                    .payAccount4(account4).totalPrice(relaseIncomeBonus).build();

        } else {
            // 消费账户余额充足
            return MemberAccountVo.builder().account1(cemberAccount.getAccount1())
                    .account4(BigDecimal.ZERO)
                    .payAccount1(relaseIncomeBonus)
                    .payAccount4(BigDecimal.ZERO).totalPrice(relaseIncomeBonus).build();

        }
    }


    /**
     * 获取年金金额
     *
     * @return
     */
    private MemberExchangeAnnuityVo getExchangeAnnuityMoney(CuMember member) {
        Integer pkSettleGrade = member.getPkSettleGrade();
        R<GradeDTO> gradeDto = gradeServiceApi.getGrade(pkSettleGrade);
        GradeDTO grade = gradeDto.getData();
        // 激活包，等级续费价格
        return MemberExchangeAnnuityVo.builder()
                .grade(grade).renewAmount(grade.getRenewAmount()).build();
    }

    /**
     * 查询当前会员还差多少pv 升级到下一级
     */
    @GetMapping("next-level-pv")
    public AjaxResult nextLevelPv() {

        Long pkMember = SecurityUtils.getUserId();
        Integer pkCountry = SecurityUtils.getPkCountry();
        CuMember member = iCuMemberService.getMember(pkMember);

        R<BigDecimal> memberOrderAchieve = orderServiceApi.getMemberOrderAchieve(pkMember);
        BigDecimal achieve = memberOrderAchieve.getData();
        // 等级名称
        String gradeName = "";
        BdGradeExt bdGrade = new BdGradeExt();
        R<List<GradeDTO>> gradeDto = gradeServiceApi.queryNextGrade(pkCountry);
        List<GradeDTO> gradeList = gradeDto.getData();
        for (int i = 0; i < gradeList.size(); i++) {
            if (gradeList.get(i).getPkId().equals(member.getPkSettleGrade())) {
                // 如果等级相等 查询下一等级
                if (i == gradeList.size() - 1) {
                    // 达到最大等级
                    bdGrade.setIsMaxGrade(EYesNo.YES.getIntValue());
                } else {
                    gradeName = gradeList.get(i + 1).getGradeName();
                    BigDecimal startValue = gradeList.get(i + 1).getStartValue();
                    BigDecimal value = startValue.subtract(achieve);
                    bdGrade.setGradeName(gradeName);
                    bdGrade.setGradeValue(value.intValue());
                    bdGrade.setIsMaxGrade(EYesNo.NO.getIntValue());
                }
            }
        }
        return AjaxResult.success(bdGrade);
    }

}
