package com.hzs.bonus.bonus.controller.manage;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.hzs.bonus.bonus.param.BonusParam;
import com.hzs.bonus.bonus.service.ICuMemberBonusService;
import com.hzs.bonus.bonus.vo.BonusTotalVO;
import com.hzs.bonus.bonus.vo.CuMemberBonusVO;
import com.hzs.bonus.bonus.vo.MemberBonusDetailSerVO;
import com.hzs.common.core.annotation.AccessPermissions;
import com.hzs.common.core.annotation.ColumnAuthority;
import com.hzs.common.core.annotation.Log;
import com.hzs.common.core.constant.BonusFieldConstants;
import com.hzs.common.core.constant.EnumsPrefixConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
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.utils.reflect.ReflectUtils;
import com.hzs.common.core.web.controller.BaseController;
import com.hzs.common.core.web.page.TableDataInfo;
import com.hzs.common.domain.member.ext.CuMemberBonusExt;
import com.hzs.common.security.utils.SecurityUtils;
import com.hzs.common.service.ITransactionCommonService;
import com.hzs.system.sys.IMenuColumnServiceApi;
import com.hzs.system.sys.IUserServiceApi;
import com.hzs.system.sys.dto.UserAuthorityDTO;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 会员奖金-会员奖金汇总表 前端控制器
 */
@RestController
@RequestMapping("/manage/bonus")
public class CuMemberBonusController extends BaseController {

    @Autowired
    private ICuMemberBonusService iCuMemberBonusService;
    @Autowired
    private ITransactionCommonService iTransactionCommonService;

    @DubboReference
    IUserServiceApi iUserServiceApi;
    @DubboReference
    IMenuColumnServiceApi iMenuColumnServiceApi;

    /**
     * 分页查询会员某个时间段内的奖金汇总
     */
    @AccessPermissions("totalBonus")
    @PostMapping("/query-bonus-total")
    @Log(module = EOperationModule.BONUS_TOTAL, business = EOperationBusiness.BONUS_TOTAL, method = EOperationMethod.SELECT)
    @ColumnAuthority(perms = "totalBonus")
    public TableDataInfo listBonusTotal(@RequestBody BonusParam bonusParam) {
        List<Integer> pkVertex = new ArrayList<>();
        if (StringUtils.isNotEmpty(bonusParam.getPkBdVertexStr())) {
            pkVertex = Arrays.stream(bonusParam.getPkBdVertexStr().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        }
        bonusParam.setPkVertexList(pkVertex);
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        packageBonusParam(bonusParam);
        startPage();
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryBonusTotalVoByConditionForServer(bonusParam);
        TableDataInfo dataTable = getDataTable(cuMemberBonusList);
        dataTable.setRows(getBonusTotalVoS(cuMemberBonusList));
        return dataTable;
    }

    /**
     * 分页查询会员某个时间段内的奖金汇总
     */
    @PostMapping("/export-bonus-total")
    @Log(module = EOperationModule.BONUS_TOTAL, business = EOperationBusiness.BONUS_TOTAL, method = EOperationMethod.EXPORT)
    public void exportBonusTotal(HttpServletResponse response, BonusParam bonusParam) {
        List<Integer> pkVertex = new ArrayList<>();
        if (StringUtils.isNotEmpty(bonusParam.getPkBdVertexStr())) {
            pkVertex = Arrays.stream(bonusParam.getPkBdVertexStr().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        }
        bonusParam.setPkVertexList(pkVertex);
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        packageBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusList = iCuMemberBonusService.queryBonusTotalVoByConditionForServer(bonusParam);
        List<BonusTotalVO> bonusTotalVoList = getBonusTotalVoS(cuMemberBonusList);
        Map<String, Integer> sourceBonusList = iMenuColumnServiceApi.queryMenuColumn("totalBonus", SecurityUtils.getUserId()).getData();
        ExcelUtil<BonusTotalVO> util = new ExcelUtil<>(BonusTotalVO.class, sourceBonusList);
        util.exportExcel(response, bonusTotalVoList, "奖金汇总导出");
    }

    private List<BonusTotalVO> getBonusTotalVoS(List<CuMemberBonusExt> cuMemberBonusList) {
        List<BonusTotalVO> totalVoList = new ArrayList<>();
        cuMemberBonusList.forEach(cuMemberBonus -> {
            totalVoList.add(BeanUtil.copyProperties(cuMemberBonus, BonusTotalVO.class));
        });
        return totalVoList;
    }

    /**
     * 分页查询会员某个时间段内的奖金明细
     */
    @AccessPermissions("BonusDetail")
    @PostMapping("/query-bonus-detail")
    @Log(module = EOperationModule.BONUS_DETAIL, method = EOperationMethod.SELECT)
    public TableDataInfo listBonus(@RequestBody BonusParam bonusParam) {
        List<Integer> pkVertex = new ArrayList<>();
        if (StringUtils.isNotEmpty(bonusParam.getPkBdVertexStr())) {
            pkVertex = Arrays.stream(bonusParam.getPkBdVertexStr().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        }
        bonusParam.setPkVertexList(pkVertex);
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        //获取管理员权限《角色地区范围、 体系列表、团队列表)
        Date date = DateUtils.currentDate();
        if (null == bonusParam.getStartDate() || null == bonusParam.getEndDate()) {
            bonusParam.setStartDate(DateUtils.currentMonthFirstDate());
            bonusParam.setEndDate(DateUtils.beforeDate(1, ChronoUnit.DAYS, date));
        }
        packageBonusParam(bonusParam);

        startPage();
        List<CuMemberBonusExt> cuMemberBonusExtList = iCuMemberBonusService.queryMemberBonusVoByConditionForServer(bonusParam);
        CuMemberBonusExt cmb = iCuMemberBonusService.queryMemberBonusByConditionForServerSum(bonusParam);
        if (cmb != null) {
            cmb.setMemberCode("合计");
            cuMemberBonusExtList.add(cmb);
        }
        List<CuMemberBonusVO> cuMemberBonusVoList = getBonusDetail(cuMemberBonusExtList);
        TableDataInfo dataTable = getDataTable(cuMemberBonusExtList);
        dataTable.setRows(cuMemberBonusVoList);
        return dataTable;
    }

    /**
     * 分页查询会员某个时间段内的奖金明细
     */
    @PostMapping("/export-bonus-detail")
    @Log(module = EOperationModule.BONUS_DETAIL, method = EOperationMethod.SELECT)
    public void exportBonusDetail(HttpServletResponse response, BonusParam bonusParam) {
        List<Integer> pkVertex = new ArrayList<>();
        if (StringUtils.isNotEmpty(bonusParam.getPkBdVertexStr())) {
            pkVertex = Arrays.stream(bonusParam.getPkBdVertexStr().split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
        }
        bonusParam.setPkVertexList(pkVertex);
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        packageBonusParam(bonusParam);
        List<CuMemberBonusExt> cuMemberBonusExtList = iCuMemberBonusService.queryMemberBonusVoByConditionForServer(bonusParam);
        CuMemberBonusExt cuMemberBonusExt = iCuMemberBonusService.initCuMemberBonus();
        cuMemberBonusExt.setMemberCode("小计：");
        if (CollectionUtil.isNotEmpty(cuMemberBonusExtList)) {
            cuMemberBonusExt.setOutExchangeRate(cuMemberBonusExtList.get(0).getOutExchangeRate());
            for (CuMemberBonusExt memberBonusExt : cuMemberBonusExtList) {
                iCuMemberBonusService.calculateBonusTotal(cuMemberBonusExt, memberBonusExt);
            }
        }
        cuMemberBonusExtList.add(cuMemberBonusExt);
        List<CuMemberBonusVO> cuMemberBonusVoList = getBonusDetail(cuMemberBonusExtList);
        Map<String, Integer> bonusDetail = iMenuColumnServiceApi.queryMenuColumn("BonusDetail", SecurityUtils.getUserId()).getData();
        ExcelUtil<CuMemberBonusVO> util = new ExcelUtil<>(CuMemberBonusVO.class, bonusDetail);
        util.exportExcel(response, cuMemberBonusVoList, "奖金明细导出");
    }

    private List<CuMemberBonusVO> getBonusDetail(List<CuMemberBonusExt> cuMemberBonusExtList) {
        List<CuMemberBonusVO> cuMemberBonusVoList = new ArrayList<>(cuMemberBonusExtList.size());
        for (CuMemberBonusExt cuMemberBonusExt : cuMemberBonusExtList) {
            CuMemberBonusVO cuMemberBonusVO = BeanUtil.copyProperties(cuMemberBonusExt, CuMemberBonusVO.class);

            cuMemberBonusVO.setMemberCode(cuMemberBonusExt.getMemberCode());
            cuMemberBonusVO.setMemberName(cuMemberBonusExt.getMemberName());

            for (String key : CuMemberBonusVO.INCOME_ARRAY) {
                ReflectUtils.invokeSetter(cuMemberBonusVO, key + BonusFieldConstants.INCOME_SUFFIX, ComputeUtil.computeMultiply(ReflectUtils.invokeGetter(cuMemberBonusExt, key), cuMemberBonusExt.getOutExchangeRate()));
            }
            cuMemberBonusVoList.add(cuMemberBonusVO);
        }
        return cuMemberBonusVoList;
    }

    /**
     * 分页查询会员某个时间段内的奖金来源
     */
    @AccessPermissions("sourceBonus")
    @PostMapping("/query-bonus-source")
    @Log(module = EOperationModule.BONUS_SOURCE, business = EOperationBusiness.BONUS_SOURCE, method = EOperationMethod.SELECT)
    public TableDataInfo listBonusSource(@RequestBody BonusParam bonusParam) {
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        packageBonusParam(bonusParam);
        startPage();
        return iCuMemberBonusService.queryMemberBonusDetailSerVoByCondition(bonusParam);
    }


    /**
     * 分页查询会员某个时间段内的奖金来源
     */
    @PostMapping("/export-bonus-source")
    @Log(module = EOperationModule.BONUS_SOURCE, business = EOperationBusiness.BONUS_SOURCE, method = EOperationMethod.EXPORT)
    public void exportBonusSource(HttpServletResponse response, BonusParam bonusParam) {
        bonusParam.setPkCountry(SecurityUtils.getPkCountry());
        packageBonusParam(bonusParam);
        TableDataInfo tableDataInfo = iCuMemberBonusService.queryMemberBonusDetailSerVoByCondition(bonusParam);
        List<MemberBonusDetailSerVO> memberBonusDetailSerVOList = (List<MemberBonusDetailSerVO>) tableDataInfo.getRows();

        // 获取需要翻译的枚举翻译
        Map<Integer, String> transactionLongMap = iTransactionCommonService.exportEnumTransactionByDB(EnumsPrefixConstants.KEY_GRADE, EnumsPrefixConstants.KEY_AWARD);
        for (MemberBonusDetailSerVO memberBonusDetailSerVO : memberBonusDetailSerVOList) {
            memberBonusDetailSerVO.setOrderTypeVal(EOrderType.getEnumLabelByValue(memberBonusDetailSerVO.getOrderType()));
            memberBonusDetailSerVO.setIncomeStatusVal(EBonusIncomeStatus.getEnumLabelByValue(memberBonusDetailSerVO.getIncomeStatus()));

            if (transactionLongMap.containsKey(memberBonusDetailSerVO.getPkSettleGrade())) {
                memberBonusDetailSerVO.setPkSettleGradeVal(transactionLongMap.get(memberBonusDetailSerVO.getPkSettleGrade()));
            }
            if (transactionLongMap.containsKey(memberBonusDetailSerVO.getPkAwards())) {
                memberBonusDetailSerVO.setPkAwardsVal(transactionLongMap.get(memberBonusDetailSerVO.getPkAwards()));
            }
        }
        ExcelUtil<MemberBonusDetailSerVO> util = new ExcelUtil<>(MemberBonusDetailSerVO.class, iMenuColumnServiceApi.queryMenuColumn("sourceBonus", SecurityUtils.getUserId()).getData());
        util.exportExcel(response, memberBonusDetailSerVOList, "奖金来源导出");
    }

    private void packageBonusParam(BonusParam bonusParam) {
        UserAuthorityDTO userAuthorityDto = iUserServiceApi.getUserAuthority(SecurityUtils.getUserId()).getData();
        bonusParam.setVertexList(userAuthorityDto.getUserVertexList());
        bonusParam.setTeamList(userAuthorityDto.getUserTeamList());
        bonusParam.setSystemType(SecurityUtils.getSystemType());
    }
}
