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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.hzs.common.core.constant.CountryConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.core.enums.EPlaceDept;
import com.hzs.common.core.utils.CommonUtil;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
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.bonus.CuMemberBonusPush;
import com.hzs.common.domain.member.bonus.CuMemberBonusPushHis;
import com.hzs.common.domain.member.ext.CuMemberBonusPushExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.base.service.ICuMemberShareService;
import com.hzs.member.bonus.service.ICuMemberBonusPushHisService;
import com.hzs.member.bonus.service.ICuMemberBonusPushService;
import com.hzs.member.marketnews.param.MarketNewsParam;
import com.hzs.member.marketnews.param.SeaFlourParam;
import com.hzs.member.marketnews.param.TripleCycleListParam;
import com.hzs.member.marketnews.vo.SeaFlourVo;
import com.hzs.member.marketnews.vo.UserInvestmentVo;
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 org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 市场动态部分接口
 */
@RestController
@RequestMapping("/api/market-news")
public class MarketNewsController extends BaseController {

    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private ICuMemberShareService iCuMemberShareService;
    @Autowired
    private ICuMemberService iCuMemberService;
    @Autowired
    private ICuMemberBonusPushService iCuMemberBonusPushService;
    @Autowired
    private ICuMemberBonusPushHisService iCuMemberBonusPushHisService;

    @DubboReference
    IGradeServiceApi iGradeServiceApi;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 招商列表
     *
     * @return
     */
    @GetMapping("/bidding-list")
    public TableDataInfo biddingList(MarketNewsParam marketNewsParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<List<GradeDTO>> gradeDate = iGradeServiceApi.queryGradeList(pkCountry);
        List<GradeDTO> gradeList = gradeDate.getData();

        marketNewsParam.setPkCountry(pkCountry);
        startPage();
        List<UserInvestmentVo> list = iCuMemberService.selectBiddingList(marketNewsParam);
        for (UserInvestmentVo userInvestmentVo : list) {
            if (userInvestmentVo.getOrderType() != null) {
                String label = EOrderType.getEnumByValue(userInvestmentVo.getOrderType()).getLabel();
                userInvestmentVo.setOrderTypeStr(label);
            }
            if (userInvestmentVo.getRound() == null) {
                userInvestmentVo.setRound(0);
            }
            if (userInvestmentVo.getSecond() == null) {
                userInvestmentVo.setSecond(0);
            }

            //注册等级key
            if (userInvestmentVo.getPkRegisterGrade() != null) {
                for (GradeDTO gradeDTO : gradeList) {
                    if (gradeDTO.getPkId().equals(userInvestmentVo.getPkRegisterGrade())) {
                        userInvestmentVo.setRegisterGradeVal(gradeDTO.getGradeName());
                    }
                }
            }
        }
        return getDataTable(list);
    }


    /**
     * 注册列表
     *
     * @return
     */
    @GetMapping("/reg-list")
    public TableDataInfo regList(MarketNewsParam marketNewsParam) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        marketNewsParam.setPkCountry(pkCountry);
        marketNewsParam.setPkCreator(SecurityUtils.getUserId());
        R<List<GradeDTO>> gradeDate = iGradeServiceApi.queryGradeList(pkCountry);
        List<GradeDTO> gradeList = gradeDate.getData();
        R<CurrencyDTO> currencyDto = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        CurrencyDTO currency = currencyDto.getData();
        if (marketNewsParam.getEndCreationTime() != null) {
            marketNewsParam.setEndCreationTime(DateUtils.getEndTime(marketNewsParam.getEndCreationTime()));
        }
        startPage();
        // 2025年6月26日 强制3个月之前的数据不可见
        Date endDate = DateUtils.addDate(new Date(), -90);
        marketNewsParam.setStartCreationTime(endDate);
        List<UserInvestmentVo> list = iCuMemberService.selectRegList(marketNewsParam);
        for (UserInvestmentVo userInvestmentVo : list) {
            if (userInvestmentVo.getPkPlaceParent() != null && userInvestmentVo.getPkParent() != null) {
                if (userInvestmentVo.getPkPlaceParent() == 0 || userInvestmentVo.getPkParent() == 0) {
                    userInvestmentVo.setParentName("-");
                    userInvestmentVo.setParentCode("-");
                    userInvestmentVo.setPlaceParentCode("-");
                    userInvestmentVo.setPlaceParentName("-");
                }
            }

            //注册等级key
            if (userInvestmentVo.getPkRegisterGrade() != null) {
                for (GradeDTO gradeDTO : gradeList) {
                    if (gradeDTO.getPkId().equals(userInvestmentVo.getPkRegisterGrade())) {
                        userInvestmentVo.setRegisterGradeVal(gradeDTO.getGradeName());
                    }
                }
            }
            if (userInvestmentVo.getPlaceDept() != null) {
                userInvestmentVo.setPlaceDeptVal(EPlaceDept.getEPlaceDept(userInvestmentVo.getPlaceDept()));
            }
            // 所属国是中国
            if (pkCountry.equals(CountryConstants.CHINA_COUNTRY)) {
                userInvestmentVo.setRegPv(userInvestmentVo.getRegPv().multiply(currency.getInExchangeRate()));
            }

            userInvestmentVo.setMemberCode(CommonUtil.getMemberCode(userInvestmentVo.getMemberCode(), userInvestmentVo.getServiceCode()));
            userInvestmentVo.setMemberName(CommonUtil.getMemberName(userInvestmentVo.getPkVertex(), userInvestmentVo.getMemberName(), userInvestmentVo.getNickName()));
            userInvestmentVo.setParentCode(CommonUtil.getMemberCode(userInvestmentVo.getParentCode(), userInvestmentVo.getParentServiceCode()));
            userInvestmentVo.setParentName(CommonUtil.getMemberName(userInvestmentVo.getParentPkVertex(), userInvestmentVo.getParentName(), userInvestmentVo.getParentNickName()));
            userInvestmentVo.setPlaceParentCode(CommonUtil.getMemberCode(userInvestmentVo.getPlaceParentCode(), userInvestmentVo.getPlaceServiceCode()));
            userInvestmentVo.setPlaceParentName(CommonUtil.getMemberName(userInvestmentVo.getPlacePkVertex(), userInvestmentVo.getPlaceParentName(), userInvestmentVo.getPlaceNickName()));

            // 2025年6月26日 脱敏
//            userInvestmentVo.setMemberName(desensitizationName(userInvestmentVo.getMemberName()));
//            userInvestmentVo.setMemberCode(desensitizationCode(userInvestmentVo.getMemberCode()));
            userInvestmentVo.setParentName(desensitizationName(userInvestmentVo.getParentName()));
            userInvestmentVo.setParentCode(desensitizationCode(userInvestmentVo.getParentCode()));
            userInvestmentVo.setPlaceParentName(desensitizationName(userInvestmentVo.getPlaceParentName()));
            userInvestmentVo.setPlaceParentCode(desensitizationCode(userInvestmentVo.getPlaceParentCode()));

        }
        return getDataTable(list);
    }
    private String desensitizationName(String name){
        return StrUtil.hide(name, 1, name.length() - 1);
    }
    private String desensitizationCode(String code){
        return StrUtil.hide(code, 4, code.length() - 3);
    }

    /**
     * 海粉列表
     */
    @GetMapping("/sea_flour_list")
    public TableDataInfo seaFlourList(SeaFlourParam seaFlourParam) {
        seaFlourParam.setPkMember(SecurityUtils.getUserId());
        if (seaFlourParam.getStartCreationTime() != null) {
            seaFlourParam.setStartCreationTime(DateUtil.beginOfDay(seaFlourParam.getStartCreationTime()));
        }
        if (seaFlourParam.getEndCreationTime() != null) {
            seaFlourParam.setEndCreationTime(DateUtil.endOfDay(seaFlourParam.getEndCreationTime()));
        }
        startPage();
        List<SeaFlourVo> memberList = iCuMemberShareService.seaFlourList(seaFlourParam);
        if (CollectionUtil.isNotEmpty(memberList)) {
            for (SeaFlourVo seaFlourVo : memberList) {
                seaFlourVo.setMemberCode(CommonUtil.getMemberCode(seaFlourVo.getMemberCode(), seaFlourVo.getServiceCode()));
                seaFlourVo.setMemberName(CommonUtil.getMemberName(seaFlourVo.getPkVertex(), seaFlourVo.getMemberName(), seaFlourVo.getNickName()));
            }
        }
        return getDataTable(memberList);
    }

    /**
     * 轮次历史业绩
     */
    @GetMapping("/round-his")
    public TableDataInfo seaFlourList() {
        List<CuMemberBonusPushHis> cuMemberBonusPushHis = iCuMemberBonusPushHisService.queryCuMemberBonusPushHis(SecurityUtils.getUserId());
        if (Objects.equals(CountryConstants.CHINA_COUNTRY, SecurityUtils.getPkCountry())) {
            CurrencyDTO currencyDTO = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry()).getData();
            cuMemberBonusPushHis.forEach(bonusPushHis ->
                    bonusPushHis.setCalAchieve(ComputeUtil.computeMultiply(bonusPushHis.getCalAchieve(), currencyDTO.getInExchangeRate())));
        }
        return getDataTable(cuMemberBonusPushHis);
    }

    /**
     * 三单循环列表
     */
    @GetMapping("/triple_cycle_list")
    public TableDataInfo tripleCycleList(TripleCycleListParam tripleCycleListParam) {
        tripleCycleListParam.setPkMember(SecurityUtils.getUserId());
        if (tripleCycleListParam.getStartCreationTime() != null) {
            tripleCycleListParam.setStartCreationTime(DateUtil.beginOfDay(tripleCycleListParam.getStartCreationTime()));
        }
        if (tripleCycleListParam.getEndCreationTime() != null) {
            tripleCycleListParam.setEndCreationTime(DateUtil.endOfDay(tripleCycleListParam.getEndCreationTime()));
        }

        // 禅道bug 8461 会员端，招商列表下的【三单循环】历史轮次需要显示已退单的会员数据   需要展示已删除的会员信息
        startPage();
        List<CuMemberBonusPushExt> list = iCuMemberBonusPushService.tripleCycleList(tripleCycleListParam);

        if (CollectionUtil.isNotEmpty(list)) {
            R<List<GradeDTO>> gradeDto = iGradeServiceApi.findAll();
            List<GradeDTO> gradeDate = gradeDto.getData();

            // 汇率比例
            R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
            BigDecimal inExchangeRate = currency.getData().getInExchangeRate();

            Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EOrderType.values());
            Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE);

            for (CuMemberBonusPushExt cuMemberBonusPush : list) {
                cuMemberBonusPush.setMemberCode(CommonUtil.getMemberCode(cuMemberBonusPush.getMemberCode(), cuMemberBonusPush.getServiceCode()));
                cuMemberBonusPush.setMemberName(CommonUtil.getMemberName(cuMemberBonusPush.getPkVertex(), cuMemberBonusPush.getMemberName(), cuMemberBonusPush.getNickName()));

                for (GradeDTO gradeDTO : gradeDate) {
                    // 注册等级
                    if (cuMemberBonusPush.getPkRegisterGrade() != null) {
                        if (cuMemberBonusPush.getPkRegisterGrade().equals(gradeDTO.getPkId())) {
                            cuMemberBonusPush.setPkRegisterGradeStr(transactionMap1.get(gradeDTO.getPkTransaction()));
                        }
                    }
                }
                if (cuMemberBonusPush.getOrderType() != null) {
                    cuMemberBonusPush.setOrderTypeStr(transactionMap.get(EnumsPrefixConstants.ORDER_TYPE + cuMemberBonusPush.getOrderType()));
                }
                // 注册业绩 国内 * 汇率
                if (SecurityUtils.getPkCountry().equals(CountryConstants.CHINA_COUNTRY)) {
                    if (cuMemberBonusPush.getOrderAchieve() == null) {
                        cuMemberBonusPush.setOrderAchieve(BigDecimal.ZERO);
                    }
                    cuMemberBonusPush.setOrderAchieve(cuMemberBonusPush.getOrderAchieve().multiply(inExchangeRate));
                } else {
                    cuMemberBonusPush.setOrderAchieve(cuMemberBonusPush.getOrderAchieve());
                }
                cuMemberBonusPush.setCreationTime(cuMemberBonusPush.getMemberPayTime());
            }
        }
        return getDataTable(list);
    }

    /**
     * 三单循环获取下一轮次
     */
    @GetMapping("/next-round")
    public AjaxResult nextRound() {
        Long pkMember = SecurityUtils.getUserId();
        CuMemberBonusPush memberBonusPush = iCuMemberBonusPushService.nextRound(pkMember);
        if (memberBonusPush == null || memberBonusPush.getRound() == null || memberBonusPush.getSecond() == null) {
            memberBonusPush.setSecond(1);
            memberBonusPush.setRound(1);
        }
        if (memberBonusPush.getSecond() == 3) {
            // 三单循环第三轮
            memberBonusPush.setSecond(1);
            memberBonusPush.setRound(memberBonusPush.getRound() + 1);
        } else {
            memberBonusPush.setSecond(memberBonusPush.getSecond() + 1);
        }
        return AjaxResult.success(memberBonusPush);
    }

}
