package com.nantian.cloud.jljc.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.*;
import com.nantian.cloud.jljc.service.*;
import com.nantian.cloud.jljc.vo.Query;
import com.nantian.cloud.jljc.vo.TSuperviseTaskOrganizationVo;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.minio.service.MinioTemplate;
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 lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * 节能节能监察任务表
 *
 * @date 2020-09-21
 */
@Slf4j
@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping("/tSuperviseTask")
@Api(value = "tSuperviseTask", tags = "节能监察任务表")
public class TSuperviseTaskController {
    @Autowired
    private TSuperviseTaskService tSuperviseTaskService;
    @Autowired
    private TSupervisionOrganizationService tSupervisionOrganizationService;
    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    private EnterpriseInfoService enterpriseInfoService;
    @Autowired
    private TSupervisionPersonService tSupervisionPersonService;
    @Autowired
    private TSupervisionInspectionService tSupervisionInspectionService;
    @Autowired
    private TSupervisionInvestigationService tSupervisionInvestigationService;
    @Autowired
    private TSupervisionNoteService tSupervisionNoteService;
    @Autowired
    private TSupervisionNotificationService tSupervisionNotificationService;
    @Autowired
    private TSupervisionComprehensiveEnergyService tSupervisionComprehensiveEnergyService;
    @Autowired
    private TSuperviseTaskApplyService tSuperviseTaskApplyService;



    /**
     * 监察任务上报接口
     * param id
     * @return
     */
    @SysLog("监察任务上报接口")
    @GetMapping("/taskReport/{id}")
    public R setReportType(@PathVariable Long id){
        ScUser u = SecurityUtils.getUser();
        TSuperviseTask tSuperviseTask = tSuperviseTaskService.getById(id);
        tSuperviseTask.setReportType(1);
        tSuperviseTask.setUpdateTime(new Date());
        tSuperviseTask.setUserid(u.getId());
        tSuperviseTaskService.updateById(tSuperviseTask);
        return R.ok();
    }

    /**
     * 分页查询企业信息
     */
    @SysLog("分页查询监察任务的企业信息")
    @GetMapping("/pageCom")
    @ApiOperation(value = "分页获取企业信息表", notes = "分页获取企业信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Query", value = "查询条件（企业名称name、企业信用编码code、地区pArea area、行业pIndustry industry）", required = false, dataType = "json", paramType = "path")
    })
    public R getPageCom(Page page, Query query) {
        //Page page = new Page();
        //查询条件地区以更细的为准
        if (query.getArea() == null || "".equals(query.getArea())) {
            query.setArea(query.getPArea());
        }
        //查询条件行业以更细的为准
        if (query.getIndustry() == null || "".equals(query.getIndustry())) {
            query.setIndustry(query.getPIndustry());
        }
        return R.ok(tSuperviseTaskService.getPageCom(page, query));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @SysLog("分页获取节能监察任务表")
    @ApiOperation(value = "分页获取节能监察任务表", notes = "分页获取节能监察任务表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Query", value = "查询条件（企业名称name、企业信用编码code、" +
                    "地区pArea area、行业pIndustry industry、监察编号num、任务名称item、任务状态state 1下发任务,2回复,3通过,4不通过" +
                    "、监察类型type 1书面监察,2现场监察,3复查、任务来源source 年度计划,抽查,复查,移交,举报投诉）", required = false, dataType = "json", paramType = "path")
    })
    public R getTSuperviseTaskPage(Page page, Query query) {
        //TSuperviseTask tSuperviseTask = new TSuperviseTask();
        //tSuperviseTask.setDelFlag("1"); //筛选未删除项
        //return R.ok(tSuperviseTaskService.page(page, Wrappers.query(tSuperviseTask)));
        //TSuperviseTask  ： 企业名称monitoredEnt、企业信用代码epc、行业industry、地区locate、监察编号monitorId、任务名称taskName、任务状态taskState
        if (query.getArea() == null || "".equals(query.getArea())) {
            query.setArea(query.getPArea());
        }
        //查询条件行业以更细的为准
        if (query.getIndustry() == null || "".equals(query.getIndustry())) {
            query.setIndustry(query.getPIndustry());
        }

        /*IPage<TSuperviseTaskOrganizationVo> tSuperviseTaskPage = tSuperviseTaskService.getTSuperviseTask(page, query);
        List<TSuperviseTaskOrganizationVo> newList = getTaskOrganizationVos(tSuperviseTaskPage);
        tSuperviseTaskPage.setRecords(newList);
        return R.ok(tSuperviseTaskPage);*/
        return R.ok(tSuperviseTaskService.getPageScope(page, query));
    }

    /**
     * 分页获取节能监察任务表（手机端）
     */
    @GetMapping("/pageByWX")
    @SysLog("分页获取节能监察任务表（手机端）")
    @ApiOperation(value = "分页获取节能监察任务表（手机端）", notes = "分页获取节能监察任务表（手机端）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Query", value = "查询条件（企业名称name、企业信用编码code、" +
                    "地区area、行业industry、监察编号num、监察类型type 1书面监察,2现场监察）", required = false, dataType = "json", paramType = "path")
    })
    public R pageByWX(Page page, Query query) {
        if (query.getArea() != null && !"".equals(query.getArea())) {
            if (query.getArea().contains("0000")) { //省
                query.setArea(StrUtil.subWithLength(query.getArea(), 0, 2)); //截取前2位
            } else if (query.getArea().contains("00")) { //州市
                query.setArea(StrUtil.subWithLength(query.getArea(), 0, 4)); //截取前4位
            }
        }
        return R.ok(tSuperviseTaskService.pageByWX(page, query));
    }

    /**
     * 节能监察任务完成情况汇总
     */
    @GetMapping("/totalByTask")
    @SysLog("节能监察任务完成情况汇总")
    @ApiOperation(value = "节能监察任务完成情况汇总", notes = "节能监察任务完成情况汇总")
    @ApiImplicitParam(name = "year", value = "年份", required = false, dataType = "string", paramType = "path")
    public R totalByTask(Query query) {
        return R.ok(tSuperviseTaskService.totalByTask(query));
    }


    /**
     * 分页查询
     */
    @GetMapping("/getTSuperviseTaskPageCom")
    @SysLog("分页获取节能监察任务表")
    @ApiOperation(value = "分页获取节能监察任务表", notes = "分页获取节能监察任务表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "分页对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "Query", value = "查询条件（企业名称name、企业信用编码code、" +
                    "地区pArea area、行业pIndustry industry、监察编号num、任务名称item、任务状态state 1下发任务,2回复,3通过,4不通过" +
                    "、监察类型type 1书面监察,2现场监察,3复查、任务来源source 年度计划,抽查,复查,移交,举报投诉）", required = false, dataType = "json", paramType = "path")
    })
    public R getTSuperviseTaskPageCom(Page page, Query query) {
        //TSuperviseTask tSuperviseTask = new TSuperviseTask();
        //tSuperviseTask.setDelFlag("1"); //筛选未删除项
        //return R.ok(tSuperviseTaskService.page(page, Wrappers.query(tSuperviseTask)));
        //TSuperviseTask  ： 企业名称monitoredEnt、企业信用代码epc、行业industry、地区locate、监察编号monitorId、任务名称taskName、任务状态taskState
        ScUser u = SecurityUtils.getUser();
        query.setCode(u.getEnterpriseCode());
        //查询条件行业以更细的为准
        /*if (query.getIndustry() == null || "".equals(query.getIndustry())) {
            query.setIndustry(query.getPIndustry());
        }
        if (query.getArea() == null || "".equals(query.getArea())) {
            query.setArea(query.getPArea());
        }*/
        /*IPage<TSuperviseTaskOrganizationVo> voIPage = tSuperviseTaskService.getTSuperviseTask(page, query);
        voIPage.setRecords(getTaskOrganizationVos(voIPage));
        return R.ok(voIPage);*/
        return R.ok(tSuperviseTaskService.getTSuperviseTask(page, query));
    }

    /**
     * 添加监察文书是否填报或上传附件
     */
    private List<TSuperviseTaskOrganizationVo> getTaskOrganizationVos(IPage<TSuperviseTaskOrganizationVo> tSuperviseTaskPage) {
        List<TSuperviseTaskOrganizationVo> taskOrganizationVos = tSuperviseTaskPage.getRecords();
        List<TSuperviseTaskOrganizationVo> newList = new ArrayList<>();
        for (TSuperviseTaskOrganizationVo taskOrganizationVo : taskOrganizationVos) {
            /*boolean flag = false;
            if (taskOrganizationVo.getMonitorId() != null) {
                //获取监察任务
                TSuperviseTask tSuperviseTask = new TSuperviseTask();
                tSuperviseTask.setMonitorId(taskOrganizationVo.getMonitorId());
                tSuperviseTask.setDelFlag("1");
                TSuperviseTask task = tSuperviseTaskService.getOne(Wrappers.query(tSuperviseTask));
                if (task != null) {
                    flag = true;
                    TSuperviseTask newTask = hasUploadFun(taskOrganizationVo.getMonitorId(), task);
                    taskOrganizationVo.setInspectionStatus(newTask.getInspectionStatus());
                    taskOrganizationVo.setInvestigationStatus(newTask.getInvestigationStatus());
                    taskOrganizationVo.setNoteStatus(newTask.getNoteStatus());
                    taskOrganizationVo.setNotificationStatus(newTask.getNotificationStatus());
                    taskOrganizationVo.setComprehensiveEnergyStatus(newTask.getComprehensiveEnergyStatus());
                }
            }
            if (flag = false) {
                taskOrganizationVo.setInspectionStatus("false");
                taskOrganizationVo.setInvestigationStatus("false");
                taskOrganizationVo.setNoteStatus("false");
                taskOrganizationVo.setNotificationStatus("false");
                taskOrganizationVo.setComprehensiveEnergyStatus("false");
            }*/
            newList.add(hasUploadFun(taskOrganizationVo.getMonitorId(), taskOrganizationVo));
        }
        return newList;
    }

    /**
     * 根据id获取节能监察任务表
     */
    @GetMapping("/getById")
    @SysLog("根据id获取节能监察任务表")
    @ApiOperation(value = "根据id获取节能监察任务表", notes = "根据id获取节能监察任务表")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R getById(Long id) {
        //return R.ok(tSuperviseTaskService.getById(id));
        return R.ok(tSuperviseTaskService.getTaskById(id));
    }

    /**
     * 根据tSuperviseTask对象的id清空节能监察任务表中的附加文件名称：告知书(附件)、现场监察笔录(附件)、现场询问笔录(附件)、通知书(附件)、现场文件(附件)
     */
    @PostMapping("/updateTask")
    @SysLog("根据id修改节能监察任务表中附加文件名称")
    @ApiOperation(value = "根据id修改节能监察任务表中附加文件名称", notes = "根据id修改节能监察任务表中附加文件名称")
    @ApiImplicitParam(name = "TSuperviseTask", value = "节能监察任务表对象", required = true, dataType = "json", paramType = "path")
    public R updateById(@RequestBody TSuperviseTask tSuperviseTask) {
        return R.ok(tSuperviseTaskService.updateTask(tSuperviseTask));
    }

    /**
     * 判断企业是否有未完成的下达任务
     */
    @GetMapping("/haveTaskRelease")
    @SysLog("判断企业是否有未完成的下达任务")
    @ApiOperation(value = "判断企业是否有未完成的下达任务", notes = "判断企业是否有未完成的下达任务")
    @ApiImplicitParam(name = "epc", value = "企业信用编码", required = true, dataType = "string", paramType = "path")
    public R haveTaskRelease(String epc) {
        if (epc == null) {
            return R.failed("企业信用编码为空，查询失败！");
        }
        List<TSuperviseTask> tSuperviseTasks = tSuperviseTaskService.haveTaskRelease(epc);
        log.error("判断企业是否有未完成的下达任务，任务为：{}", tSuperviseTasks);
        if (tSuperviseTasks.size() == 0) {
            return R.ok("企业无未完成的节能监察任务表"); //code 0
        } else {
            return R.failed("该企业还有未完成的书面监察任务表，继续下达任务？"); //code 1
        }
    }

    /**
     * 任务下达，获取监察人员
     */
    @GetMapping("/getJCPerson")
    @SysLog("监察任务下达，获取监察人员")
    @ApiOperation(value = "任务下达，获取监察人员", notes = "任务下达，获取监察人员")
    //@ApiImplicitParam(name = "areaCode", value = "地区代码", required = true, dataType = "string", paramType = "path")
    public R getJCPerson() {
        ScUser u = SecurityUtils.getUser();
        return R.ok(tSupervisionPersonService.getJCPerson(u.getDeptId()));
    }

    /**
     * 政府端任务下达，任务告知书不用
     */
    @PostMapping("/taskRelease")
    @SysLog("政府端任务下达（新增/修改），formdata请求方式")
    @ApiOperation(value = "政府端任务下达（新增/修改），formdata请求方式", notes = "政府端任务下达（新增/修改），formdata请求方式")
    @ApiImplicitParams({
            //@ApiImplicitParam(name = "file", value = "文件流（告知书）", required = true, dataType = "File", paramType = "path"),
            @ApiImplicitParam(name = "TSuperviseTask", value = "节能监察任务表对象", required = false, dataType = "json", paramType = "path"),
            @ApiImplicitParam(name = "taskDate", value = "监察时间", required = false, dataType = "string", paramType = "path"),
    })
    //public R taskRelease(TSuperviseTask tSuperviseTask, @RequestParam("file") MultipartFile file, String taskDate) throws Exception {
    public R taskRelease(TSuperviseTask tSuperviseTask, String taskDate) throws Exception {
        ScUser u = SecurityUtils.getUser();

        TSuperviseTask t = new TSuperviseTask();
        t.setMonitorId(tSuperviseTask.getMonitorId());
        t.setDelFlag("1");
        if (tSuperviseTaskService.list(Wrappers.query(t)).size() > 0) {
            return R.failed("节能监察编码已存在，任务下达失败！");
        }

        if (tSuperviseTask.getId() == null) {//新增
            //tSuperviseTask.setDeptId(u.getDeptId());
            tSuperviseTask.setDelFlag("1");
            EnterpriseInfo enterprise = enterpriseInfoService.getInfoByCode(tSuperviseTask.getEpc());
            if (enterprise != null) {
                //tSuperviseTask.setMonitoredEnt(enterprise.getCmpName());
                tSuperviseTask.setIndustry(enterprise.getIndustryCode());
                //tSuperviseTask.setLocate(enterprise.getRegionCode());
            }
        }
        TSupervisionOrganization o = tSupervisionOrganizationService.getOne(new QueryWrapper<>(new TSupervisionOrganization())
                .eq("id",tSuperviseTask.getOrganizationId()));
        if(o!=null){ //设置deptId、locate为经办单位地区码
            tSuperviseTask.setDeptId(Integer.parseInt(o.getAreaCode()));
            tSuperviseTask.setLocate(o.getAreaCode());
        }else{
            return R.failed("监察机构不存在");
        }
        tSuperviseTask.setUpdateTime(new Date());
        tSuperviseTask.setUserid(u.getId());
        tSuperviseTask.setTaskState("1");   //任务下达
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        if (taskDate != null && !"".equals(taskDate)) {  //设置监察时间
            tSuperviseTask.setDate(df.parse(taskDate));
        }

		/*if(file!=null){
			//上传文件
			String uuid = UUID.randomUUID().toString();
			InputStream inputStream = file.getInputStream(); //得到文件流
			String fileName = file.getOriginalFilename();    //文件名（含后缀）
			minioTemplate.putObject("jljc", uuid, inputStream);
			//1：告知书(附件)
			tSuperviseTask.setNotification(fileName + "<" + uuid);
		}*/

        return R.ok(tSuperviseTaskService.saveOrUpdate(tSuperviseTask));
    }


    /**
     * 企业回复节能监察任务(材料提交)
     */
    @PostMapping("/submit")
    @SysLog("企业回复节能监察任务(材料提交)")
    @ApiOperation(value = "企业回复节能监察任务(材料提交)", notes = "企业回复节能监察任务(材料提交)")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R save(Long id) {

        TSuperviseTask tSuperviseTask = tSuperviseTaskService.getById(id);
        if (tSuperviseTask == null) {
            return R.failed("节能监察任务不存在，回复失败！");
        }

        if (tSuperviseTask.getSelectCapacity() == null) {
            return R.failed("请提交附件，选择产能与工序/工艺，再回复！");
        }
        if (tSuperviseTask.getComprehensiveEnergy() == null) {
            return R.failed("请提交附件，综合能耗计算表，再回复！");
        }
        if (tSuperviseTask.getUnitEnergy() == null) {
            return R.failed("请提交附件，单位能耗计算表，再回复！");
        }

        ScUser u = SecurityUtils.getUser();
        tSuperviseTask.setUserid(u.getId());
        tSuperviseTask.setUpdateTime(new Date());
        tSuperviseTask.setTaskState("2"); //回复
        return R.ok(tSuperviseTaskService.updateById(tSuperviseTask));
    }


    /**
     * 新增/修改节能监察任务表
     */
    @PostMapping("/renew")
    @SysLog("新增/修改节能监察任务表")
    @ApiOperation(value = "新增/修改节能监察任务表", notes = "新增/修改节能监察任务表")
    @ApiImplicitParam(name = "TSuperviseTask", value = "节能监察任务表对象", required = true, dataType = "json", paramType = "path")
    public R save(@RequestBody TSuperviseTask tSuperviseTask) {

        TSuperviseTask t = new TSuperviseTask();
        t.setMonitorId(tSuperviseTask.getMonitorId());
        if(tSuperviseTask.getId()==null){
            if (tSuperviseTaskService.list(Wrappers.query(t)).size() > 0) {
                return R.failed("节能监察编码已存在， 新增/修改节能监察任务失败！");
            }
        }
        String monitorId=tSuperviseTask.getMonitorId();
        String inspectors=tSuperviseTask.getInspectors();
        Map<String, Object> map = new HashMap();
        map=tSuperviseTaskService.taskInfo(tSuperviseTask);
        ScUser u = SecurityUtils.getUser();
        if (tSuperviseTask.getId() == null) {//新增
            tSuperviseTask.setDeptId(u.getDeptId());
            tSuperviseTask.setDelFlag("1");
        }
        tSuperviseTask.setUpdateTime(new Date());
        tSuperviseTask.setUserid(u.getId());
        return R.ok(tSuperviseTaskService.saveOrUpdate(tSuperviseTask));
    }

    /**
     * 上传文件材料
     */
    @SneakyThrows
    @PostMapping("/upload")
    @SysLog("监察任务上传文件材料")
    @ApiOperation(value = "上传文件材料", notes = "上传文件材料")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path"),
            @ApiImplicitParam(name = "type", value = "文件类型（1：告知书(附件)，" +
                    "2：选择产能与工序/工艺(附件)，" +
                    "3：综合能耗计算表(附件)" +
                    "4：单位能耗计算表(附件)" +
                    "5：现场监察笔录(附件)" +
                    "6：现场询问笔录(附件)" +
                    "7：通知书(附件)" +
                    "8：现场文件(附件)", required = true, dataType = "string", paramType = "path"),
            @ApiImplicitParam(name = "file", value = "文件流", required = true, dataType = "File", paramType = "path"),
    })
    public R upload(String type, @RequestParam("file") MultipartFile file, Long id) {

        TSuperviseTask tSuperviseTask = tSuperviseTaskService.getById(id);
        if (tSuperviseTask == null) {
            return R.failed("节能监察任务表不存在，上传附件失败");
        }

        //上传文件
        String uuid = UUID.randomUUID().toString();
        InputStream inputStream = file.getInputStream(); //得到文件流
        String fileName = file.getOriginalFilename();    //文件名（含后缀）
        //minioTemplate.putObject("jljc", uuid, inputStream);
        minioTemplate.putObject("jljc", uuid, inputStream, inputStream.available(), "application/octet-stream");

        String fileUrl = fileName + "<" + uuid;
        if ("1".equals(type)) {
            //1：告知书(附件)
            tSuperviseTask.setNotification(fileUrl);
        } else if ("2".equals(type)) {
            //2：选择产能与工序/工艺(附件)
            tSuperviseTask.setSelectCapacity(fileUrl);
        } else if ("3".equals(type)) {
            //3：综合能耗计算表(附件)
            tSuperviseTask.setComprehensiveEnergy(fileUrl);
        } else if ("4".equals(type)) {
            //4:单位能耗计算表(附件)
            tSuperviseTask.setUnitEnergy(fileUrl);
        } else if ("5".equals(type)) {
            //5：现场监察笔录(附件)
            tSuperviseTask.setInsiteSupervision(fileUrl);
        } else if ("6".equals(type)) {
            //6：现场询问笔录(附件)
            tSuperviseTask.setInterviewTranscripts(fileUrl);
        } else if ("7".equals(type)) {
            //7：通知书(附件)
            tSuperviseTask.setNote(fileUrl);
        }else if ("8".equals(type)) {
            //8：现场文件(附件)
            tSuperviseTask.setSceneFile(fileUrl);
        } else {
            return R.failed("文件类型错误，上传附件失败");
        }
        ScUser u = SecurityUtils.getUser();
        tSuperviseTask.setUserid(u.getId());
        tSuperviseTask.setUpdateTime(new Date());

        return R.ok(tSuperviseTaskService.updateById(tSuperviseTask));
    }

    /**
     * 查询监察文书是否填报或上传附件
     */
    @GetMapping("/hasUpload")
    @SysLog("查询监察文书是否填报或上传附件")
    @ApiOperation(value = "查询监察文书是否填报或上传附件", notes = "查询监察文书是否填报或上传附件")
    @ApiImplicitParam(name = "monitorId", value = "监察编号", required = false, dataType = "json", paramType = "path")
    public R hasUpload(String monitorId) {
        if (monitorId == null) {
            return R.failed("监察编号不能为空，查询失败！");
        }

        //获取监察任务
        TSuperviseTask tSuperviseTask = new TSuperviseTask();
        tSuperviseTask.setMonitorId(monitorId);
        tSuperviseTask.setDelFlag("1");
        TSuperviseTask task = tSuperviseTaskService.getOne(Wrappers.query(tSuperviseTask));
        if (task == null) {
            return R.failed("监察任务不存在，查询失败！");
        }

        //Map<String, Object> map = new HashMap<>();
        return R.ok(hasUploadFun(monitorId, task));
    }

    /**
     * 查询监察文书是否填报或上传附件方法
     */
    //private  Map<String, Object> hasUploadFun(String monitorId, TSuperviseTask task, Map<String, Object> map) {
    private <T extends TSuperviseTask> T  hasUploadFun(String monitorId, T task) {
        //现场检查笔录
        TSupervisionInspection tSupervisionInspection = new TSupervisionInspection();
        tSupervisionInspection.setMonitorId(monitorId);
        tSupervisionInspection.setDelFlag("1");
        List<TSupervisionInspection> inspectionList = tSupervisionInspectionService.list(Wrappers.query(tSupervisionInspection));
        if (task.getInsiteSupervision() != null || inspectionList.size() > 0) {//现场检查笔录
            //map.put("inspection", "true");
            task.setInspectionStatus("true");
        } else {
            //map.put("inspection", "false");
            task.setInspectionStatus("false");
        }

        //调查（询问）笔录
        TSupervisionInvestigation tSupervisionInvestigation = new TSupervisionInvestigation();
        tSupervisionInvestigation.setMonitorId(monitorId);
        tSupervisionInvestigation.setDelFlag("1");
        List<TSupervisionInvestigation> investigationList = tSupervisionInvestigationService.list(Wrappers.query(tSupervisionInvestigation));
        if (task.getInterviewTranscripts() != null || investigationList.size() > 0) {//调查询问笔录
            //map.put("investigation", "true");
            task.setInvestigationStatus("true");
        } else {
            //map.put("investigation", "false");
            task.setInvestigationStatus("false");
        }

        //节能监察通知书
        TSupervisionNote tSupervisionNote = new TSupervisionNote();
        tSupervisionNote.setMonitorId(monitorId);
        tSupervisionNote.setDelFlag("1");
        List<TSupervisionNote> noteList = tSupervisionNoteService.list(Wrappers.query(tSupervisionNote));
        if (task.getNote() != null || noteList.size() > 0) {//节能监察通知书
            //map.put("note", "true");
            task.setNoteStatus("true");
        } else {
            //map.put("note", "false");
            task.setNoteStatus("false");
        }

        //监察告知书
        TSupervisionNotification tSupervisionNotification = new TSupervisionNotification();
        tSupervisionNotification.setMonitorId(monitorId);
        tSupervisionNotification.setDelFlag("1");
        List<TSupervisionNotification> notificationList = tSupervisionNotificationService.list(Wrappers.query(tSupervisionNotification));
        if (task.getNotification() != null || notificationList.size() > 0) {//监察告知书
            //map.put("notification", "true");
            task.setNotificationStatus("true");
        } else {
            //map.put("notification", "false");
            task.setNotificationStatus("false");
        }

        //节能监察综合能耗
        TSupervisionComprehensiveEnergy tSupervisionComprehensiveEnergy = new TSupervisionComprehensiveEnergy();
        tSupervisionComprehensiveEnergy.setMonitorId(monitorId);
        tSupervisionComprehensiveEnergy.setDelFlag("1");
        List<TSupervisionComprehensiveEnergy> comprehensiveEnergyList = tSupervisionComprehensiveEnergyService.list(Wrappers.query(tSupervisionComprehensiveEnergy));
        if (comprehensiveEnergyList.size() > 0) {//节能监察综合能耗，不判断task的附件字段
            //map.put("comprehensiveEnergy", "true");
            task.setComprehensiveEnergyStatus("true");
        } else {
            //map.put("comprehensiveEnergy", "false");
            task.setComprehensiveEnergyStatus("false");
        }

        //return map;
        return task;
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    @SysLog("删除节能监察任务表")
    @ApiOperation(value = "删除节能监察任务表", notes = "删除节能监察任务表")
    @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int", paramType = "path")
    public R removeById(Integer[] id) {
        for (int i = 0; i < id.length; i++) {
            TSuperviseTask tSuperviseTask = tSuperviseTaskService.getById(id[i]);
            if (tSuperviseTask == null) {
                return R.failed("节能监察任务表不存在，删除失败");
            }
            ScUser u = SecurityUtils.getUser();
            tSuperviseTask.setDelFlag("4");
            tSuperviseTask.setUserid(u.getId());
            tSuperviseTask.setUpdateTime(new Date());
            tSuperviseTaskService.updateById(tSuperviseTask);
        }
        return R.ok();
    }

    /*
    导入Excel监察表
     */
    @PostMapping("/excelImport")
    @SysLog("Excel导入节能监察任务表")
    @ApiOperation(value = "导入excel", notes = "导入excel")
    @ApiImplicitParam(name = "file", value = "文件", required = true, dataType = "file", paramType = "path")
    public R excelImport(@RequestParam MultipartFile file) throws FileFormatException {
        return  tSuperviseTaskService.excelImport(file);
    }

}
