package com.artfess.cqlt.manager.impl;

import com.artfess.base.enums.KpiTargetTypeEnum;
import com.artfess.base.exception.BaseException;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.cqlt.dao.QfOperationKpiMDao;
import com.artfess.cqlt.manager.QfOperationKpiDManager;
import com.artfess.cqlt.manager.QfOperationKpiMManager;
import com.artfess.cqlt.model.QfOperationKpiD;
import com.artfess.cqlt.model.QfOperationKpiM;
import com.artfess.cqlt.vo.FaReportRespVo;
import com.artfess.cqlt.vo.FaTargetRespVo;
import com.artfess.cqlt.vo.ReportReqVo;
import com.artfess.i18n.util.I18nUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.api.client.util.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 运营--KPI数据填报主表 服务实现类
 *
 * @author min.wu
 * @company 阿特菲斯信息技术有限公司
 * @since 2023-02-14
 */
@Slf4j
@Service
public class QfOperationKpiMManagerImpl extends BaseManagerImpl<QfOperationKpiMDao, QfOperationKpiM> implements QfOperationKpiMManager {

    @Autowired
    private QfOperationKpiDManager operationKpiDManager;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importExcel(List<QfOperationKpiD> list, String mainId) {
        QfOperationKpiM qfOperationKpiM = this.baseMapper.selectById(mainId);
        Assert.notNull(qfOperationKpiM, I18nUtil.getMessage("filldata.notExist", LocaleContextHolder.getLocale()));
        Assert.isTrue(!"1".equals(qfOperationKpiM.getStatus()),  I18nUtil.getMessage("data_operate", LocaleContextHolder.getLocale()));
        QueryWrapper<QfOperationKpiD> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("main_id_", mainId);
        operationKpiDManager.remove(queryWrapper);
        List<QfOperationKpiD> newList = Lists.newArrayList();
        list.forEach(detail -> {
            if(StringUtils.isEmpty(detail.getEnterpriseCode())) {
                return;
            }

            detail.setMainId(mainId);
            detail.setFillDate(qfOperationKpiM.getFillDate());
            newList.add(detail);
        });
        boolean b = operationKpiDManager.saveBatch(newList);
        return b;
    }

    @Override
    public boolean updateStatus(QfOperationKpiM t) {
        QfOperationKpiM qfOperationKpiM = baseMapper.selectById(t.getId());
        if (null == qfOperationKpiM) {
            return false;
        }
        qfOperationKpiM.setStatus(qfOperationKpiM.getStatus() == 0 ? 1 : 0);
        int i = this.baseMapper.updateById(qfOperationKpiM);
        if (i > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertInfo(QfOperationKpiM t) {
        QueryWrapper<QfOperationKpiM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        List<QfOperationKpiM> qfOperationKpiMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(qfOperationKpiMS)) {
            throw new BaseException(I18nUtil.getMessage("QfOperationKpiM.repeat", LocaleContextHolder.getLocale()));
        }
        int insert = this.baseMapper.insert(t);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateInfo(QfOperationKpiM t) {
        QueryWrapper<QfOperationKpiM> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fill_year_", t.getFillYear());
        queryWrapper.eq("fill_month_", t.getFillMonth());
        queryWrapper.eq("report_id_", t.getReportId());
        queryWrapper.ne("id_", t.getId());
        List<QfOperationKpiM> qfOperationKpiMS = this.baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(qfOperationKpiMS)) {
            throw new BaseException(I18nUtil.getMessage("QfOperationKpiM.repeat", LocaleContextHolder.getLocale()));
        }
        int insert = this.baseMapper.updateById(t);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    @Override
    public List<FaTargetRespVo> data(ReportReqVo t) {
        //获取当前指标的年季月趋势数据
        if (null == t.getYear() || t.getYear() <= 0) {
            int year = LocalDate.now().getYear();
            t.setYear(year);
        }

        if (null == t.getStartYear() || null == t.getEndYear()) {
            t.setEndYear(t.getYear());
            t.setStartYear(t.getYear() - 5);
        }
        if(!StringUtils.isEmpty(t.getEnterpriseCode()) && "CIGR".equals(t.getEnterpriseCode())) {
            t.setEnterpriseCode(null);
        }
        //时间维度
        List<QfOperationKpiD> list = this.baseMapper.data(t);
        if (CollectionUtils.isEmpty(list)) {
            return Lists.newArrayList();
        }

        List<FaTargetRespVo> data = Lists.newArrayList();
        //计算tr转换率
        for (int i = 1; i <= 7; i++) {
            processTrAct(data, list, KpiTargetTypeEnum.getTarget(i));
        }

        return data;
    }

    private void processTrAct(List<FaTargetRespVo> data, List<QfOperationKpiD> detailList, KpiTargetTypeEnum kpiTargetTypeEnum) {
        FaTargetRespVo resultFa = new FaTargetRespVo();
        resultFa.setTargetName(kpiTargetTypeEnum.getTargetName());
        resultFa.setTargetNameEn(kpiTargetTypeEnum.getTargetNameEn());
        resultFa.setTargetUnit(kpiTargetTypeEnum.getTargetUnit());
        resultFa.setTargetId(kpiTargetTypeEnum.getTargetId());
        resultFa.setStaLat("1");
        resultFa.setType("1");

        Map<Integer, QfOperationKpiD> monthData = detailList.stream().filter(b -> !StringUtils.isEmpty(b.getFillMonth())).collect(Collectors.toMap(item -> item.getFillMonth(), item -> item));
        List<FaReportRespVo> reportRespVos = Lists.newArrayList();
        FaTargetRespVo finalResultFa = resultFa;
        List<FaReportRespVo> finalReportRespVos = reportRespVos;
        monthData.forEach((month,detail) -> {
            BigDecimal fillData = BigDecimal.ZERO;
            fillData = getFillData(kpiTargetTypeEnum, detail, fillData);
            FaReportRespVo faReportRespVo = new FaReportRespVo();
            faReportRespVo.setMonth(month);
            faReportRespVo.setActual(fillData);

            finalReportRespVos.add(faReportRespVo);
            finalResultFa.setResultData(finalReportRespVos);
        });
        data.add(resultFa);
    }

    private BigDecimal getFillData(KpiTargetTypeEnum kpiTargetTypeEnum, QfOperationKpiD detail, BigDecimal fillData) {

        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.hr_acr_act_quantity_.getType())) {
            fillData = detail.getHrAcrActQuantity();
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.tr_exfi_act_.getType())) {
            fillData = detail.getTrExfiAct();
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.oee24_ex_epdm_act_.getType())) {
            fillData = detail.getOee24ExEpdmAct();
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.crj_exfi_act_.getType())) {
            fillData = detail.getCrjExfiAct();
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.cc_exfi_act_.getType())) {
            fillData = detail.getCcExfiAct();
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.qr_ex_epdm_act_.getType())
            && null != detail.getQrExEpdmAct()) {
            fillData = new BigDecimal(100).subtract(detail.getQrExEpdmAct());
        }
        if (kpiTargetTypeEnum.getType().equals(KpiTargetTypeEnum.hr_et_rate_bud_.getType())) {
            fillData = detail.getHrEtDirAct();
        }
        if(null != fillData) {
            fillData= fillData.setScale(2, BigDecimal.ROUND_HALF_DOWN);
        }
        return fillData;
    }


    @Override
    public List<FaTargetRespVo> fromUnderData(ReportReqVo t) {
        Assert.hasText(t.getTargetId(), "请选择要统计的指标id");
        KpiTargetTypeEnum kpiTargetTypeEnum = KpiTargetTypeEnum.findByTargetId(t.getTargetId());
        List<FaTargetRespVo> resultList = Lists.newArrayList();
        //获取当前指标的年季月趋势数据
        if (null == t.getYear() || t.getYear() <= 0) {
            int year = LocalDate.now().getYear();
            t.setYear(year);
        }

        if (null == t.getStartYear() || null == t.getEndYear()) {
            t.setEndYear(t.getYear());
            t.setStartYear(t.getYear() - 10);
        }

        if (null == t.getStartQuarter() || null == t.getEndQuarter()) {
            t.setEndQuarter(4);
            t.setStartQuarter(1);
        }

        if (null == t.getStartMonth() || null == t.getEndMonth()) {
            t.setYear(t.getQuarterYear());
            t.setEndMonth(12);
            t.setStartMonth(1);
        }

        List<QfOperationKpiD> yearData = this.baseMapper.yearData(t);
        if (!CollectionUtils.isEmpty(yearData)) {
            FaTargetRespVo resultFa = new FaTargetRespVo();

            resultFa.setTargetName(kpiTargetTypeEnum.getTargetName());
            resultFa.setTargetNameEn(kpiTargetTypeEnum.getTargetNameEn());
            resultFa.setTargetUnit(kpiTargetTypeEnum.getTargetUnit());
            resultFa.setTargetId(kpiTargetTypeEnum.getTargetId());
            resultFa.setStaLat("1");
            resultFa.setType("2");
            List<FaReportRespVo> reportRespVos = Lists.newArrayList();
            yearData.forEach(detail -> {
                BigDecimal fillData = BigDecimal.ZERO;
                fillData = getFillData(kpiTargetTypeEnum, detail, fillData);

                FaReportRespVo faReportRespVo = new FaReportRespVo();
                faReportRespVo.setYear(detail.getFillYear());
                faReportRespVo.setActual(fillData);
                reportRespVos.add(faReportRespVo);
            });
            resultFa.setResultData(reportRespVos);
            resultList.add(resultFa);
        }

        List<QfOperationKpiD> quarterData = this.baseMapper.quarterData(t);
        if (!CollectionUtils.isEmpty(quarterData)) {
            FaTargetRespVo resultFa = new FaTargetRespVo();

            resultFa.setTargetName(kpiTargetTypeEnum.getTargetName());
            resultFa.setTargetNameEn(kpiTargetTypeEnum.getTargetNameEn());
            resultFa.setTargetUnit(kpiTargetTypeEnum.getTargetUnit());
            resultFa.setTargetId(kpiTargetTypeEnum.getTargetId());
            resultFa.setStaLat("1");
            resultFa.setType("3");
            List<FaReportRespVo> reportRespVos = Lists.newArrayList();
            quarterData.forEach(detail -> {
                BigDecimal fillData = BigDecimal.ZERO;
                fillData = getFillData(kpiTargetTypeEnum, detail, fillData);

                FaReportRespVo faReportRespVo = new FaReportRespVo();
                faReportRespVo.setMonth(detail.getFillMonth());
                faReportRespVo.setActual(fillData);
                reportRespVos.add(faReportRespVo);
            });
            resultFa.setResultData(reportRespVos);
            resultList.add(resultFa);
        }
        List<QfOperationKpiD> monthData = this.baseMapper.monthData(t);
        if (!CollectionUtils.isEmpty(monthData)) {
            FaTargetRespVo resultFa = new FaTargetRespVo();

            resultFa.setTargetName(kpiTargetTypeEnum.getTargetName());
            resultFa.setTargetNameEn(kpiTargetTypeEnum.getTargetNameEn());
            resultFa.setTargetUnit(kpiTargetTypeEnum.getTargetUnit());
            resultFa.setTargetId(kpiTargetTypeEnum.getTargetId());
            resultFa.setStaLat("1");
            resultFa.setType("4");
            List<FaReportRespVo> reportRespVos = Lists.newArrayList();
            monthData.forEach(detail -> {
                BigDecimal fillData = BigDecimal.ZERO;
                fillData = getFillData(kpiTargetTypeEnum, detail, fillData);

                FaReportRespVo faReportRespVo = new FaReportRespVo();
                faReportRespVo.setMonth(detail.getFillMonth());
                faReportRespVo.setActual(fillData);
                reportRespVos.add(faReportRespVo);
            });
            resultFa.setResultData(reportRespVos);
            resultList.add(resultFa);
        }
        return resultList;
    }

    @Override
    public List<FaReportRespVo> enterpriseData(ReportReqVo t) {
        Assert.hasText(t.getTargetId(), "请选择要统计的指标id");
        int year = LocalDate.now().getYear();
        t.setYear(year);
        List<QfOperationKpiD> faReportRespVos = this.baseMapper.enterpriseData(t);

        KpiTargetTypeEnum kpiTargetTypeEnum = KpiTargetTypeEnum.findByTargetId(t.getTargetId());

        if (!CollectionUtils.isEmpty(faReportRespVos)) {
            List<FaReportRespVo> reportRespVos = Lists.newArrayList();
            faReportRespVos.forEach(detail -> {
                BigDecimal fillData = BigDecimal.ZERO;
                fillData = getFillData(kpiTargetTypeEnum, detail, fillData);

                FaReportRespVo faReportRespVo = new FaReportRespVo();
                faReportRespVo.setYear(detail.getFillYear());
                faReportRespVo.setActual(fillData);
                faReportRespVo.setEnterpriseCode(detail.getEnterpriseCode());
                reportRespVos.add(faReportRespVo);
            });
            return reportRespVos;
        }

        return Lists.newArrayList();
    }

}
