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

import cn.com.victorysoft.business.indicator.dao.LessMeasureSummaryDao;
import cn.com.victorysoft.business.indicator.dao.LessSummaryDao;
import cn.com.victorysoft.business.indicator.dao.MoreMeasureSummaryDao;
import cn.com.victorysoft.business.indicator.entity.LessMeasureSummary;
import cn.com.victorysoft.business.indicator.entity.LessSummary;
import cn.com.victorysoft.business.indicator.entity.MoreMeasureSummary;
import cn.com.victorysoft.business.sys.dto.DynamicColumnData;
import cn.com.victorysoft.business.sys.entity.DateRange;
import cn.com.victorysoft.business.sys.entity.SysFlag;
import cn.com.victorysoft.business.sys.param.UnitMonthParam;
import cn.com.victorysoft.business.sys.param.UnitMonthRangeParam;
import cn.com.victorysoft.business.sys.service.SysDictService;
import cn.com.victorysoft.business.util.DateUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class LessSummaryService {

    @Resource
    private LessSummaryDao lessSummaryDao;
    @Resource
    private LessMeasureSummaryDao lessMeasureSummaryDao;
    @Resource
    private SysDictService sysDictService;

    /**
     * 参数转对象主键
     *
     * @param param
     * @return
     */
    private LessSummary parseKey(UnitMonthParam param) {
        LessSummary key = new LessSummary();
        key.setUnitcode(param.getUnitcode());
        key.setMonth(param.getMonth());
        key.setReasonId("all");
        return key;
    }

    /**
     * 查询本单位合计数据
     */
    public LessSummary selectUnitSum(UnitMonthParam param) {

        LessSummary lessSummary = lessSummaryDao.selectByPrimaryKey(this.parseKey(param));

        //去年
        UnitMonthParam lastParam = new UnitMonthParam();
        lastParam.setUnitcode(param.getUnitcode());
        String format = null;
        try {
            Date date = DateUtils.parseDate(param.getMonth() + "01", "yyyyMMdd");
            format = DateUtils.format(DateUtils.addYears(date, -1), "yyyyMM").substring(0, 4) + "12";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        lastParam.setMonth(format);
        LessSummary lastYear = lessSummaryDao.selectByPrimaryKey(this.parseKey(lastParam));

        if (lessSummary != null && lastYear != null ){
            if (lessSummary.getUnitcode().equals(lastYear.getUnitcode())) {
                lessSummary.setLastYearWell(lastYear.getWell());
                lessSummary.setLastYearSection(lastYear.getSection());
                lessSummary.setLastYearWater(lastYear.getWater());
            }
        }

        return lessSummary;
    }

    /**
     * 查询本单位数据
     */
    public List<LessSummary> selectUnit(UnitMonthParam param) {
        return lessSummaryDao.selectUnit(param);
    }

    /**
     * 查询本单位原因数据
     */
    public List<LessSummary> selectUnitReason(UnitMonthParam param) {
        List<LessSummary> list = lessSummaryDao.selectUnit(param);
        return list.stream().filter(item -> !"all".equals(item.getReasonId())).collect(Collectors.toList());
    }

    /**
     * 查询子单位合计数据
     */
    public List<LessSummary> selectChildrenSum(UnitMonthParam param) {

        List<LessSummary> lessSummaries = lessSummaryDao.selectChildrenSum(this.parseKey(param));
        //去年
        UnitMonthParam lastParam = new UnitMonthParam();
        lastParam.setUnitcode(param.getUnitcode());
        String format = null;
        try {
            Date date = DateUtils.parseDate(param.getMonth() + "01", "yyyyMMdd");
            format = DateUtils.format(DateUtils.addYears(date, -1), "yyyyMM").substring(0, 4) + "12";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        lastParam.setMonth(format);
        List<LessSummary> lastYear = lessSummaryDao.selectChildrenSum(this.parseKey(lastParam));

        if (lessSummaries.size() > 0 && lastYear.size() > 0) {
            for (int i = 0; i < lessSummaries.size(); i++) {
                for (int i1 = 0; i1 < lastYear.size(); i1++) {
                    if (lessSummaries.get(i).getUnitcode().equals(lastYear.get(i1).getUnitcode())) {
                        lessSummaries.get(i).setLastYearWell(lastYear.get(i1).getWell());
                        lessSummaries.get(i).setLastYearSection(lastYear.get(i1).getSection());
                        lessSummaries.get(i).setLastYearWater(lastYear.get(i1).getWater());
                        break;
                    }
                }
            }
        }

        return lessSummaries;
    }

    /**
     * 查询子单位数据
     */
    public List<LessSummary> selectChildren(UnitMonthParam param) {
        return lessSummaryDao.selectChildren(param);
    }

    /**
     * 查询本月和上月数据
     */
    public List<LessSummary> selectMonth2(UnitMonthParam param) {
        List<LessSummary> result = new ArrayList<>(2);
        // 本月
        LessSummary current = this.selectUnitSum(param);
        // 上月
        UnitMonthParam preParam = new UnitMonthParam();
        preParam.setUnitcode(param.getUnitcode());
        preParam.setMonth(DateUtils.getPreviousMonth(param.getMonth(), 1));
        LessSummary previous = this.selectUnitSum(preParam);
        result.add(current);
        result.add(previous);
        return result;
    }

    /**
     * 查询本月和上月数据
     */
    public List<List<LessSummary>> selectChildrenMonth2(UnitMonthParam param) {
        List<List<LessSummary>> result = new ArrayList<>(2);
        // 本月
        List<LessSummary> current = this.selectChildrenSum(param);
        // 上月
        UnitMonthParam preParam = new UnitMonthParam();
        preParam.setUnitcode(param.getUnitcode());
        preParam.setMonth(DateUtils.getPreviousMonth(param.getMonth(), 1));
        List<LessSummary> previous = this.selectChildrenSum(preParam);
        //去年
        UnitMonthParam lastParam = new UnitMonthParam();
        lastParam.setUnitcode(param.getUnitcode());
        String format = null;
        try {
            Date date = DateUtils.parseDate(param.getMonth() + "01", "yyyyMMdd");
            format = DateUtils.format(DateUtils.addYears(date, -1), "yyyyMM").substring(0, 4) + "12";
        } catch (ParseException e) {
            e.printStackTrace();
        }
        lastParam.setMonth(format);
        List<LessSummary> lastYear = this.selectChildrenSum(lastParam);

        result.add(current);
        result.add(previous);
        result.add(lastYear);
        return result;
    }

    /**
     * 查询单位范围数据
     */
    public List<LessSummary> selectRange(UnitMonthParam param, int previous) {
        UnitMonthRangeParam rangeParam = new UnitMonthRangeParam();
        rangeParam.setUnitcode(param.getUnitcode());
        rangeParam.setMonth1(DateUtils.getPreviousMonth(param.getMonth(), previous));
        rangeParam.setMonth2(param.getMonth());
        return lessSummaryDao.selectRange(rangeParam);
    }

    /**
     * 查询治理对策统计
     */
    public DynamicColumnData selectMeasure(UnitMonthParam param) {
        DynamicColumnData data = new DynamicColumnData();
        // 查询表头
        List<SysFlag> measures = sysDictService.queryDict("LESS_MEASURE");
        for (SysFlag measure : measures) {
            DynamicColumnData.Column column = new DynamicColumnData.Column(measure.getFlagCode(), measure.getFlagName());
            data.getColumnList().add(column);
        }
        DynamicColumnData.Column column = new DynamicColumnData.Column("all", "合计");
        data.getColumnList().add(column);
        // 查询统计数据
        List<LessMeasureSummary> list = lessMeasureSummaryDao.selectChildren(param);
        list.addAll(lessMeasureSummaryDao.selectUnit(param));
        for (LessMeasureSummary summary : list) {
            Optional<Map<String, Object>> optional = data.getDataList().stream().filter(map -> {
                return summary.getUnitcode().equals(map.get("unitcode"))
                        && summary.getMonth().equals(map.get("month"));
            }).findAny();
            Map<String, Object> map = optional.orElseGet(() -> {
                Map<String, Object> item = new HashMap<>();
                item.put("unitcode", summary.getUnitcode());
                item.put("unitname", summary.getUnitname());
                item.put("month", summary.getMonth());
                // 放入数据列表中
                data.getDataList().add(item);
                return item;
            });
            map.put(summary.getMeasureId() + "_WELL", summary.getWell());
            map.put(summary.getMeasureId() + "_SECTION", summary.getSection());
            map.put(summary.getMeasureId() + "_WATER", summary.getWater());
        }
        return data;
    }

    /**
     * 查询欠注原因分析
     */
    public DynamicColumnData selectReason(UnitMonthParam param) {
        DynamicColumnData data = new DynamicColumnData();
        // 查询表头
        List<SysFlag> measures = sysDictService.queryDict("LESS_REASON");
        for (SysFlag measure : measures) {
            DynamicColumnData.Column column = new DynamicColumnData.Column(measure.getFlagCode(), measure.getFlagName());
            data.getColumnList().add(column);
        }
        DynamicColumnData.Column column = new DynamicColumnData.Column("all", "合计");
        data.getColumnList().add(column);
        // 查询统计数据
        List<LessSummary> list = lessSummaryDao.selectChildren(param);
        list.addAll(lessSummaryDao.selectUnit(param));
        for (LessSummary summary : list) {
            Optional<Map<String, Object>> optional = data.getDataList().stream().filter(map -> {
                return summary.getUnitcode().equals(map.get("unitcode"))
                        && summary.getMonth().equals(map.get("month"));
            }).findAny();
            Map<String, Object> map = optional.orElseGet(() -> {
                Map<String, Object> item = new HashMap<>();
                item.put("unitcode", summary.getUnitcode());
                item.put("unitname", summary.getUnitname());
                item.put("month", summary.getMonth());
                // 放入数据列表中
                data.getDataList().add(item);
                return item;
            });
            map.put(summary.getReasonId() + "_WELL", summary.getWell());
            map.put(summary.getReasonId() + "_SECTION", summary.getSection());
            map.put(summary.getReasonId() + "_WATER", summary.getWater());
        }
        return data;
    }

    /**
     * 汇总单位数据
     */
    @Async
    @Transactional
    public void summary(String month) {
        String prevMonth = DateUtils.getPreviousMonth(month, 1);
        lessSummaryDao.deleteByMonth(month);
        lessSummaryDao.summaryStation(month, prevMonth);
        lessSummaryDao.summaryStationIncrease(month, prevMonth);
        lessSummaryDao.summaryStationReduce(month, prevMonth);
        lessSummaryDao.summaryArea(month);
        lessSummaryDao.summaryCompany(month);
        lessSummaryDao.summaryGroup(month);
    }

    /**
     * 汇总单位措施数据
     */
    @Async
    @Transactional
    public void summaryMeasure(String month) {
        lessMeasureSummaryDao.deleteByMonth(month);
        lessMeasureSummaryDao.summaryStation(month);
        lessMeasureSummaryDao.summaryArea(month);
        lessMeasureSummaryDao.summaryCompany(month);
        lessMeasureSummaryDao.summaryGroup(month);
    }
}
