package cn.com.victorysoft.business.indicator.service;

import cn.com.victorysoft.business.indicator.constant.Constants;
import cn.com.victorysoft.business.indicator.dao.WellSectionMonthDao;
import cn.com.victorysoft.business.indicator.dto.MeasureCompareDto;
import cn.com.victorysoft.business.indicator.entity.SectionRateSummary;
import cn.com.victorysoft.business.indicator.entity.UnitApproveThreshold;
import cn.com.victorysoft.business.indicator.entity.WellSectionMonth;
import cn.com.victorysoft.business.indicator.param.WellSectionMonthParam;
import cn.com.victorysoft.business.sys.entity.WellBasic;
import cn.com.victorysoft.business.sys.service.SysBaseService;
import cn.com.victorysoft.business.util.PageUtils;
import cn.com.victorysoft.business.util.StringUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static cn.com.victorysoft.business.indicator.constant.Constants.*;

@Service
public class WellSectionMonthService {

    @Resource
    private WellSectionMonthDao wellSectionMonthDao;
    @Resource
    private SectionRateSummaryService sectionRateSummaryService;
    @Resource
    private LessSummaryService lessSummaryService;
    @Resource
    private MoreSummaryService moreSummaryService;
    @Resource
    private SysBaseService sysBaseService;
    @Resource
    private UnitApproveThresholdService unitApproveThresholdService;

    public int insert(WellSectionMonth record) {
        return wellSectionMonthDao.insert(record);
    }

    public WellSectionMonth selectByPrimaryKey(WellSectionMonth key) {
        return wellSectionMonthDao.selectByPrimaryKey(key);
    }

    /**
     * 更新维护数据
     */
    public int updateEdit(WellSectionMonth record) {
        WellSectionMonth originRecord = this.selectByPrimaryKey(record);
        // 如果修改的评价结果变化，设置为待审核
        if (StringUtils.isNotEmpty(record.getEvaluateEdit()) && !record.getEvaluateEdit().equals(originRecord.getEvaluate())) {
            record.setApproved("0");
        }
        // 更新
        int result = wellSectionMonthDao.updateByPrimaryKeySelective(record);
        String month = record.getMonth();
        // 如果原因变化，只重新统计原因
        if (Constants.MORE.equals(originRecord.getEvaluate()) &&
                StringUtils.isNotEmpty(record.getReasonId()) && !record.getReasonId().equals(originRecord.getReasonId())) {
            moreSummaryService.summary(month);
        }
        if (Constants.LESS.equals(originRecord.getEvaluate()) &&
                StringUtils.isNotEmpty(record.getReasonId()) && !record.getReasonId().equals(originRecord.getReasonId())) {
            lessSummaryService.summary(month);
        }
        // 如果措施或是否实施变化，只重新统计措施
        if (Constants.MORE.equals(originRecord.getEvaluate()) &&
                ((record.getApply() != null && record.getApply() &&
                        StringUtils.isNotEmpty(record.getMeasureId()) &&
                        !record.getMeasureId().equals(originRecord.getMeasureId()))
                        || (record.getApply() != null && !record.getApply().equals(originRecord.getApply())))) {
            moreSummaryService.summaryMeasure(month);
        }
        if (Constants.LESS.equals(originRecord.getEvaluate()) &&
                ((record.getApply() != null && record.getApply() &&
                        StringUtils.isNotEmpty(record.getMeasureId()) &&
                        !record.getMeasureId().equals(originRecord.getMeasureId()))
                        || (record.getApply() != null && !record.getApply().equals(originRecord.getApply())))) {
            lessSummaryService.summaryMeasure(month);
        }
        return result;
    }

    /**
     * 审核
     */
    public String updateApprove(WellSectionMonth param) {
        // 批量审批
        List<WellSectionMonth> list = new ArrayList<>();
        String[] wellnameList = param.getWellname().split(",");
        String[] monthList = param.getMonth().split(",");
        String[] sectionList = param.getSections().split(",");
        for (int i = 0; i < wellnameList.length; i++) {
            WellSectionMonth entity = new WellSectionMonth();
            entity.setWellname(wellnameList[i]);
            entity.setMonth(monthList[i]);
            entity.setSection(Integer.valueOf(sectionList[i]));
            list.add(entity);
        }

        // 审核通过
        if ("1".equals(param.getApproved())) {
            // 审核限制，默认2%（检查层总层 正常和正常边底水驱）
            String month = list.get(0).getMonth();
            WellBasic wellBasic0 = sysBaseService.selectWellBasic(list.get(0).getWellname());
            String companyCode = wellBasic0.getCompanycode();
            UnitApproveThreshold threshold = unitApproveThresholdService.selectByCompany(companyCode);
            BigDecimal maxRate = threshold != null ? threshold.getThreshold() : new BigDecimal("0.02");
            // 已审批数量
            int approved = wellSectionMonthDao.countApproved(companyCode, month);
            // 检查层总层 正常和正常边底水驱
            WellSectionMonthParam summaryParam = new WellSectionMonthParam();
            summaryParam.setMonth(month);
            summaryParam.setMonth1(month);
            summaryParam.setMonth2(month);
            summaryParam.setUnitcode(companyCode);
            summaryParam.setWellTypes(Arrays.asList("1", "3"));
            List<SectionRateSummary> summaryList = sectionRateSummaryService.selectUnitChildren(summaryParam);
            SectionRateSummary summary = summaryList.stream().filter(item -> item.getUnitcode().equals(companyCode)).findFirst().orElse(null);
            if (summary != null && summary.getCheckSection() != null && summary.getCheckSection() > 0) {
                int checkSection = summary.getCheckSection();
                // (已审批层数+待审批层数)/检查层数
                BigDecimal approveRate = new BigDecimal(approved + list.size()).divide(new BigDecimal(checkSection), 2, RoundingMode.HALF_UP);
                if (approveRate.compareTo(maxRate) > 0) {
                    return "检查层数："+checkSection+"，已审核层数："+approved+"，新增审核层数："+list.size()+
                            "，审核层数超出限制" + (maxRate.multiply(new BigDecimal(100))) + "%，禁止审核通过";
                }
            }

            for (WellSectionMonth record : list) {
                record.setApproved(param.getApproved());
                WellSectionMonth originRecord = this.selectByPrimaryKey(record);
                // 存储原来计算结果
                record.setEvaluateCalc(originRecord.getEvaluate());
                // 更新评价结果
                record.setEvaluate(originRecord.getEvaluateEdit());
                // 欠注类型
                if (LESS.equals(record.getEvaluate())) {
                    if (originRecord.getNozzle() != null && originRecord.getNozzle().contains("控制")) {
                        record.setLessType(LESS_TYPE_NOZZLE);
                    }
                    // 除了带嘴欠注，都是放大
                    else {
                        record.setLessType(LESS_TYPE_BIG);
                    }
                }
                // 更新
                wellSectionMonthDao.updateByPrimaryKeySelective(record);
                // 如果评价结果变化，全部重新统计
                if (StringUtils.isNotEmpty(record.getEvaluate()) && !record.getEvaluate().equals(originRecord.getEvaluate())) {
                    sectionRateSummaryService.summary(month);
                    lessSummaryService.summary(month);
                    lessSummaryService.summaryMeasure(month);
                    moreSummaryService.summary(month);
                    moreSummaryService.summaryMeasure(month);
                }
            }
        }
        // 审批拒绝
        else if ("2".equals(param.getApproved())) {
            for (WellSectionMonth record : list) {
                record.setApproved(param.getApproved());
                // 更新
                wellSectionMonthDao.updateByPrimaryKeySelective(record);
            }
        }
        return null;
    }

    public PageInfo<WellSectionMonth> selectPage(WellSectionMonthParam param) {
        setColumnNames(param);
        PageUtils.startPage(param);
        return new PageInfo<>(wellSectionMonthDao.selectList(param));
    }

    public List<WellSectionMonth> selectList(WellSectionMonthParam param) {
        setColumnNames(param);
        return wellSectionMonthDao.selectList(param);
    }

    public PageInfo<MeasureCompareDto> pageMeasureCompare(WellSectionMonthParam param) {
        PageUtils.startPage(param);
        // 只查询已实施措施的
        param.setApply(true);
        List<WellSectionMonth> beforeList = this.selectList(param);
        PageInfo<WellSectionMonth> pageInfo = new PageInfo<>(beforeList);
        PageInfo<MeasureCompareDto> result = PageUtils.pageInfo2DTOExcludeList(pageInfo, MeasureCompareDto.class);
        List<MeasureCompareDto> list = beforeList.stream().map(item -> {
            MeasureCompareDto dto = new MeasureCompareDto();
            dto.setBefore(item);
            return dto;
        }).collect(Collectors.toList());
        // 查询治理后数据
        this.setMeasureAfter(list);
        result.setList(list);
        return result;
    }

    public List<MeasureCompareDto> selectMeasureCompare(WellSectionMonthParam param) {
        // 只查询已实施措施的
        param.setApply(true);
        List<WellSectionMonth> beforeList = this.selectList(param);
        List<MeasureCompareDto> list = beforeList.stream().map(item -> {
            MeasureCompareDto dto = new MeasureCompareDto();
            dto.setBefore(item);
            return dto;
        }).collect(Collectors.toList());
        // 查询治理后数据
        this.setMeasureAfter(list);
        return list;
    }

    private void setColumnNames(WellSectionMonthParam param) {
        String[] unitColumn = sysBaseService.getUnitColumns(param.getUnitcode());
        param.setSearchUnitColumn(unitColumn[0]);
        param.setUnitColumn(unitColumn[1]);
    }

    private void setMeasureAfter(List<MeasureCompareDto> list) {
        if (list.size() > 0) {
            List<WellSectionMonth> nextList = wellSectionMonthDao.selectNextMonthList(list);
            for (MeasureCompareDto dto : list) {
                Optional<WellSectionMonth> optional = nextList.stream().filter(dto::matchNextMonth).findAny();
                optional.ifPresent(dto::setAfter);
            }
        }
    }

}
