package com.tofly.xrtygis.custom.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.mapper.PricePlanMapper;
import com.tofly.xrtygis.custom.service.CustomPricePlanService;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.entity.*;
import com.tofly.xrtygis.service.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 预算指标单价
 *
 * @author 陈浩
 * @date 2021/3/22
 */
@Service
@AllArgsConstructor
public class CustomPricePlanServiceImpl implements CustomPricePlanService {

    private final CostbgpriceService costbgpriceService;
    private final CostbgwaterService costbgwaterService;
    private final CostbgwateryearService costbgwateryearService;
    private final CostbgindexService costbgindexService;
    private final CostbgindexyearService costbgindexyearService;
    private final CostbgfixedService costbgfixedService;
    private final CostbgfixedyearService costbgfixedyearService;
    private final PricePlanMapper pricePlanMapper;

    /**
     * 添加计划
     *
     * @param price 预算指标单价信息
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insetPricePlan(Costbgprice price) {
        return costbgpriceService.save(price);
    }

    /**
     * 查询每年最新单价
     *
     * @param page page
     * @param year 年份
     * @return page
     */
    @Override
    public Page viewNewPlan(Page page, String year) {
        //每个年份最新单价信息
        List<Map<String, Object>> dates = pricePlanMapper.selectMaxTime();
        List<Costbgprice> pageList = new ArrayList();
        if (null != year) {
            List<Costbgprice> costbgprices = costbgpriceService.list(Wrappers.<Costbgprice>lambdaQuery()
                    .eq(Costbgprice::getYear, year)
                    .orderByDesc(Costbgprice::getCreateTime));
            if (!costbgprices.isEmpty()) {
                pageList.add(costbgprices.get(0));
            }
        } else {
            for (Map<String, Object> map : dates) {
                Costbgprice price = costbgpriceService.getOne(Wrappers.<Costbgprice>lambdaQuery()
                        .eq(Costbgprice::getYear, map.get("year"))
                        .eq(Costbgprice::getCreateTime, map.get("time")));
                pageList.add(price);
            }
        }
        return CommonMethod.listToPage(page, pageList);
    }

    /**
     * 查看历史记录信息
     *
     * @param page  page
     * @param year  年份
     * @param start 开始时间
     * @param end   结束时间
     * @return page
     */
    @Override
    public Page viewHistoryPlan(Page page, String year, String start, String end) {

        return pricePlanMapper.getPriceHistory(page, year, start, end);
    }

    /**
     * 删除计划
     *
     * @param id 计划id
     * @return true
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePlan(String id) {

        if (id == null) {
            throw new ToflyDeniedException("未传入数据");
        }

        List<Costbgprice> list = costbgpriceService.list(Wrappers.<Costbgprice>lambdaQuery().in(Costbgprice::getId, Arrays.asList(id.split(","))));

        for (Costbgprice costbgprice : list) {
            int year = Integer.parseInt(costbgprice.getYear());
            if (year < Date8Util.getYear()) {
                throw new ToflyDeniedException(costbgprice.getYear() + "年份计划已过时，不能删除");
            }
            if (year == Date8Util.getYear()) {
                if (costbgpriceService.list(Wrappers.<Costbgprice>lambdaQuery().eq(Costbgprice::getYear, year)).size() > 1) {
                    throw new ToflyDeniedException(costbgprice.getYear() + "年份计划存在历史记录，不能删除");
                }
            }
            costbgpriceService.remove(Wrappers.<Costbgprice>lambdaQuery().in(Costbgprice::getYear, year));

            Costbgfixedyear fixedYear = costbgfixedyearService.getOne(Wrappers.<Costbgfixedyear>lambdaQuery()
                    .eq(Costbgfixedyear::getYear, costbgprice.getYear()));

            if (fixedYear != null) {
                costbgfixedyearService.removeById(fixedYear.getId());
                costbgfixedService.remove(Wrappers.<Costbgfixed>lambdaQuery().eq(Costbgfixed::getYearId, fixedYear.getId()));
            }
        }
        return true;
    }

    /**
     * 修改计划
     *
     * @param costbgprice 预算指标单价信息表
     * @return true
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePlan(Costbgprice costbgprice) {
        String year = costbgpriceService.getById(costbgprice.getId()).getYear();

        if (!year.equals(costbgprice.getYear())) {
            throw new ToflyDeniedException("年份不允许修改");
        }

        //先修改单价表
        costbgpriceService.updateById(costbgprice);
        //当这三项数据被修改是执行操作
        if (costbgprice.getDlddjOne() != null || costbgprice.getDlddjTwo() != null || costbgprice.getWnzydj() != null) {
            Costbgprice price = costbgpriceService.getById(costbgprice.getId());
            //获取单变、指标、水量年份计划id
            Costbgfixedyear fixedYear = costbgfixedyearService.getOne(Wrappers.<Costbgfixedyear>lambdaQuery()
                    .eq(Costbgfixedyear::getYear, price.getYear()));
            Costbgindexyear indexYear = costbgindexyearService.getOne(Wrappers.<Costbgindexyear>lambdaQuery()
                    .eq(Costbgindexyear::getYear, price.getYear()));

            Costbgwateryear waterYear = costbgwateryearService.getOne(Wrappers.<Costbgwateryear>lambdaQuery()
                    .eq(Costbgwateryear::getYear, price.getYear()));


            if (null != fixedYear && null != indexYear && null != waterYear) {
                //查出年份计划详情
                List<Costbgfixed> fixedList = costbgfixedService.list(Wrappers.<Costbgfixed>lambdaQuery()
                        .eq(Costbgfixed::getYearId, fixedYear.getId()));
                //遍历
                fixedList.forEach(fixed -> {
                    //对应年份月份的计划详情

                    Costbgindex index = costbgindexService.getOne(Wrappers.<Costbgindex>lambdaQuery()
                            .eq(Costbgindex::getYearId, indexYear.getId()).eq(Costbgindex::getMonth, fixed.getMouth()));


                    Costbgwater water = costbgwaterService.getOne(Wrappers.<Costbgwater>lambdaQuery()
                            .eq(Costbgwater::getYearId, waterYear.getId()).eq(Costbgwater::getMonth, fixed.getMouth()));

                    Costbgfixed costbgfixed = CommonMethod.calFixedPlan(fixed, index, price, water);
                    //修改单变计划表
                    costbgfixedService.updateById(costbgfixed);

                });
            }

        }
        return true;
    }

}
