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.enums.EOrderType;
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.CuBonusVertexStatisTotalVO;
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.ArrayList;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private ICuBonusVertexStatisService iCuBonusVertexStatisService;
    @DubboReference
    ICurrencyServiceApi currencyServiceApi;

    /**
     * 奖金拨比列表
     **/
    @AccessPermissions("TopPerformanceTotal")
    @GetMapping("/list")
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_VERTEX_RATIO_TOTAL, method = EOperationMethod.SELECT)
    public TableDataInfo list(CuBonusVertexStatisTotalVO cuBonusVertexStatisTotalVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuBonusVertexStatisTotalVO> slList;
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
        BigDecimal exchangeRate = currency.getData().getInExchangeRate() == null ? BigDecimal.ONE : currency.getData().getInExchangeRate();
        cuBonusVertexStatisTotalVO.setRate(exchangeRate);
        BigDecimal cent = new BigDecimal(100);
        cuBonusVertexStatisTotalVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStatisTotalVO.setPkCountry(pkCountry);
        //默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStatisTotalVO.getStartDate()) ||
                StringUtils.isEmpty(cuBonusVertexStatisTotalVO.getEndDate())) {
            cuBonusVertexStatisTotalVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStatisTotalVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(EOrderType.REGISTER_ORDER.getValue());
        orderTypeList.add(EOrderType.UPGRADE_ORDER.getValue());
        cuBonusVertexStatisTotalVO.setOrderTypeList(orderTypeList);
        //查询分红比例配置
        cuBonusVertexStatisTotalVO.setDividendRatio(BigDecimal.ZERO);
        //查询顶点会员
        List<CuBonusVertexStatisTotalVO> vertexList = iCuBonusVertexStatisService.queryCuBonusVertex(cuBonusVertexStatisTotalVO);

        CuBonusVertexStatisVO cvs = BeanUtil.copyProperties(cuBonusVertexStatisTotalVO, CuBonusVertexStatisVO.class);
        for (CuBonusVertexStatisTotalVO ve : vertexList) {
            cvs.setPkVertex(ve.getPkVertex());

//            CuBonusVertexStatisTotalVO energyChamberAmountSum = iCuBonusVertexStatisService.queryEnergyChamberOrderTotal(cvs);
//            //查询顶点拓展封顶人数
//            CuBonusVertexStatisTotalVO orgTopNumber = iCuBonusVertexStatisService.queryOrgTopNumber(cvs);
//            if (orgTopNumber != null) {
//                energyChamberAmountSum.setOrgTopNumber(orgTopNumber.getOrgTopNumber());
//            }
//            //查询顶点拓展平均碰次和拓展最高碰次
//            CuBonusVertexStatisTotalVO touch = iCuBonusVertexStatisService.queryTouch(cvs);
//            if (touch != null) {
//                energyChamberAmountSum.setOrgAvTouch(touch.getOrgAvTouch());
//                energyChamberAmountSum.setOrgMaxTouch(touch.getOrgMaxTouch());
//            }

        }
        startPage();
        //查询顶点奖金拨比汇总
        slList = iCuBonusVertexStatisService.queryCuBonusStatisTotal(cuBonusVertexStatisTotalVO);
        //查询顶点奖金拨比汇总总和（最后一行）
        CuBonusVertexStatisTotalVO cuBonusVertexStatisSum = iCuBonusVertexStatisService.queryCuBonusStatisSum(cuBonusVertexStatisTotalVO);
        cuBonusVertexStatisSum.setMainBonus((cuBonusVertexStatisSum.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
        cuBonusVertexStatisSum.setRepurBonus(cuBonusVertexStatisSum.getRepurBonus().multiply(currency.getData().getInExchangeRate()));
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(itm -> {

//                if (itm.getPkVertex().equals(itmm.getPkVertex())) {
//                    itm.setFirstPurchaseAll(itm.getFirstPurchaseAll().subtract(itmm.getOrderAmount()).add(itmm.getEnergySum()));
//                    itm.setOrgTopNumber(itmm.getOrgTopNumber());
//                    itm.setOrgAvTouch(itmm.getOrgAvTouch());
//                    itm.setOrgMaxTouch(itmm.getOrgMaxTouch());
//                }

                //重新算首购拨比
                if (itm.getFirstPurchaseAll().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal mainBonusRate = cent.multiply((itm.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
                    mainBonusRate = mainBonusRate.divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP);
                    itm.setMainBonusRate(mainBonusRate);
                    itm.setIntroduceBonusRate(itm.getIntroduceBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setOrgBonusRate(itm.getOrgBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setServiceBonusRate(itm.getServiceBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                }
                //首购拨出金额
                itm.setMainBonus((itm.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
                itm.setRepurBonus(itm.getRepurBonus().multiply(currency.getData().getInExchangeRate()));
                cuBonusVertexStatisTotalVO.setFirstPurchaseAllSum(cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum().add(itm.getFirstPurchaseAll()));
            });
        }
        //计算占比
        slList.forEach(itm -> {
            if (cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum().compareTo(BigDecimal.ZERO) > 0) {
                itm.setFirstPurchaseRatio(cent.multiply(itm.getFirstPurchaseAll()).divide(cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum(), 4, RoundingMode.HALF_UP));
            }
        });
        cuBonusVertexStatisSum.setMemberName("汇总");
        slList.add(cuBonusVertexStatisSum);
        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, CuBonusVertexStatisTotalVO cuBonusVertexStatisTotalVO) {
        Integer pkCountry = SecurityUtils.getPkCountry();
        List<CuBonusVertexStatisTotalVO> slList;
        R<CurrencyDTO> currency = currencyServiceApi.getCurrency(pkCountry);
        BigDecimal exchangeRate = currency.getData().getInExchangeRate() == null ? BigDecimal.ONE : currency.getData().getInExchangeRate();
        cuBonusVertexStatisTotalVO.setRate(exchangeRate);
        BigDecimal cent = new BigDecimal(100);
        cuBonusVertexStatisTotalVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStatisTotalVO.setPkCountry(pkCountry);
        //默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStatisTotalVO.getStartDate()) ||
                StringUtils.isEmpty(cuBonusVertexStatisTotalVO.getEndDate())) {
            cuBonusVertexStatisTotalVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStatisTotalVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }
        List<Integer> orderTypeList = new ArrayList<>();
        orderTypeList.add(EOrderType.REGISTER_ORDER.getValue());
        orderTypeList.add(EOrderType.UPGRADE_ORDER.getValue());
        cuBonusVertexStatisTotalVO.setOrderTypeList(orderTypeList);
        //查询分红比例配置
        cuBonusVertexStatisTotalVO.setDividendRatio(BigDecimal.ZERO);
        //查询顶点会员
        List<CuBonusVertexStatisTotalVO> vertexList = iCuBonusVertexStatisService.queryCuBonusVertex(cuBonusVertexStatisTotalVO);

        CuBonusVertexStatisVO cvs = BeanUtil.copyProperties(cuBonusVertexStatisTotalVO, CuBonusVertexStatisVO.class);
        for (CuBonusVertexStatisTotalVO ve : vertexList) {
            cvs.setPkVertex(ve.getPkVertex());

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

        startPage();
        //查询顶点奖金拨比汇总
        slList = iCuBonusVertexStatisService.queryCuBonusStatisTotal(cuBonusVertexStatisTotalVO);
        //查询顶点奖金拨比汇总总和（最后一行）
        CuBonusVertexStatisTotalVO cuBonusVertexStatisSum = iCuBonusVertexStatisService.queryCuBonusStatisSum(cuBonusVertexStatisTotalVO);
        cuBonusVertexStatisSum.setMainBonus((cuBonusVertexStatisSum.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
        cuBonusVertexStatisSum.setRepurBonus(cuBonusVertexStatisSum.getRepurBonus().multiply(currency.getData().getInExchangeRate()));
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(itm -> {

//                if (itm.getPkVertex().equals(itmm.getPkVertex())) {
//                    itm.setFirstPurchaseAll(itm.getFirstPurchaseAll().subtract(itmm.getOrderAmount()).add(itmm.getEnergySum()));
//                    itm.setOrgTopNumber(itmm.getOrgTopNumber());
//                    itm.setOrgAvTouch(itmm.getOrgAvTouch());
//                    itm.setOrgMaxTouch(itmm.getOrgMaxTouch());
//                }

                //重新算首购拨比
                if (itm.getFirstPurchaseAll().compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal mainBonusRate = cent.multiply((itm.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
                    mainBonusRate = mainBonusRate.divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP);
                    itm.setMainBonusRate(mainBonusRate);
                    itm.setIntroduceBonusRate(itm.getIntroduceBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setOrgBonusRate(itm.getOrgBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                    itm.setServiceBonusRate(itm.getServiceBonus().multiply(cuBonusVertexStatisTotalVO.getPerCent()).divide(itm.getFirstPurchaseAll(), 4, RoundingMode.HALF_UP));
                }
                //首购拨出金额
                itm.setMainBonus((itm.getMainBonus()).multiply(currency.getData().getInExchangeRate()));
                itm.setRepurBonus(itm.getRepurBonus().multiply(currency.getData().getInExchangeRate()));
                cuBonusVertexStatisTotalVO.setFirstPurchaseAllSum(cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum().add(itm.getFirstPurchaseAll()));
            });
        }
        //计算占比
        slList.forEach(itm -> {
            if (cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum().compareTo(BigDecimal.ZERO) > 0) {
                itm.setFirstPurchaseRatio(cent.multiply(itm.getFirstPurchaseAll()).divide(cuBonusVertexStatisTotalVO.getFirstPurchaseAllSum(), 4, RoundingMode.HALF_UP));
            }
        });
        cuBonusVertexStatisSum.setMemberName("汇总");
        slList.add(cuBonusVertexStatisSum);
        ExcelUtil<CuBonusVertexStatisTotalVO> util = new ExcelUtil<>(CuBonusVertexStatisTotalVO.class);
        util.exportExcel(response, slList, "拨比列表");
    }

}
