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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
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.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.base.CuMember;
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: yuhui
 * @Time: 2023/1/13 16:38
 * @Classname: MarketNewsController
 * @PackageName: com.hzs.member.marketNews.controller.api
 */
@RestController
@RequestMapping("/api/market-news")
public class MarketNewsController extends BaseController {
    @Autowired
    private ITransactionCommonService iTransactionCommonService;
    @Autowired
    private ICuMemberShareService memberShareService;
    @Autowired
    private ICuMemberService memberService;
    @Autowired
    private ICuMemberBonusPushService memberBonusPushService;
    @Autowired
    private ICuMemberBonusPushHisService cuMemberBonusPushHisService;

    @DubboReference
    IGradeServiceApi gradeServiceApi;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

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

        marketNewsParam.setPkCountry(pkCountry);
        startPage();
        List<UserInvestmentVo> list = memberService.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 = gradeServiceApi.queryGradeList(pkCountry);
        List<GradeDTO> gradeList = gradeDate.getData();
        R<CurrencyDTO> currencyDto = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        CurrencyDTO currency = currencyDto.getData();
        if (marketNewsParam.getEndCreationTime() != null) {
            marketNewsParam.setEndCreationTime(DateUtils.getEndTime(marketNewsParam.getEndCreationTime()));
        }
        startPage();
        List<UserInvestmentVo> list = memberService.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(userInvestmentVo.getMemberCode());
            userInvestmentVo.setMemberName(userInvestmentVo.getMemberName());
            userInvestmentVo.setParentCode(userInvestmentVo.getParentCode());
            userInvestmentVo.setParentName(userInvestmentVo.getParentName());
            userInvestmentVo.setPlaceParentCode(userInvestmentVo.getPlaceParentCode());
            userInvestmentVo.setPlaceParentName(userInvestmentVo.getPlaceParentName());
        }
        return getDataTable(list);
    }

    /**
     * 海粉列表
     */
    @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 = memberShareService.seaFlourList(seaFlourParam);
        if (CollectionUtil.isNotEmpty(memberList)) {
            for (SeaFlourVo seaFlourVo : memberList) {
                seaFlourVo.setMemberCode(seaFlourVo.getMemberCode());
                seaFlourVo.setMemberName(seaFlourVo.getMemberName());
            }
        }
        return getDataTable(memberList);
    }

    /**
     * 轮次历史业绩
     */
    @GetMapping("/round-his")
    public TableDataInfo seaFlourList() {
        List<CuMemberBonusPushHis> cuMemberBonusPushHis = cuMemberBonusPushHisService.queryCuMemberBonusPushHis(SecurityUtils.getUserId());
        if (Objects.equals(CountryConstants.CHINA_COUNTRY, SecurityUtils.getPkCountry())) {
            CurrencyDTO currencyDTO = currencyServiceApi.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) {
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(SecurityUtils.getPkCountry());
        // 汇率比例
        BigDecimal inExchangeRate = currency.getData().getInExchangeRate();
        R<List<GradeDTO>> gradeDto = gradeServiceApi.findAll();
        List<GradeDTO> gradeDate = gradeDto.getData();
        tripleCycleListParam.setPkMember(SecurityUtils.getUserId());
        startPage();
        if (tripleCycleListParam.getStartCreationTime() != null) {
            tripleCycleListParam.setStartCreationTime(DateUtil.beginOfDay(tripleCycleListParam.getStartCreationTime()));
        }
        if (tripleCycleListParam.getEndCreationTime() != null) {
            tripleCycleListParam.setEndCreationTime(DateUtil.endOfDay(tripleCycleListParam.getEndCreationTime()));
        }
        Map<String, String> transactionMap = iTransactionCommonService.exportEnumTransaction(EOrderType.values());
        Map<Integer, String> transactionMap1 = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE);
        //查询所有汇率
        R<List<CurrencyDTO>> currencyDTOList = currencyServiceApi.findAll();
        Map<Integer, CurrencyDTO> currencyMap = currencyDTOList.getData().stream().collect(Collectors.toMap(CurrencyDTO::getPkCountry, Function.identity()));
        // 禅道bug 8461 会员端，招商列表下的【三单循环】历史轮次需要显示已退单的会员数据   需要展示已删除的会员信息
        List<CuMemberBonusPushExt> list = memberBonusPushService.tripleCycleList(tripleCycleListParam);
        for (CuMemberBonusPushExt cuMemberBonusPush : list) {

            cuMemberBonusPush.setMemberCode(cuMemberBonusPush.getMemberCode());
            cuMemberBonusPush.setMemberName(cuMemberBonusPush.getMemberName());

            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 (cuMemberBonusPush.getOrderAchieve() == null) {
                cuMemberBonusPush.setOrderAchieve(BigDecimal.ZERO);
            }
            cuMemberBonusPush.setOrderAchieve(cuMemberBonusPush.getOrderAchieve().multiply(inExchangeRate));
            cuMemberBonusPush.setCreationTime(cuMemberBonusPush.getMemberPayTime());

            // 跨国报单 汇率转换
            Long pkCreator = cuMemberBonusPush.getPkCreator();
            CuMember member = memberService.getMember(pkCreator);
            if (!member.getPkSettleCountry().equals(cuMemberBonusPush.getPkCountry())) {
                // 会员结算国是中国 并且会员结算国和订单下单国家不一致
                CurrencyDTO thisCurrency = currencyMap.get(member.getPkSettleCountry());
                CurrencyDTO settleCurrency = currencyMap.get(cuMemberBonusPush.getPkCountry());
                cuMemberBonusPush.setOrderAmount(cuMemberBonusPush.getOrderAmount().divide(settleCurrency.getInExchangeRate(), 2, BigDecimal.ROUND_HALF_UP).multiply(thisCurrency.getInExchangeRate()));
            }

        }
        return getDataTable(list);
    }

    /**
     * 三单循环获取下一轮次
     */
    @GetMapping("next-round")
    public AjaxResult nextRound() {
        //   Integer pkCountry = SecurityUtils.getPkCountry();
        Long pkMember = SecurityUtils.getUserId();
        CuMemberBonusPush memberBonusPush = memberBonusPushService.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);
    }

}
