package com.nantian.cloud.jljc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.TSupervisionQuotaVo;
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.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;


/**
 * 节能监察单位产品
 *
 * @since 2020-10-29
 */
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tSupervisionUnitEnergy")
@Api(value = "tSupervisionUnitEnergy", tags = "节能监察单位产品")
public class TSupervisionUnitEnergyController {

    private final TSupervisionUnitEnergyService tSupervisionUnitEnergyService;
    private final TSupervisionUnitItemService tSupervisionUnitItemService;
    private final TSupervisionUnitEnergyComprehensiveService tSupervisionUnitEnergyComprehensiveService;
    private final TSupervisionQuotaService tSupervisionQuotaService;
    private final TSupervisionUnitEnergyTaskService tSupervisionUnitEnergyTaskService;

    @GetMapping("/task")
    @SysLog("查询节能监察能耗计算任务列表")
    @ApiOperation(value = "查询节能监察能耗计算任务列表", notes = "查询节能监察能耗计算任务列表")
    @ApiImplicitParam(name = "TSupervisionUnitEnergy", value = "节能监察单位产品对象", required = false, dataType = "json", paramType = "path")
    public R selectTask(TSupervisionUnitEnergy tSupervisionUnitEnergy) {
        return R.ok(tSupervisionUnitEnergyService.selectTask(tSupervisionUnitEnergy));
    }

    /**
     * 查询全部节能监察单位产品
     */
    @GetMapping("/list")
    @SysLog("查询全部节能监察单位产品")
    @ApiOperation(value = "查询全部节能监察单位产品", notes = "查询全部节能监察单位产品")
    @ApiImplicitParam(name = "TSupervisionUnitEnergy", value = "节能监察单位产品对象", required = false, dataType = "json", paramType = "path")
    public R selectAll(TSupervisionUnitEnergy tSupervisionUnitEnergy) {
        tSupervisionUnitEnergy.setDelFlag("1"); //筛选未删除项
        tSupervisionUnitEnergy.setTce("0");     //筛选不是能耗汇总的数据
        List<TSupervisionUnitEnergy> tSupervisionUnitEnergyList = tSupervisionUnitEnergyService.list(Wrappers.query(tSupervisionUnitEnergy).orderByAsc("production_num").orderByDesc("update_time"));
        List<TSupervisionUnitEnergy> newUnitEnergyList = new ArrayList<TSupervisionUnitEnergy>();
        for (TSupervisionUnitEnergy unitEnergy : tSupervisionUnitEnergyList) {
            //设置子表数据
            TSupervisionUnitItem q = new TSupervisionUnitItem();
            q.setDelFlag("1");
            q.setUnitEnergyId(unitEnergy.getId());
            //List<TSupervisionUnitItem> itemList = tSupervisionUnitItemService.list(Wrappers.query(q));
            //itemList.stream().sorted(Comparator.comparingInt(TSupervisionUnitItem::getSortNum)); //排序
            QueryWrapper<TSupervisionUnitItem> query = Wrappers.query(q);
            query.orderByAsc("sort_num");
            List<TSupervisionUnitItem> itemList = tSupervisionUnitItemService.list(query);
            if (itemList.size() > 0) {
                unitEnergy.setUnitItemList(itemList);
            } else {
                unitEnergy.setUnitItemList(new ArrayList<>());
            }

            TSupervisionUnitEnergyComprehensive q2 = new TSupervisionUnitEnergyComprehensive();
            q2.setDelFlag("1");
            q2.setUnitEnergyId(unitEnergy.getId());
            List<TSupervisionUnitEnergyComprehensive> comprehensiveList = tSupervisionUnitEnergyComprehensiveService.list(Wrappers.query(q2));
            if (comprehensiveList.size() > 0) {
                unitEnergy.setUnitEnergyComprehensiveList(comprehensiveList);
            } else {
                unitEnergy.setUnitEnergyComprehensiveList(new ArrayList<>());
            }
            TSupervisionUnitEnergyTask q3 = new TSupervisionUnitEnergyTask();
            q3.setDelFlag("1");
            q3.setUnitEnergyId(unitEnergy.getId());
            List<TSupervisionUnitEnergyTask> unitEnergyLists = null;
            unitEnergyLists = tSupervisionUnitEnergyTaskService.list(Wrappers.query(q3));
            //查询全厂能耗
            String monitorId = tSupervisionUnitEnergy.getMonitorId();
            String[] split = monitorId.split("-");
            String s = split[split.length - 1] + split[split.length - 2];
            List<TSupervisionUnitEnergyTask> energyTask = tSupervisionUnitEnergyTaskService.list(new QueryWrapper<TSupervisionUnitEnergyTask>().eq("unit_energy_id", s).eq("del_flag", "1").orderByAsc("update_time"));
            if (energyTask.size() > 0){
                unitEnergyLists.add(energyTask.get(0));
            }
            if (unitEnergyLists.size() > 0) {
                unitEnergy.setUnitEnergyTaskList(unitEnergyLists);
            } else {
                unitEnergy.setUnitEnergyTaskList(new ArrayList<>());
            }
            newUnitEnergyList.add(unitEnergy);
        }
        return R.ok(newUnitEnergyList);
    }


    /**
     * 初始化产品种类下拉框
     */
    @GetMapping("/type")
    @SysLog("初始化产品种类下拉框")
    @ApiOperation(value = "初始化产品种类下拉框", notes = "初始化产品种类下拉框")
    @ApiImplicitParam(name = "monitorId", value = "节能监察编号", required = false, dataType = "json", paramType = "path")
    public R getType(String monitorId) {
        if (monitorId == null || "".equals(monitorId)) {
            return R.failed("节能监察编号不能为空，获取产品种类下拉框失败！");
        }
        return R.ok(tSupervisionUnitEnergyService.getType(monitorId));
    }

    /**
     * 根据id获取节能监察单位产品
     */
    @GetMapping("/getById")
    @SysLog("根据id获取节能监察单位产品")
    @ApiOperation(value = "根据id获取节能监察单位产品", notes = "根据id获取节能监察单位产品")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(Integer id) {
        TSupervisionUnitEnergy unitEnergy = tSupervisionUnitEnergyService.getById(id);
        if (unitEnergy != null) {
            TSupervisionUnitItem q = new TSupervisionUnitItem();
            q.setDelFlag("1");
            q.setUnitEnergyId(id);
            List<TSupervisionUnitItem> itemList = tSupervisionUnitItemService.list(Wrappers.query(q));
            if (itemList.size() > 0) {
                unitEnergy.setUnitItemList(itemList);
            }

            TSupervisionUnitEnergyComprehensive q2 = new TSupervisionUnitEnergyComprehensive();
            q2.setUnitEnergyId(id);
            q2.setDelFlag("1");
            List<TSupervisionUnitEnergyComprehensive> comprehensiveList = tSupervisionUnitEnergyComprehensiveService.list(Wrappers.query(q2));
            if (comprehensiveList.size() > 0) {
                unitEnergy.setUnitEnergyComprehensiveList(comprehensiveList);
            }
            return R.ok(unitEnergy);
        } else {
            return R.ok();
        }
    }

    /**
     * 保存/修改节能监察单位产品
     */
    @Transactional
    @PostMapping("saveOrUpdate")
    @SysLog("保存/修改节能监察单位产品")
    @ApiOperation(value = "保存/修改节能监察单位产品", notes = "保存/修改节能监察单位产品")
    @ApiImplicitParam(name = "TSupervisionUnitEnergy", value = "节能监察单位产品对象", required = true, dataType = "json", paramType = "path")
    public R saveOrUpdate(@RequestBody String s) {
        return R.ok(tSupervisionUnitEnergyService.saveOrUpdateByString(s));
    }

    /**
     * 删除单耗计算工序
     */
    @GetMapping("/deleteTask")
    @SysLog("删除单耗计算工序")
    public R deleteTask(TSupervisionUnitEnergyTask task){

        boolean task1 = tSupervisionUnitEnergyService.deleteTask(task);

        if (task1){
            return R.ok();
        }else {
            return R.failed();
        }

    }

    /**
     * 保存/修改节能监察单位产品(item表用文件流形式传入)
     */
    @Transactional
    @SysLog("保存/修改节能监察单位产品(item表用文件流形式传入)")
    @PostMapping("saveOrUpdateByExcel")
    @ApiOperation(value = "保存/修改节能监察单位产品(item表用文件流形式传入)", notes = "保存/修改节能监察单位产品(item表用文件流形式传入)")
    public R saveOrUpdateByExcel(@RequestParam("file") MultipartFile file, String s) throws FileFormatException {
        return R.ok(tSupervisionUnitEnergyService.saveOrUpdateByExcel(s,file));
    }

    /**
     * 批量保存/修改节能监察单位产品
     */
    @PostMapping("saveOrUpdateBatch")
    @SysLog("批量保存/修改节能监察单位产品")
    @ApiOperation(value = "批量保存/修改节能监察单位产品", notes = "批量保存/修改节能监察单位产品")
    @ApiImplicitParam(name = "data", value = "节能监察单位产品对象", required = true, dataType = "json", paramType = "path")
    public R saveOrUpdateBatch(@RequestBody String s) {
        JSONObject json = JSONObject.parseObject(s);
        String para = json.getString("data");
        List<TSupervisionUnitEnergy> tSupervisionUnitEnergyList = (List<TSupervisionUnitEnergy>) JSONArray.parseArray(para, TSupervisionUnitEnergy.class);
        List<TSupervisionUnitEnergy> newList = new ArrayList<>();
        for (TSupervisionUnitEnergy tSupervisionUnitEnergy : tSupervisionUnitEnergyList) {
            ScUser u = SecurityUtils.getUser();
            tSupervisionUnitEnergy.setUserid(u.getId());
            tSupervisionUnitEnergy.setUpdateTime(new Date());
            //hasOld( tSupervisionUnitEnergy, u);
            if (tSupervisionUnitEnergy.getId() == null) { //新增
                tSupervisionUnitEnergy.setDelFlag("1");
                tSupervisionUnitEnergy.setDeptId(u.getDeptId());
            }
            newList.add(tSupervisionUnitEnergy);
        }
        return R.ok(tSupervisionUnitEnergyService.saveOrUpdateBatch(newList));
    }


    private void hasOld(TSupervisionUnitEnergy tSupervisionUnitEnergy, ScUser u) {
        TSupervisionUnitEnergy old = new TSupervisionUnitEnergy();
        //old.setEpc(tSupervisionUnitEnergy.getEpc());
        old.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
        TSupervisionUnitEnergy o = tSupervisionUnitEnergyService.getOne(Wrappers.query(old));
        if (o != null) { //有历史数据，属于修改
            tSupervisionUnitEnergy.setId(o.getId());
        } else {
            tSupervisionUnitEnergy.setDelFlag("1");
            tSupervisionUnitEnergy.setDeptId(u.getDeptId());
        }
    }


    /**
     * 根据id删除节能监察单位产品
     */
    @GetMapping("/delete")
    @SysLog("根据id删除节能监察单位产品")
    @ApiOperation(value = "根据id删除节能监察单位产品", notes = "根据id删除节能监察单位产品")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R delete(Integer id) {
        TSupervisionUnitEnergy tSupervisionUnitEnergy = tSupervisionUnitEnergyService.getById(id);
        if (tSupervisionUnitEnergy == null) {
            return R.failed("id不存在，删除节能监察单位产品失败！");
        }
        ScUser u = SecurityUtils.getUser();
        tSupervisionUnitEnergy.setUpdateTime(new Date());
        tSupervisionUnitEnergy.setDelFlag("4");
        tSupervisionUnitEnergy.setUserid(u.getId());
        return R.ok(tSupervisionUnitEnergyService.updateById(tSupervisionUnitEnergy));
    }
}
