package com.hzs.member.base.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.sign.Base64Util;
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.service.ITransactionCommonService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.IMemberInfoService;
import com.hzs.member.base.vo.MemberCardVO;
import com.hzs.member.base.vo.MemberDataVO;
import com.hzs.member.base.vo.MemberInfoVO;
import com.hzs.member.detail.service.ICuMemberChangeLogService;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
import com.hzs.system.common.ICommonServiceApi;
import com.hzs.system.common.dto.MemberDataDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 会员信息服务
 */
@Service
public class MemberInfoServiceImpl implements IMemberInfoService {

    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberChangeLogService iCuMemberChangeLogService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;
    @DubboReference
    ICommonServiceApi iCommonServiceApi;

    @Override
    public MemberInfoVO getMemberInfo(Long memberId) {
        if (null == memberId) {
            return null;
        }

        CuMemberExt cuMember = iCuMemberService.getMenuMember(memberId);
        if (null != cuMember) {
            // 调用system服务，获取国家、币种、等级、奖衔等数据
            MemberDataDTO memberDataDTO = iCommonServiceApi.getMemberData(MemberDataDTO.builder()
                    .pkCountry(cuMember.getPkCountry())
                    .pkSettleCountry(cuMember.getPkSettleCountry())
                    .pkGrade(cuMember.getPkSettleGrade())
                    .pkAwards(cuMember.getPkAwards())
//                    .pkMaxAwards(cuMember.getPkMaxAwards())
                    .build())
                    .getData();

            BigDecimal consumeAchieve = cuMember.getConsumeAchieve();
            if (CountryConstants.CHINA_COUNTRY.equals(cuMember.getPkSettleCountry())) {
                // 中国会员，汇率处理
                consumeAchieve = consumeAchieve.multiply(memberDataDTO.getExchangeRate());
            }

            // 会员名称，优先取昵称，没有取名称
            String memberName = StringUtils.isNotEmpty(cuMember.getNickName()) ? cuMember.getNickName() : cuMember.getMemberName();
            // 自然国家
            String pkCountryVal = memberDataDTO.getPkCountryVal();
            // 结算国家
            String pkSettleCountryVal = memberDataDTO.getPkSettleCountryVal();

            // 国家翻译
            Map<Integer, String> transactionMap = iTransactionCommonService.enumTransactionByDBFromPkId(Arrays.asList(memberDataDTO.getPkCountryTransaction(), memberDataDTO.getPkSettleCountryTransaction()));
            if (null != transactionMap.get(memberDataDTO.getPkCountryTransaction())) {
                pkCountryVal = transactionMap.get(memberDataDTO.getPkCountryTransaction());
            }
            if (null != transactionMap.get(memberDataDTO.getPkSettleCountryTransaction())) {
                pkSettleCountryVal = transactionMap.get(memberDataDTO.getPkSettleCountryTransaction());
            }
            // 特殊登录处理（两个特殊账号，登录之后单独处理）
            int loginType = 0;

            // 封装返回信息
            return MemberInfoVO.builder()
                    .memberCode(cuMember.getMemberCode())
                    .memberName(memberName)
                    .registerTime(cuMember.getPayTime())
                    .pkCountry(cuMember.getPkCountry())
                    .pkCountryVal(pkCountryVal)
                    .countryCircularIcon(memberDataDTO.getCountryCircularIcon())
                    .countrySquareIcon(memberDataDTO.getCountrySquareIcon())
                    .pkSettleCountry(cuMember.getPkSettleCountry())
                    .pkSettleCountryVal(pkSettleCountryVal)
                    .settleCountryCircularIcon(memberDataDTO.getSettleCountryCircularIcon())
                    .settleCountrySquareIcon(memberDataDTO.getSettleCountrySquareIcon())
                    .settleCountryLightName(memberDataDTO.getSettleCountryLightName())
                    .settleCountryImg(memberDataDTO.getSettleCountryImg())
                    .pkGradeId(cuMember.getPkSettleGrade())
                    .pkGrade(memberDataDTO.getPkGrade())
                    .gradeIcon(memberDataDTO.getGradeIcon())
                    .pkAwardsId(cuMember.getPkAwards())
                    .pkAwards(memberDataDTO.getPkAwards())
                    .awardsIcon(memberDataDTO.getAwardsIcon())
//                    .pkMaxAwardsId(cuMember.getPkMaxAwards())
//                    .pkMaxAwards(memberDataDTO.getPkMaxAwards())
//                    .maxAwardsIcon(memberDataDTO.getMaxAwardsIcon())
                    .currencyIcon(memberDataDTO.getCurrencyIcon())
                    .registerAuthority(cuMember.getRegisterAuthority())
                    .headPath(cuMember.getHeadPath())
                    .consumeAchieve(consumeAchieve)
                    .payTime(cuMember.getPayTime())
                    .globalCode(cuMember.getGlobalCode())
                    .countryCode(cuMember.getCountryCode())
                    .loginType(loginType)
                    .specialRegistration(cuMember.getSpecialRegistration())
                    .expireDate(cuMember.getExpireDate())
                    .serviceCode(cuMember.getServiceCode())
                    .build();
        }
        return null;
    }

    @Override
    public MemberDataVO queryMemberData(Long memberId) {
        MemberDataVO memberDataVO = iCuMemberService.queryMemberData(memberId);
        // 手机号脱敏
        memberDataVO.setPhone(DesensitizedUtil.mobilePhone(memberDataVO.getPhone()));
        // 证件号码脱敏
        memberDataVO.setIdCardAuth(DesensitizedUtil.idCardNum(memberDataVO.getIdCardAuth(), 6, 6));

        if (CountryConstants.CHINA_COUNTRY.equals(memberDataVO.getPkSettleCountry())) {
            // 汇率
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(memberDataVO.getPkSettleCountry()).getData();

            // 中国会员，汇率处理
            memberDataVO.setConsumeAchieve(memberDataVO.getConsumeAchieve().multiply(currencyDTO.getInExchangeRate()));
        }

        // 国家翻译
        Map<Integer, String> transactionMap = iTransactionCommonService.enumTransactionByDBFromPkId(Arrays.asList(memberDataVO.getPkCountryTransaction(), memberDataVO.getPkSettleCountryTransaction()));
        if (null != transactionMap.get(memberDataVO.getPkCountryTransaction())) {
            memberDataVO.setCountryName(transactionMap.get(memberDataVO.getPkCountryTransaction()));
        }
        if (null != transactionMap.get(memberDataVO.getPkSettleCountryTransaction())) {
            memberDataVO.setSettleCountryName(transactionMap.get(memberDataVO.getPkSettleCountryTransaction()));
        }

        return memberDataVO;
    }

    @Override
    public MemberCardVO queryMemberCard(Long memberId) {
        CuMember cuMember = iCuMemberService.getMemberById(memberId);
        if (null != cuMember) {
            // 调用system服务，获取国家、币种、等级、奖衔等数据
            MemberDataDTO memberDataDTO = iCommonServiceApi.getMemberData(MemberDataDTO.builder()
                    .pkGrade(cuMember.getPkSettleGrade())
                    .pkAwards(cuMember.getPkAwards())
                    .build())
                    .getData();

            // 等级图标
            String gradeIcon = memberDataDTO.getGradeIcon();
            // 等级图标base64
            String gradeIconStr = Base64Util.toUrlBase64(gradeIcon);

            // 奖衔图标
            String awardsIcon = memberDataDTO.getAwardsIcon();
            // 奖衔图标base64
            String awardsIconStr = Base64Util.toUrlBase64(awardsIcon);

            return MemberCardVO.builder()
                    .gradeIcon(gradeIcon)
                    .gradeIconStr(gradeIconStr)
                    .awardsIcon(awardsIcon)
                    .awardsIconStr(awardsIconStr)
                    .build();
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateMemberInfo(CuMember cuMember, List<CuMemberChangeLog> cuMemberChangeLogList) {
        // 插入会员修改记录
        if (CollectionUtil.isNotEmpty(cuMemberChangeLogList)) {
            iCuMemberChangeLogService.saveBatch(cuMemberChangeLogList);
        }

        // 更新会员信息
        if (null != cuMember) {
            iCuMemberService.updateById(cuMember);
        }
    }

}
