package com.hzs.member.statis.controller.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.domain.R;
import com.hzs.common.core.enums.EOperationBusiness;
import com.hzs.common.core.enums.EOperationMethod;
import com.hzs.common.core.enums.EOperationModule;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.core.utils.poi.ExcelUtil;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.member.statis.service.ICuBonusVertexStatisService;
import com.hzs.member.statis.vo.CuBonusVertexStaticTotalVO;
import com.hzs.member.statis.vo.CuBonusVertexStatisVO;
import com.hzs.system.base.ICurrencyServiceApi;
import com.hzs.system.base.dto.CurrencyDTO;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 奖金拨比零线汇总统计 前端控制器
 */
@Slf4j
@RestController
@RequestMapping("/manage/bonus-vertex-total-statis")
public class CuBonusVertexStatisTotalController extends BaseController {

    @Autowired
    private ICuBonusVertexStatisService iCuBonusVertexStatisService;
    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 奖金拨比列表
     **/
    @AccessPermissions("TopPerformanceTotal")
    @GetMapping("/list")
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_VERTEX_RATIO_TOTAL, method = EOperationMethod.SELECT)
    public TableDataInfo list(CuBonusVertexStaticTotalVO cuBonusVertexStaticTotalVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(pkCountry);
        BigDecimal cent = new BigDecimal(100);
        BigDecimal exchangeRate = currency.getData().getInExchangeRate() == null ? BigDecimal.ONE : currency.getData().getInExchangeRate();
        cuBonusVertexStaticTotalVO.setRate(exchangeRate);
        cuBonusVertexStaticTotalVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStaticTotalVO.setPkCountry(pkCountry);
        //默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStaticTotalVO.getStartDate())
                || StringUtils.isEmpty(cuBonusVertexStaticTotalVO.getEndDate())) {
            cuBonusVertexStaticTotalVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStaticTotalVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }

        Map<Integer, CuBonusVertexStaticTotalVO> touchMap = new HashMap<>();
        //查询顶点会员
        List<CuBonusVertexStaticTotalVO> vertexList = iCuBonusVertexStatisService.queryCuBonusVertex(cuBonusVertexStaticTotalVO);
        CuBonusVertexStatisVO cvs = BeanUtil.copyProperties(cuBonusVertexStaticTotalVO, CuBonusVertexStatisVO.class);
        for (CuBonusVertexStaticTotalVO ve : vertexList) {
            cvs.setPkVertex(ve.getPkVertex());

            CuBonusVertexStaticTotalVO mapTouch = new CuBonusVertexStaticTotalVO();
            mapTouch.setPkVertex(ve.getPkVertex());
            //查询顶点拓展封顶人数
            CuBonusVertexStaticTotalVO orgTopNumber = iCuBonusVertexStatisService.queryOrgTopNumber(cvs);
            if (orgTopNumber != null) {
                mapTouch.setOrgTopNumber(orgTopNumber.getOrgTopNumber());
            }
            //查询顶点拓展平均碰次和拓展最高碰次
            CuBonusVertexStaticTotalVO touch = iCuBonusVertexStatisService.queryTouch(cvs);
            if (touch != null) {
                mapTouch.setOrgAvTouch(touch.getOrgAvTouch());
                mapTouch.setOrgMaxTouch(touch.getOrgMaxTouch());
            }
            touchMap.put(ve.getPkVertex(), mapTouch);
        }

        startPage();
        //查询顶点奖金拨比汇总
        List<CuBonusVertexStaticTotalVO> slList = iCuBonusVertexStatisService.queryCuBonusStatisTotal(cuBonusVertexStaticTotalVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(itm -> {
                CuBonusVertexStaticTotalVO tmpTotalVO = touchMap.get(itm.getPkVertex());
                if (null != tmpTotalVO) {
                    itm.setOrgTopNumber(tmpTotalVO.getOrgTopNumber());
                    itm.setOrgAvTouch(tmpTotalVO.getOrgAvTouch());
                    itm.setOrgMaxTouch(tmpTotalVO.getOrgMaxTouch());
                }
                if (itm.getFirstPurchaseAll().compareTo(BigDecimal.ZERO) > 0) {
                    itm.setIntroduceBonusRate(itm.getIntroduceBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setOrgBonusRate(itm.getOrgBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setLeaderBonusRate(itm.getLeaderBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setServiceBonusRate(itm.getServiceBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                }
                if (itm.getRepurchaseAllAmount().compareTo(BigDecimal.ZERO) > 0) {
                    itm.setRepurRangeBonusRate(itm.getRepurRangeBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                    itm.setRepurOrgBonusRate(itm.getRepurOrgBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                    itm.setRepurLeaderBonusRate(itm.getRepurLeaderBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                }
            });
        }

        //查询顶点奖金拨比汇总总和（最后一行）
        CuBonusVertexStaticTotalVO cuBonusVertexStaticSum = iCuBonusVertexStatisService.queryCuBonusStatisSum(cuBonusVertexStaticTotalVO);
        if (null != cuBonusVertexStaticSum) {
            cuBonusVertexStaticSum.setMemberName("汇总");
            slList.add(cuBonusVertexStaticSum);
        } else {
            slList.add(new CuBonusVertexStaticTotalVO());
        }
        return getDataTable(slList);
    }

    /**
     * 导出奖金拨比列表
     **/
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_VERTEX_RATIO_TOTAL, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuBonusVertexStaticTotalVO cuBonusVertexStaticTotalVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        R<CurrencyDTO> currency = iCurrencyServiceApi.getCurrency(pkCountry);
        BigDecimal cent = new BigDecimal(100);
        BigDecimal exchangeRate = currency.getData().getInExchangeRate() == null ? BigDecimal.ONE : currency.getData().getInExchangeRate();
        cuBonusVertexStaticTotalVO.setRate(exchangeRate);
        cuBonusVertexStaticTotalVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStaticTotalVO.setPkCountry(pkCountry);
        //默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStaticTotalVO.getStartDate()) ||
                StringUtils.isEmpty(cuBonusVertexStaticTotalVO.getEndDate())) {
            cuBonusVertexStaticTotalVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStaticTotalVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }

        Map<Integer, CuBonusVertexStaticTotalVO> touchMap = new HashMap<>();
        //查询顶点会员
        List<CuBonusVertexStaticTotalVO> vertexList = iCuBonusVertexStatisService.queryCuBonusVertex(cuBonusVertexStaticTotalVO);
        CuBonusVertexStatisVO cvs = BeanUtil.copyProperties(cuBonusVertexStaticTotalVO, CuBonusVertexStatisVO.class);
        for (CuBonusVertexStaticTotalVO ve : vertexList) {
            cvs.setPkVertex(ve.getPkVertex());

            CuBonusVertexStaticTotalVO mapTouch = new CuBonusVertexStaticTotalVO();
            mapTouch.setPkVertex(ve.getPkVertex());
            //查询顶点拓展封顶人数
            CuBonusVertexStaticTotalVO orgTopNumber = iCuBonusVertexStatisService.queryOrgTopNumber(cvs);
            if (orgTopNumber != null) {
                mapTouch.setOrgTopNumber(orgTopNumber.getOrgTopNumber());
            }
            //查询顶点拓展平均碰次和拓展最高碰次
            CuBonusVertexStaticTotalVO touch = iCuBonusVertexStatisService.queryTouch(cvs);
            if (touch != null) {
                mapTouch.setOrgAvTouch(touch.getOrgAvTouch());
                mapTouch.setOrgMaxTouch(touch.getOrgMaxTouch());
            }
            touchMap.put(ve.getPkVertex(), mapTouch);
        }

        //查询顶点奖金拨比汇总
        List<CuBonusVertexStaticTotalVO> slList = iCuBonusVertexStatisService.queryCuBonusStatisTotal(cuBonusVertexStaticTotalVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(itm -> {
                CuBonusVertexStaticTotalVO tmpTotalVO = touchMap.get(itm.getPkVertex());
                if (null != tmpTotalVO) {
                    itm.setOrgTopNumber(tmpTotalVO.getOrgTopNumber());
                    itm.setOrgAvTouch(tmpTotalVO.getOrgAvTouch());
                    itm.setOrgMaxTouch(tmpTotalVO.getOrgMaxTouch());
                }
                //重新算首购拨比
                if (itm.getFirstPurchaseAll().compareTo(BigDecimal.ZERO) > 0) {
                    itm.setIntroduceBonusRate(itm.getIntroduceBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setOrgBonusRate(itm.getOrgBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setLeaderBonusRate(itm.getLeaderBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setServiceBonusRate(itm.getServiceBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                }
                if (itm.getRepurchaseAllAmount().compareTo(BigDecimal.ZERO) > 0) {
                    itm.setRepurRangeBonusRate(itm.getRepurRangeBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                    itm.setRepurOrgBonusRate(itm.getRepurOrgBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                    itm.setRepurLeaderBonusRate(itm.getRepurLeaderBonus().multiply(cuBonusVertexStaticTotalVO.getPerCent()).divide(itm.getRepurchaseAllAmount(), 4, RoundingMode.HALF_UP));
                }
            });
        }

        //查询顶点奖金拨比汇总总和（最后一行）
        CuBonusVertexStaticTotalVO cuBonusVertexStaticSum = iCuBonusVertexStatisService.queryCuBonusStatisSum(cuBonusVertexStaticTotalVO);
        if (null != cuBonusVertexStaticSum) {
            cuBonusVertexStaticSum.setMemberName("汇总");
            slList.add(cuBonusVertexStaticSum);
        } else {
            slList.add(new CuBonusVertexStaticTotalVO());
        }
        ExcelUtil<CuBonusVertexStaticTotalVO> util = new ExcelUtil<>(CuBonusVertexStaticTotalVO.class);
        util.exportExcel(response, slList, "拨比列表");
    }

}
