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

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.constant.msg.FinanceMsgConstants;
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.domain.AjaxResult;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.util.TransactionUtils;
import com.hzs.member.statis.service.ICuBonusVertexStatisService;
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.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private ICuBonusVertexStatisService iCuBonusVertexStatisService;

    @DubboReference
    ICurrencyServiceApi iCurrencyServiceApi;

    /**
     * 查询所有顶点会员
     **/
    @GetMapping("/vertexList")
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_VERTEX_RATIO_LIST, method = EOperationMethod.SELECT)
    public TableDataInfo vertexList() {
        List<CuBonusVertexStatisVO> vertexList = iCuBonusVertexStatisService.vertexList(null);
        return getDataTable(vertexList);
    }

    /**
     * 顶点奖金拨比列表统计
     **/
    @AccessPermissions("TopPerformance")
    @GetMapping("/list")
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_VERTEX_RATIO_LIST, method = EOperationMethod.SELECT)
    public TableDataInfo list(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        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();
        cuBonusVertexStatisVO.setRate(exchangeRate);
        cuBonusVertexStatisVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStatisVO.setPkCountry(pkCountry);

        //默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStatisVO.getStartDate())
                || StringUtils.isEmpty(cuBonusVertexStatisVO.getEndDate())) {
            cuBonusVertexStatisVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStatisVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }

        startPage();
        //查询中国奖金拨比列表
        List<CuBonusVertexStatisVO> slList = iCuBonusVertexStatisService.queryCuBonusStatis(cuBonusVertexStatisVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(item -> {
                item.setMainRegAmount(item.getMainRegAmount().add(item.getSpecialRegisterAmount()));
                item.setMainUpAmount(item.getMainUpAmount().add(item.getSpecialUpgradeAmount()));
                item.setMainRepurAmount(item.getMainRepurAmount().add(item.getSpecialRepurchaseAmount()));
            });
        }
        return getDataTable(slList);
    }

    /**
     * 顶点奖金拨比列表统计导出
     **/
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_RATIO_LIST, method = EOperationMethod.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        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();
        cuBonusVertexStatisVO.setRate(exchangeRate);
        cuBonusVertexStatisVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStatisVO.setPkCountry(pkCountry);

        // 默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStatisVO.getStartDate())
                || StringUtils.isEmpty(cuBonusVertexStatisVO.getEndDate())) {
            cuBonusVertexStatisVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStatisVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }

        List<CuBonusVertexStatisVO> slList = iCuBonusVertexStatisService.queryCuBonusStatis(cuBonusVertexStatisVO);
        if (CollectionUtil.isNotEmpty(slList)) {
            slList.forEach(item -> {
                item.setMainRegAmount(item.getMainRegAmount().add(item.getSpecialRegisterAmount()));
                item.setMainUpAmount(item.getMainUpAmount().add(item.getSpecialUpgradeAmount()));
                item.setMainRepurAmount(item.getMainRepurAmount().add(item.getSpecialRepurchaseAmount()));
            });
        }

        // 合计
        CuBonusVertexStatisVO subtotal = iCuBonusVertexStatisService.queryCuBonusSumStatis(cuBonusVertexStatisVO);
        if (null != subtotal) {
            subtotal.setMemberCode("合计");
            subtotal.setMainBonusPvRate(subtotal.getMainBonusPvRateSum());
            subtotal.setRepurBonusPvRate(subtotal.getRepurBonusPvRateSum());
            subtotal.setMainRegAmount(subtotal.getMainRegAmountSum().add(subtotal.getSpecialRegisterAmountSum()));
            subtotal.setMainUpAmount(subtotal.getMainUpAmountSum().add(subtotal.getSpecialUpgradeAmountSum()));
            subtotal.setFirstPurchaseAll(subtotal.getFirstPurchaseAllSum());
            subtotal.setIntroduceBonus(subtotal.getIntroduceBonusSum());
            subtotal.setOrgBonus(subtotal.getOrgBonusSum());
            subtotal.setLeaderBonus(subtotal.getLeaderBonusSum());
            subtotal.setServiceBonus(subtotal.getServiceBonusSum());
            subtotal.setMainRepurAmount(subtotal.getMainRepurAmountSum().add(subtotal.getSpecialRepurchaseAmountSum()));
            subtotal.setRepurchaseAllAmount(subtotal.getRepurchaseAllAmountSum());
            subtotal.setRepurRangeBonus(subtotal.getRepurRangeBonusSum());
            subtotal.setRepurOrgBonus(subtotal.getRepurOrgBonusSum());
            subtotal.setRepurLeaderBonus(subtotal.getRepurLeaderBonusSum());
            subtotal.setMainBonus(subtotal.getMainBonusSum());
            subtotal.setMainBonusRate(subtotal.getMainBonusRateSum());
            subtotal.setRepurBonus(subtotal.getRepurBonusSum());
            subtotal.setRepurBonusRate(subtotal.getRepurBonusRateSum());
            subtotal.setTotalBonus(subtotal.getTotalBonusSum());
            subtotal.setTotalBonusRate(subtotal.getTotalBonusRateSum());
        }
        slList.add(subtotal);

        ExcelUtil<CuBonusVertexStatisVO> util = new ExcelUtil<>(CuBonusVertexStatisVO.class);
        util.exportExcel(response, slList, "拨比列表");
    }

    /**
     * 顶点奖金拨比列表统计合计
     **/
    @AccessPermissions("TopPerformance")
    @GetMapping("/subtotal")
    @Log(module = EOperationModule.BONUS_DIAL_RATIO, business = EOperationBusiness.BONUS_DIAL_RATIO_LIST, method = EOperationMethod.SELECT)
    public AjaxResult subtotal(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        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();
        cuBonusVertexStatisVO.setRate(exchangeRate);
        cuBonusVertexStatisVO.setPerCent(exchangeRate.multiply(cent));
        cuBonusVertexStatisVO.setPkCountry(pkCountry);

        // 默认查询当前日期的前一天
        Date date = DateUtils.currentDate();
        if (StringUtils.isEmpty(cuBonusVertexStatisVO.getStartDate())
                || StringUtils.isEmpty(cuBonusVertexStatisVO.getEndDate())) {
            cuBonusVertexStatisVO.setStartDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
            cuBonusVertexStatisVO.setEndDate(DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, date));
        }

        //查询合计
        CuBonusVertexStatisVO subtotal = iCuBonusVertexStatisService.queryCuBonusSumStatis(cuBonusVertexStatisVO);
        if (null != subtotal) {
            subtotal.setMainRegAmountSum(subtotal.getMainRegAmountSum().add(subtotal.getSpecialRegisterAmountSum()));
            subtotal.setMainUpAmountSum(subtotal.getMainUpAmountSum().add(subtotal.getSpecialUpgradeAmountSum()));
            subtotal.setMainRepurAmountSum(subtotal.getMainRepurAmountSum().add(subtotal.getSpecialRepurchaseAmountSum()));
        }
        return AjaxResult.success(subtotal);
    }

    /**
     * 统计历史奖金拨比数据, 手动统计某一天
     **/
    @GetMapping("/statis-history")
    public AjaxResult statisHistoryBonus(String startDate, String endDate) {
        if (StringUtils.isEmpty(startDate) || StringUtils.isEmpty(endDate)) {
            return AjaxResult.error(TransactionUtils.getContent(FinanceMsgConstants.SELECT_DATE_NOT_NULL));
        }
        List<CuBonusVertexStatisVO> vertexList = iCuBonusVertexStatisService.vertexList(null);
        List<Integer> pkVertexList = vertexList.stream().map(CuBonusVertexStatisVO::getPkVertex).collect(Collectors.toList());
        // 删除数据
        if (CollectionUtil.isNotEmpty(pkVertexList)) {
            iCuBonusVertexStatisService.delStatis(startDate, endDate, pkVertexList);
        }
        // 重新统计
        Boolean b = iCuBonusVertexStatisService.anewStatisHistoryBonus(startDate, endDate);
        return AjaxResult.success(b);
    }

}
