package com.nantian.cloud.jljc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.nantian.cloud.jljc.entity.TDualcontrolProgress;
import com.nantian.cloud.jljc.service.TDualcontrolProgressService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.*;

/**
 * 能耗双控-完成情况填报
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tDualcontrolProgress")
@Api(value="tDualcontrolProgress",tags = "能耗双控-完成情况填报表")
public class TDualcontrolProgressController {

    @Autowired
    private TDualcontrolProgressService progressService;

    @GetMapping("/planTime")
    @SysLog("获取五年计划时间（双控）")
    @ApiOperation(value = "获取五年计划时间", notes = "获取五年计划时间")
    public R planTime(){
        Calendar date = Calendar.getInstance();
        String year = String.valueOf(date.get(Calendar.YEAR));
        int startYear = 2020, endYear = Integer.parseInt(year);
        float tmp = (endYear-startYear) / 5f;
        int num = (int)Math.ceil(tmp); //向上取整
        List<Map<String,Object>> planTime = new ArrayList<>();
        /*for (int i = 0; i <= num; i++) {
            planTime.add((startYear+i*5+1) + "-" + (startYear+(i+1)*5));
        }*/
        for (int i = num-1, j=1; i >= 0; i--,j++) {
            Map<String,Object> map = new HashMap<>();
            map.put("value",j);
            map.put("label",(startYear+i*5+1) + "-" + (startYear+(i+1)*5));
            planTime.add(map);
        }
        return R.ok(planTime);
    }

    @PostMapping("/saveOrUpdate")
    @SysLog("填写或修改完成情况（双控）")
    @ApiOperation(value = "填写或修改完成情况", notes = "填写或修改完成情况")
    public R saveOrUpdate(@RequestBody TDualcontrolProgress progress){
        ScUser u = SecurityUtils.getUser();
        DecimalFormat df = new DecimalFormat(".00"); //保留2位小数
        progressService.saveOrUpdateProgress(progress, u, df);
        /*更新年度数据
        QueryWrapper<TDualcontrolProgress> q =new QueryWrapper<>();
        q.eq("item_code",progress.getItemCode());
        q.eq("del_flag","1");
        q.eq("year",progress.getYear());
        List<TDualcontrolProgress> progressList = progressService.list(q);
        q.eq("quarter","0");
        TDualcontrolProgress progressCount = progressService.getOne(q);
        if (progressList.size()==4 || progressCount!=null) { //四个季度数据已填 或 已有年度数据，需更新年度数据
            TDualcontrolProgress progress1 = progressService.getProgressByQuarter(progress);
            if(progressCount!=null){
                progress1.setId(progressCount.getId());
            }
            progress1.setItemStatus("2"); //年度值系统生成，不允许修改
            progressService.saveOrUpdateProgress(progress1, u, df);
        }*/
        return R.ok();
    }

    @GetMapping("/initialize")
    @SysLog("完成情况填写初始化（双控）")
    @ApiOperation(value = "完成情况填写初始化", notes = "完成情况填写初始化")
    public R initialize(TDualcontrolProgress progress) {
        Map map = new HashMap<String,Object>();
        /*if(progress.getQuarter()==null){
            progress.setQuarter("1"); //默认查询季度值
        }*/
        ScUser u = SecurityUtils.getUser();
        String deptId = u.getDeptId().toString();
        progress.setItemCode(deptId); //完成情况初始化，本级及下级数据
        List<TDualcontrolProgress> list = progressService.listByIndex(progress);
        /*合计值，只累计下级部门已提交的数据
        TDualcontrolProgress sum = progressService.sumByIndex(progress);
        if(deptId.contains("00")){ //州市或省，没有填写数据时或保存的为草稿时，返回系统计算的合计值
            if (list == null) {
                list = new ArrayList<>();
                list.add(sum);
            } else if (list.size() <= 0) {
                list.add(sum);
           // } else if (list.get(list.size()-1).getGdpTotal() == null && !list.get(list.size()-1).getItemStatus().equals("2")) { //转态不为提交时，用系统合计值
            } else if (list.get(list.size()-1).getGdpTotal() == null && !list.get(0).getItemStatus().equals("2")) { //转态不为提交时，用系统合计值
                //TDualcontrolProgress tmp = list.get(list.size()-1);
                TDualcontrolProgress tmp = list.get(0);
                if(tmp.getItemStatus().equals("0")){
                    tmp.setItemStatus("3");
                }
                tmp.setGdpTotal(sum.getGdpTotal());
                tmp.setEnergyTotal(sum.getEnergyTotal());
                //list.set(list.size()-1, tmp);
                list.set(0, tmp);
            }
        }*/
        map.put("list",list);
        map.put("quarter",progress.getQuarter());
        return R.ok(map);
    }

    /**
     * 完成进度查询，包含晴雨表、影响因素、完成进度
     * type类型，1季度，2年度，3五年计划
     */
    @GetMapping("/visualizationList")
    @SysLog("完成进度查询（双控）")
    @ApiOperation(value = "完成进度查询", notes = "完成进度查询")
    public R visualizationList(String type, String planYear, String year, String quarter, String region) throws InterruptedException {
        return R.ok(progressService.visualizationList(type,planYear,year,quarter,region));
    }

    @GetMapping("/forecast")
    @SysLog("预测功能（双控）")
    @ApiOperation(value = "预测功能", notes = "预测功能")
    public R forecastData(){
        TDualcontrolProgress q = new TDualcontrolProgress();
        q.setDelFlag("1");
        q.setItemCode(SecurityUtils.getUser().getDeptId().toString());
        List<TDualcontrolProgress> list = progressService.list(Wrappers.query(q).orderByDesc("year").orderByDesc("energy_total"));
        Calendar date = Calendar.getInstance();
        int year = date.get(Calendar.YEAR);
        int tmpYear = year%5==0 ? year-5 : year-(year%5);
        q.setQuarter("0");
        List<TDualcontrolProgress> list2 = progressService.list(Wrappers.query(q).ge("year",tmpYear+"").orderByAsc("year"));
        Map<String,Object> map = new HashMap<>();
        map.put("forecast",list);
        map.put("forecast2",list2);
        return R.ok(map);
    }
}
