package com.nantian.cloud.jljc.service.impl;

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.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.mapper.TSupervisionUnitEnergyMapper;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.TSupervisionQuotaVo;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 节能监察单位产品 服务实现类
 * @since 2020-10-29
 */
@Slf4j
@Service("tSupervisionUnitEnergyService")
public class TSupervisionUnitEnergyServiceImpl extends ServiceImpl<TSupervisionUnitEnergyMapper, TSupervisionUnitEnergy> implements TSupervisionUnitEnergyService {

    @Autowired
    private TSupervisionUnitItemService tSupervisionUnitItemService;
    @Autowired
    private TSupervisionUnitEnergyComprehensiveService tSupervisionUnitEnergyComprehensiveService;
    @Autowired
    private TSupervisionQuotaService tSupervisionQuotaService;
    @Autowired
    private TSupervisionUnitEnergyTaskService tSupervisionUnitEnergyTaskService;

    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    @Override
    public List<String> getType(String monitorId) {
        return baseMapper.getType(monitorId);
    }

    @Override
    public boolean saveOrUpdateByString(String s) {
        JSONObject json = JSONObject.parseObject(s);
        ScUser u = SecurityUtils.getUser();

        //主表 节能监察单位产品
        String para = json.getString("unitEnergy");
        TSupervisionUnitEnergy tSupervisionUnitEnergy = (TSupervisionUnitEnergy) JSONArray.parseObject(para, TSupervisionUnitEnergy.class);
        boolean b = saveUnitEnergy(tSupervisionUnitEnergy, u);

        //子表  节能监察单位产品项目
        saveUnitItem(json, u, tSupervisionUnitEnergy, b);
        //子表  节能监察单位产品综合能耗
        saveUnitComprehensive(json, u, tSupervisionUnitEnergy, b);
        //子表  节能监察单位产品任务列表
        saveUnitTask(json, u, tSupervisionUnitEnergy, b);
        return b;
    }

    @Override
    public boolean saveOrUpdateByExcel(String s, MultipartFile file) throws FileFormatException {
        JSONObject json = JSONObject.parseObject(s);
        ScUser u = SecurityUtils.getUser();

        //主表 节能监察单位产品
        String para = json.getString("unitEnergy");
        TSupervisionUnitEnergy tSupervisionUnitEnergy = (TSupervisionUnitEnergy) JSONArray.parseObject(para, TSupervisionUnitEnergy.class);
        boolean b = saveUnitEnergy(tSupervisionUnitEnergy, u);

        //子表  节能监察单位产品项目
        saveUnitItemByExcel(file, u, tSupervisionUnitEnergy, b);
        //子表  节能监察单位产品综合能耗
        saveUnitComprehensive(json, u, tSupervisionUnitEnergy, b);
        //子表  节能监察单位产品任务列表
        saveUnitTask(json, u, tSupervisionUnitEnergy, b);
        return b;
    }

    @Override
    public boolean deleteTask(TSupervisionUnitEnergyTask task) {

        String year = task.getYear();
        String monitorId = task.getMonitorId();
        Integer unitEnergyId = task.getUnitEnergyId();
        Integer id = task.getId();
        String code = task.getCodes();

        boolean taskB = false, energy = false, item = false, unit = false;

        //1.数据删除
        List<TSupervisionUnitEnergyTask> energyTask = tSupervisionUnitEnergyTaskService.list(new QueryWrapper<TSupervisionUnitEnergyTask>().eq("id", id));
        energyTask.forEach(e -> {
            e.setDelFlag("4");
        });
        taskB = tSupervisionUnitEnergyTaskService.updateBatchById(energyTask);// 删除t_supervision_unit_energy_task表中的数据

        List<TSupervisionUnitEnergyComprehensive> list = tSupervisionUnitEnergyComprehensiveService
                .list(new QueryWrapper<TSupervisionUnitEnergyComprehensive>().eq("unit_energy_id", unitEnergyId).eq("del_flag", "1"));
        if(list!=null && list.size()>0){
            list.forEach(l -> {
                l.setDelFlag("4");
            });
            energy = tSupervisionUnitEnergyComprehensiveService.updateBatchById(list);//删除t_supervision_unit_item中的数据
        }

        List<TSupervisionUnitItem> itemList = tSupervisionUnitItemService.list(new QueryWrapper<TSupervisionUnitItem>().eq("del_flag", "1")
                .eq("unit_energy_id", unitEnergyId).eq("codes", code));
        if(itemList!=null && itemList.size()>0){
            itemList.forEach(l -> {
                l.setDelFlag("4");
            });
            item = tSupervisionUnitItemService.updateBatchById(itemList);
        }

        List<TSupervisionUnitEnergy> unitEnergies = this.list(new QueryWrapper<TSupervisionUnitEnergy>()
                .eq("year", year).eq("monitor_id", monitorId).eq("code", code).eq("del_flag", "1").eq("id", unitEnergyId));
        if(unitEnergies!=null && unitEnergies.size()>0){
            unitEnergies.forEach(u -> {
                u.setDelFlag("4");
            });
            unit = this.updateBatchById(unitEnergies);
        }

        //2.正常数据 pid移位
        Integer pid = task.getPid();
        List<TSupervisionUnitEnergy> energies = new ArrayList<>();
        List<TSupervisionUnitEnergyTask> energyTasks = tSupervisionUnitEnergyTaskService.list(new QueryWrapper<TSupervisionUnitEnergyTask>()
                .eq("year", year).eq("del_flag", "1").eq("monitor_id", monitorId).orderByAsc("pid"));
        for (int i = 0; i < energyTasks.size(); i++) {
            TSupervisionUnitEnergyTask unitEnergyTask = energyTasks.get(i);
            if (pid < unitEnergyTask.getPid()){
                unitEnergyTask.setPid(unitEnergyTask.getPid() - 1); //计算任务表pid移位
                TSupervisionUnitEnergy unitEnergy = baseMapper.selectById(unitEnergyTask.getUnitEnergyId());
                if(unitEnergy!=null){
                    unitEnergy.setProductionNum(unitEnergyTask.getPid()); //单耗计算表productionNum移位
                    energies.add(unitEnergy);
                }
            }
        }
        tSupervisionUnitEnergyTaskService.updateBatchById(energyTasks);
        this.updateBatchById(energies);

        return taskB;
    }

    @Override
    public List<TSupervisionUnitEnergy> initializeUnitEnergyList(TSupervisionUnitEnergy tSupervisionUnitEnergy) {
        List<TSupervisionUnitEnergy> unitEnergyList = baseMapper.initializeByMonitor(tSupervisionUnitEnergy.getMonitorId(),tSupervisionUnitEnergy.getLineNumber());
        if(unitEnergyList==null || unitEnergyList.size()==0){
            unitEnergyList = baseMapper.initializeByIndustry(tSupervisionUnitEnergy.getMonitorId());
        }
        return unitEnergyList;
    }

    @Override
    public List<TSupervisionUnitEnergyTask> selectTask(TSupervisionUnitEnergy tSupervisionUnitEnergy) {
        List<TSupervisionUnitEnergyTask> newTask = new ArrayList<>();

        //查询能耗计算任务列表
        List<TSupervisionUnitEnergyTask> taskList = baseMapper.selectTaskByMonitor(tSupervisionUnitEnergy);
        //taskList.size()为1，只有综合能耗计算表，需要初始化
        if(taskList==null || taskList.size()==1){ //按照以往监察数据进行初始化
            taskList = baseMapper.initializeTaskByMonitor(tSupervisionUnitEnergy);
        }
        if(taskList==null || taskList.size()==1){ //按照行业进行初始化
            taskList = baseMapper.initializeTaskByIndustry(tSupervisionUnitEnergy);
        }

        if(taskList==null || taskList.size()==1){ //初始化
            newTask.add(new TSupervisionUnitEnergyTask(1, "未完成", "false", "0", "综合能耗计算", "", "全厂", tSupervisionUnitEnergy.getMonitorId(), tSupervisionUnitEnergy.getYear()));
            newTask.add(new TSupervisionUnitEnergyTask(2, "未完成", "true", "0", "单位产品综合能耗计算", "", "", tSupervisionUnitEnergy.getMonitorId(), tSupervisionUnitEnergy.getYear()));
        }else{
            for (int i = 0; i < taskList.size(); i++) {
                TSupervisionUnitEnergyTask task = taskList.get(i);
                if(i==1){
                    task.setStatus2("true");
                }else{
                    task.setStatus2("false");
                }
                if(task.getPid() == 0){
                    task.setPid(i+1);
                }
                if(task.getId()==null || task.getId()==0){ //初始化数据存入数据库
                    baseMapper.saveTask(task);
                }
                newTask.add(task);
            }
        }
        return newTask;
    }

    //主表 节能监察单位产品
    private boolean saveUnitEnergy(TSupervisionUnitEnergy tSupervisionUnitEnergy, ScUser u) {
        tSupervisionUnitEnergy.setUserid(u.getId());
        tSupervisionUnitEnergy.setUpdateTime(new Date());
        if (StringUtils.isBlank(tSupervisionUnitEnergy.getDelFlag())){
            tSupervisionUnitEnergy.setDelFlag("1");
        }
        tSupervisionUnitEnergy.setDeptId(u.getDeptId());
        tSupervisionUnitEnergy.setTce("0");  //不是能耗汇总
        return this.saveOrUpdate(tSupervisionUnitEnergy);
    }

    //子表  节能监察单位产品项目
    private void saveUnitItem(JSONObject json, ScUser u, TSupervisionUnitEnergy tSupervisionUnitEnergy, boolean b) {
        //取出限额标准
        TSupervisionQuota q = new TSupervisionQuota();
        q.setCode(tSupervisionUnitEnergy.getCode());
        TSupervisionQuota quota = tSupervisionQuotaService.getOne(Wrappers.query(q));
        List<TSupervisionQuotaVo> quotaVos = new ArrayList<TSupervisionQuotaVo>();
        if(quota!=null) {
            if ("1".equals(tSupervisionUnitEnergy.getEvaluationCriteria())) { //评定标准 1限定值
                if (quota.getLimits() != null && !"".equals(quota.getLimits())) {
                    quotaVos = (List<TSupervisionQuotaVo>) JSONArray.parseArray(quota.getLimits(), TSupervisionQuotaVo.class);
                }
            } else if ("2".equals(tSupervisionUnitEnergy.getEvaluationCriteria())) { //评定标准 2准入值
                if (quota.getAccess() != null && !"".equals(quota.getAccess())) {
                    quotaVos = (List<TSupervisionQuotaVo>) JSONArray.parseArray(quota.getAccess(), TSupervisionQuotaVo.class);
                }
            } else if ("3".equals(tSupervisionUnitEnergy.getEvaluationCriteria())) { //评定标准 3先进值
                if (quota.getAdvance() != null && !"".equals(quota.getAdvance())) {
                    quotaVos = (List<TSupervisionQuotaVo>) JSONArray.parseArray(quota.getAdvance(), TSupervisionQuotaVo.class);
                }
            }
        }

        //子表  节能监察单位产品项目
        String unitItem = json.getString("unitItem");
        if (unitItem != null && !"".equals(unitItem)) {
            List<TSupervisionUnitItem> unitItemList = (List<TSupervisionUnitItem>) JSONObject.parseArray(unitItem, TSupervisionUnitItem.class);
            List<TSupervisionUnitItem> newItemList = new ArrayList<>();
            List<TSupervisionUnitEnergy> newEnergyList = new ArrayList<>();
            for (TSupervisionUnitItem item : unitItemList) {
                item.setDelFlag("1");
                item.setUserid(u.getId());
                item.setDeptId(u.getDeptId());
                item.setUpdateTime(new Date());
//                item.setSortNum(item.getId());
                if (b) {
                    item.setUnitEnergyId(tSupervisionUnitEnergy.getId());
                }
                newItemList.add(item);

                if ("1".equals(item.getTce())) { //是能耗汇总，数据要放到主表
                    TSupervisionUnitEnergy unitEnergy = new TSupervisionUnitEnergy();
                    if(quotaVos.size()>0) {
                        for (TSupervisionQuotaVo quotaVo : quotaVos) {
                            //产品名称包含指标名称  或   指标名称包含产品符号
                            //if (item.getProductName().contains(quotaVo.getCol0()) || quotaVo.getCol0().contains(item.getCode())) {
                            if (item.getProductName().contains(quotaVo.getCol0()) || quotaVo.getCol0().contains(item.getOldCode())) {
                                unitEnergy.setUnitProductLimitStandard(quotaVo.getCol2()); //设置单位产品综合能耗限额标准
                                unitEnergy.setUnitProductLimitUnit(quotaVo.getCol3()); //设置单位产品综合能耗限额单位
                            }
                        }
                    }
                    TSupervisionUnitEnergy q1 = new TSupervisionUnitEnergy();
                    q1.setPid(tSupervisionUnitEnergy.getId());
                    q1.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
                    q1.setProductName(item.getProductName());
                    q1.setYear(tSupervisionUnitEnergy.getYear());
                    q1.setProcess(tSupervisionUnitEnergy.getProcess());
                    //q1.setLineNumber(tSupervisionUnitEnergy.getLineNumber());
                    //q1.setTaskName(tSupervisionUnitEnergy.getTaskName());
                    //q1.setElectrolyzerSpecifications(tSupervisionUnitEnergy.getElectrolyzerSpecifications());
                    q1.setDelFlag("1");
                    q1.setTce("1");
                    TSupervisionUnitEnergy old = this.getOne(Wrappers.query(q1));
                    if (old != null) {
                        unitEnergy.setId(old.getId()); //有历史数据为修改
                    }
                    unitEnergy.setPid(tSupervisionUnitEnergy.getId());
                    unitEnergy.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
                    unitEnergy.setYear(tSupervisionUnitEnergy.getYear());
                    unitEnergy.setProcess(tSupervisionUnitEnergy.getProcess());
                    unitEnergy.setLineNumber(tSupervisionUnitEnergy.getLineNumber());
                    unitEnergy.setElectrolyzerSpecifications(tSupervisionUnitEnergy.getElectrolyzerSpecifications());
                    unitEnergy.setSymbol(item.getCode());  //符号
                    unitEnergy.setOldCode(item.getOldCode());  //符号
                    unitEnergy.setProductName(item.getProductName()); // 名称
                    unitEnergy.setUnit(item.getUnit()); //单位
                    unitEnergy.setProduction(item.getProduction()); //数量
                    unitEnergy.setCalculationResults(item.getCalculationResults()); //计算结果
                    unitEnergy.setCode(item.getCodes());  //特征码
                    unitEnergy.setUserid(u.getId());
                    unitEnergy.setUpdateTime(new Date());
                    if (StringUtils.isBlank(item.getDelFlag())){
                        unitEnergy.setDelFlag("1");
                    }else {
                        unitEnergy.setDelFlag(item.getDelFlag());
                    }
                    unitEnergy.setDeptId(u.getDeptId());
                    unitEnergy.setTce("1");  //是能耗汇总
                    newEnergyList.add(unitEnergy);
                }
            }
            if (newItemList.size() > 0) {
                List<TSupervisionUnitItem> list = tSupervisionUnitItemService.list(new QueryWrapper<TSupervisionUnitItem>().eq("unit_energy_id", tSupervisionUnitEnergy.getId()));
                List<TSupervisionUnitItem> tempList = new ArrayList<>();
                tempList.addAll(newItemList);
                list.forEach(l -> {
                    boolean flag = true;
                    for (int i = 0; i < tempList.size(); i++) {
                        if (l.getProductName().equals(tempList.get(i).getProductName())){
                            flag = false;
                        }
                    }
                    if (flag){
                        l.setDelFlag("4");
                        l.setUpdateTime(new Date());
                        l.setUserid(u.getId());
                        newItemList.add(l);
                    }
                });
                tSupervisionUnitItemService.saveOrUpdateBatch(newItemList);
            }
            if (newEnergyList.size() > 0) {
                this.saveOrUpdateBatch(newEnergyList);
            }
        }
    }

    //子表  节能监察单位产品项目(通过excel导入)
    private void saveUnitItemByExcel(MultipartFile file, ScUser u, TSupervisionUnitEnergy tSupervisionUnitEnergy, boolean b)  throws FileFormatException {

        if (file == null) {
            throw new FileFormatException("导入失败，传入文件不存在！");
        }

        //获取原文件
        String originalFileName = file.getOriginalFilename();

        //判断传入文件格式
        if (!(originalFileName.endsWith(EXTENSION_XLS) || originalFileName.endsWith(EXTENSION_XLSX))) {
            throw new FileFormatException("传入文件不是excel格式!");
        }
        Workbook workbook = null;
        try {
            if (originalFileName.endsWith(EXTENSION_XLS)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFileName.endsWith(EXTENSION_XLSX)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }

            List<TSupervisionUnitItem> newItemList = new ArrayList<>();
            List<TSupervisionUnitEnergy> newEnergyList = new ArrayList<>();

            //读文件
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(numSheet);
                if (sheet == null) {
                    continue;
                }
                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();
                //读取首行（表头）
                Row firstRow = sheet.getRow(firstRowIndex);
                for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
                    Cell cell = firstRow.getCell(i);
                    String cellValue = this.getCellValue(cell, true);
                    System.out.println("表头数据：" + cellValue + "\t");
                }

                System.out.println("开始导入数据...");
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    int firstColumnIndex = currentRow.getFirstCellNum(); //首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列
                    boolean s = false;

                    TSupervisionUnitItem item = new TSupervisionUnitItem();
                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);
                        System.out.println(" " + currentCellValue + "\t");
                        /*if (columnIndex == firstColumnIndex) {
                            recordPersonManager.setEpc(currentCellValue);
                        }*/
                        if (columnIndex == firstColumnIndex ) { //项目名称
                            item.setProductName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 1) { //符号(下标)
                            item.setCode(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) { //单位
                            item.setUnit(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) { //数量
                            item.setProduction(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4) { //折标系数
                            item.setRefModulus(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) { //计量结果
                            item.setCalculationResults(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6) { //能耗汇总标记（0不是汇总数据，1单位产品能耗，2产量/消耗量等）
                            item.setTce(currentCellValue);

                            if ("1".equals(currentCellValue)) { //是能耗汇总，数据要放到主表
                                TSupervisionUnitEnergy unitEnergy = new TSupervisionUnitEnergy();
                                TSupervisionUnitEnergy q1 = new TSupervisionUnitEnergy();
                                q1.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
                                q1.setProductName(item.getProductName());
                                q1.setDelFlag("1");
                                q1.setTce("1");
                                TSupervisionUnitEnergy old = this.getOne(Wrappers.query(q1));
                                if (old != null) {
                                    unitEnergy.setId(old.getId()); //有历史数据为修改
                                }
                                unitEnergy.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
                                unitEnergy.setSymbol(item.getCode());  //符号
                                unitEnergy.setOldCode(item.getOldCode());  //符号
                                unitEnergy.setProductName(item.getProductName()); // 名称
                                unitEnergy.setUnit(item.getUnit()); //单位
                                unitEnergy.setProduction(item.getProduction()); //数量
                                unitEnergy.setCalculationResults(item.getCalculationResults()); //计算结果
                                unitEnergy.setCode(tSupervisionUnitEnergy.getCode());  //特征码
                                unitEnergy.setUserid(u.getId());
                                unitEnergy.setUpdateTime(new Date());
                                unitEnergy.setDelFlag("1");
                                unitEnergy.setDeptId(u.getDeptId());
                                unitEnergy.setTce("1");  //是能耗汇总
                                newEnergyList.add(unitEnergy);
                            }

                        }

                        item.setCodes(tSupervisionUnitEnergy.getCode()); //特征码
                        item.setDelFlag("1");
                        item.setUserid(u.getId());
                        item.setDeptId(u.getDeptId());
                        item.setUpdateTime(new Date());
                        if (b) {
                            item.setUnitEnergyId(tSupervisionUnitEnergy.getId());
                        }

                    }
                    newItemList.add(item);
                }
            }

            if (newItemList.size() > 0) {
                tSupervisionUnitItemService.saveOrUpdateBatch(newItemList);
            }
            if (newEnergyList.size() > 0) {
                this.saveOrUpdateBatch(newEnergyList);
            }
            System.out.println("导入成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            System.err.println("导入失败！" + e.getMessage());
        } finally {
            if (workbook != null) {
                try {
                    file.getInputStream().close();
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //子表  节能监察单位产品任务列表
    private void saveUnitTask(JSONObject json, ScUser u, TSupervisionUnitEnergy tSupervisionUnitEnergy, boolean b) {
        String unitEnergyTask = json.getString("unitEnergyTask");
        if (unitEnergyTask != null && !"".equals(unitEnergyTask)) {
            List<TSupervisionUnitEnergyTask> taskList = (List<TSupervisionUnitEnergyTask>) JSONObject.parseArray(unitEnergyTask, TSupervisionUnitEnergyTask.class);
            List<TSupervisionUnitEnergyTask> newTaskList = new ArrayList<>();
            for (int i = 0; i < taskList.size(); i++) {
                TSupervisionUnitEnergyTask task = taskList.get(i);
                task.setMonitorId(tSupervisionUnitEnergy.getMonitorId());
                task.setUserid(u.getId());
                task.setDeptId(u.getDeptId());
                task.setUpdateTime(new Date());
                if (StringUtils.isBlank(task.getDelFlag())){
                    task.setDelFlag("1");
                }
                if(StringUtils.isBlank(task.getYear())){
                    task.setYear(tSupervisionUnitEnergy.getYear());
                }
                if(tSupervisionUnitEnergy.getYear().equals(task.getYear()) && tSupervisionUnitEnergy.getTaskName().equals(task.getProcessName())){
                    task.setUnitEnergyId(tSupervisionUnitEnergy.getId());
                    task.setStatus("已完成");
                    if(StringUtils.isBlank(task.getProcess())){
                        task.setProcess(tSupervisionUnitEnergy.getProcess());
                    }
                }
                newTaskList.add(task);
            }
            if (newTaskList.size() > 0) {
                tSupervisionUnitEnergyTaskService.saveOrUpdateBatch(newTaskList);
            }
        }
    }

    //子表  节能监察单位产品综合能耗
    private void  saveUnitComprehensive(JSONObject json, ScUser u, TSupervisionUnitEnergy tSupervisionUnitEnergy, boolean b) {
        String unitEnergyComprehensive = json.getString("unitEnergyComprehensive");
        if (unitEnergyComprehensive != null && !"".equals(unitEnergyComprehensive)) {
            List<TSupervisionUnitEnergyComprehensive> unitEnergyComprehensiveList = (List<TSupervisionUnitEnergyComprehensive>) JSONObject.parseArray(unitEnergyComprehensive, TSupervisionUnitEnergyComprehensive.class);
            if(unitEnergyComprehensiveList.size()>0){
                List<TSupervisionUnitEnergyComprehensive> newEnergyComprehensiveList = new ArrayList<>();
                TSupervisionUnitEnergyComprehensive t = new TSupervisionUnitEnergyComprehensive();
//                t.setDelFlag("1");
//                t.setUnitEnergyId(unitEnergyComprehensiveList.get(0).getUnitEnergyId());
//                List<TSupervisionUnitEnergyComprehensive> Lists=new ArrayList<>();
//                Lists=tSupervisionUnitEnergyComprehensiveService.list(Wrappers.query(t));
//                if(Lists.size()>0){
//                    for(int i=0;i<Lists.size();i++){
//                        tSupervisionUnitEnergyComprehensiveService.removeById(Lists.get(i).getId());
//                    }
//                }
                for (TSupervisionUnitEnergyComprehensive comprehensive : unitEnergyComprehensiveList) {
                    comprehensive.setUserid(u.getId());
                    comprehensive.setDeptId(u.getDeptId());
                    comprehensive.setUpdateTime(new Date());
                    if (StringUtils.isBlank(comprehensive.getDelFlag())){
                        comprehensive.setDelFlag("1");
                    }
                    if (b) {
                        comprehensive.setUnitEnergyId(tSupervisionUnitEnergy.getId());
                    }
                    newEnergyComprehensiveList.add(comprehensive);
                }
                if (newEnergyComprehensiveList.size() > 0) {
                    tSupervisionUnitEnergyComprehensiveService.saveOrUpdateBatch(newEnergyComprehensiveList);
                }
            }
        }
    }

    private String getCellValue(Cell cell, boolean b) {
        if (cell == null) {
            return "";
        }
        if (b) {
            //虽然excel中设置的都是文本，但是数字文本还被读错，如“1”取成“1.0”,加上下面这句，临时把它当做文本来读取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue());
        }
    }
}
