package com.zcloud.controller.inspection;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.hotWorkApplication.Node;
import com.zcloud.entity.hotWorkApplication.Overseer;
import com.zcloud.service.bus.impl.NoticeCorpUtils;
import com.zcloud.service.hidden.HiddenCheckService;
import com.zcloud.service.hidden.HiddenService;
import com.zcloud.service.inspection.SafetyEnvironmentalAssessService;
import com.zcloud.service.inspection.SafetyEnvironmentalExplainService;
import com.zcloud.service.inspection.SafetyEnvironmentalInspectorService;
import com.zcloud.service.inspection.SafetyEnvironmentalService;
import com.zcloud.service.notice.NoticeCorpService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 说明：安全环保检查
 * 作者：luoxiaobao
 * 时间：2022-06-08
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/safetyenvironmental")
public class SafetyEnvironmentalController extends BaseController {

    @Autowired
    private SafetyEnvironmentalService safetyenvironmentalService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private NoticeCorpService noticeCorpService;
    @Autowired
    private HiddenService hiddenService;
    @Autowired
    private HiddenCheckService hiddenCheckService;
    @Autowired
    private SafetyEnvironmentalExplainService explainService;
    @Resource
    private SafetyEnvironmentalInspectorService inspectorService;
    @Resource
    private SafetyEnvironmentalAssessService assessService;
    @Autowired
    private NoticeCorpUtils noticeCorpUtils;
    @Autowired
    private Smb smb;

    /**
     * 列表
     *
     * @throws
     */
    @RequestMapping(value = "/hiddenCountByUser")
    @ResponseBody
    public Object hiddenCountByUser() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData search = new PageData();
        search = this.getPageData();
        if (Tools.isEmpty(search.get("corpinfoId"))) {
            search.put("corpinfoId", Jurisdiction.getCORPINFO_ID());
        }
        if (Tools.isEmpty(search.getString("deptId")) && !Jurisdiction.getCORPINFO_ID().equals(Jurisdiction.getDEPARTMENT_ID())) {
            search.put("deptId", Jurisdiction.getDEPARTMENT_ID());
        }
        String startTime = "";
        String endTime = "";
        if ("1".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-01-01 00:00";
            endTime = search.getString("YEAR") + "-04-01 00:00";
        } else if ("2".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-04-01 00:00";
            endTime = search.getString("YEAR") + "-07-01 00:00";
        } else if ("3".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-07-01 00:00";
            endTime = search.getString("YEAR") + "-09-01 00:00";
        } else if ("4".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-09-01 00:00";
            endTime = search.getString("YEAR") + "-12-31 24:00";
        }
        search.put("startTime", startTime);
        search.put("endTime", endTime);
        List<PageData> userAllList = usersService.listUserAndDept(search);
        List<PageData> userData = safetyenvironmentalService.getHiddenCountByUser(search);    //分公司隐患数据
        Map<String, Integer> userCount = new HashMap<>();
        for (PageData pageData : userData) {
            String userId = pageData.getString("CONFIRM_USER");
            String hiddenLevenl = pageData.getString("HIDDENLEVEL");
            String key = userId + "--" + hiddenLevenl;
            int count = 0;
            if (userCount.containsKey(key)) {
                count = userCount.get(key);
            }
            count += Integer.parseInt(pageData.getString("count"));
            userCount.put(key, count);
        }
        //						 忽略隐患 轻微隐患 小微隐患  较大隐患 重大隐患
        String[] hiddenLevelAllList = {"hiddenLevel1001", "hiddenLevel1002", "hiddenLevel1004", "jdyh001", "hiddenLevel2002"};
        for (PageData pageData : userAllList) {
            Double defen = 0d;
            for (String hiddenLevenl : hiddenLevelAllList) {
                String userId = pageData.getString("USER_ID");
                String key = userId + "--" + hiddenLevenl;
                if (userCount.containsKey(key)) {
                    pageData.put(hiddenLevenl, userCount.get(key));
                    if (hiddenLevenl.equals("hiddenLevel1002")) {
                        defen += userCount.get(key) * 0.1;
                    } else if (hiddenLevenl.equals("hiddenLevel1004")) {
                        defen += userCount.get(key) * 1;
                    }
                } else {
                    pageData.put(hiddenLevenl, "0");
                }
            }
            pageData.put("denfen", defen);
        }
        map.put("varList", userAllList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @throws Exception
     */
    @RequestMapping(value = "/hiddenCountByDept")
    @ResponseBody
    public Object hiddenByDept() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData search = new PageData();
        search = this.getPageData();
        String startTime = "";
        String endTime = "";
        if ("1".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-01-01 00:00";
            endTime = search.getString("YEAR") + "-04-01 00:00";
        } else if ("2".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-04-01 00:00";
            endTime = search.getString("YEAR") + "-07-01 00:00";
        } else if ("3".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-07-01 00:00";
            endTime = search.getString("YEAR") + "-09-01 00:00";
        } else if ("4".equals(search.getString("QUARTER"))) {
            startTime = search.getString("YEAR") + "-09-01 00:00";
            endTime = search.getString("YEAR") + "-12-31 24:00";
        }
        search.put("startTime", startTime);
        search.put("endTime", endTime);
        if ("0".equals(search.getString("PARENT_ID"))) {
            search.put("DEPARTMENT_ID", Jurisdiction.getCORPINFO_ID());
        } else {
            search.put("PARENT_ID", search.getString("PARENT_ID"));
        }
        List<PageData> varList = departmentService.listDept(search);
        for (PageData dept : varList) {
            search.put("DEPARTMENT_ID", dept.getString("DEPARTMENT_ID"));
            List<PageData> data = safetyenvironmentalService.getHiddenCountByDepat(search);    //分公司隐患数据
            double defen = 0;
            for (PageData pageData : data) {
                String hiddenLevenl = pageData.getString("HIDDENLEVEL");
                Integer count = Integer.parseInt(pageData.getString("count"));
                if (hiddenLevenl.equals("hiddenLevel1004")) {
                    defen += count * 0.2;
                }
                if (hiddenLevenl.equals("hiddenLevel1002")) {
                    defen += count * 1;
                }
                dept.put(hiddenLevenl, count);
            }
            dept.put("denfen", defen);
        }
        map.put("varList", varList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    // @RequiresPermissions("safetyenvironmental:list")
    @ResponseBody
    public Object list(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = this.getPageData();
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
//		PageData userInfo = new PageData();
//		userInfo.put("USER_ID",pd.getString("INSPECTION_ORIGINATOR_ID"));
//		userInfo = usersService.findById(userInfo);
//		if (StringUtils.isNotBlank(userInfo.getString("ISMAIN")) && "1".equals(userInfo.getString("ISMAIN"))){
//			pd.remove("INSPECTION_ORIGINATOR_ID");
//			pd.put("CORPINFO_ID_MAIN","1");
//		}
        pd = Jurisdiction.getUserDataJurisdiction(pd);
        page.setPd(pd);
        List<PageData> varList = safetyenvironmentalService.list(page);
        // 涉及隐患数
        String hiddenTotal = safetyenvironmentalService.getHiddenTotal(page);
        map.put("safetyTotal", varList.size());
        //列出SafetyEnvironmental列表
        for (PageData vector : varList) {
            safetyenvironmentalService.departmentUtil(vector);
        }
        map.put("hiddenTotal", hiddenTotal);
        map.put("safetyTotal", page.getTotalResult());
        map.put("varList", varList);
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/pleadList")
    // @RequiresPermissions("safetyenvironmental:list")
    @ResponseBody
    public Object pleadList(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        pd = Jurisdiction.getUserDataJurisdiction(pd);
        page.setPd(pd);
        List<PageData> varList = safetyenvironmentalService.pleadList(page);    //列出SafetyEnvironmental列表
        for (PageData vector : varList) {
            safetyenvironmentalService.departmentUtil(vector);
        }
        map.put("varList", varList);
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 新增
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    // @RequiresPermissions("safetyenvironmental:add")
    @ResponseBody
    public Object add() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("INSPECTION_ID", this.get32UUID());    //主键
        pd.put("INSPECTION_ORIGINATOR_ID", Jurisdiction.getUSER_ID());    //检查发起人
        pd.put("ISDELETE", "0");    //是否删除(0:有效 1：删除)
        pd.put("CREATOR", Jurisdiction.getUSER_ID());    //添加人
        pd.put("CREATTIME", DateUtil.date2Str(new Date()));    //添加时间
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        pd.put("CORPINFO_ID", "1".equals(Jurisdiction.getUSER_ID()) ? "" : Jurisdiction.getCORPINFO_ID());    //企业ID
        pd.put("ACTION_USER", Jurisdiction.getName());    //操作人
        if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE_SIGN"))) {
            MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(pd.getString("CONFIRM_MESSAGE_SIGN"));
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!"pdf".equals(suffixName) && !"jpg".equals(suffixName) && !"jpeg".equals(suffixName) && !"png".equals(suffixName) && !"mp4".equals(suffixName)) {
                errInfo = "fail";
                map.put("result", errInfo);
                map.put("msg", "文件格式不正确！");
                return map;
            }
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(file, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("CONFIRM_MESSAGE_SIGN_ROUTE", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
        }
        List<PageData> hiddenList = safetyenvironmentalService.save(pd);
        pd.put("hiddenList", hiddenList);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改页面获取数据
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/goShow")
    @ResponseBody
    public Object goShow() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd = safetyenvironmentalService.findShowById(pd);    //根据ID读取
        safetyenvironmentalService.departmentUtil(pd);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 去修改页面获取数据
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/goEdit")
    // @RequiresPermissions("safetyenvironmental:edit")
    @ResponseBody
    public Object goEdit() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd = safetyenvironmentalService.findFormById(pd);    //根据ID读取
        safetyenvironmentalService.departmentUtil(pd);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 修改
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    // @RequiresPermissions("safetyenvironmental:edit")
    @ResponseBody
    public Object edit() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("INSPECTION_STATUS", "0");    //状态(0.待检查人核实 1.检查人核实中、2.待被检查人确认、3.已归档 -1.检查人核实打回 -2被检查人申辩)
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        pd.put("CORPINFO_ID", "1".equals(Jurisdiction.getUSER_ID()) ? "" : Jurisdiction.getCORPINFO_ID());    //企业ID
        pd.put("ACTION_USER", Jurisdiction.getName());    //操作人
        if (StringUtils.isNotBlank(pd.getString("CONFIRM_MESSAGE_SIGN"))) {
            MultipartFile file = BASE64DecodedMultipartFile.base64ToMultipart(pd.getString("CONFIRM_MESSAGE_SIGN"));
            String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!"pdf".equals(suffixName) && !"jpg".equals(suffixName) && !"jpeg".equals(suffixName) && !"png".equals(suffixName) && !"mp4".equals(suffixName)) {
                errInfo = "fail";
                map.put("result", errInfo);
                map.put("msg", "文件格式不正确！");
                return map;
            }
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(file, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);
            pd.put("CONFIRM_MESSAGE_SIGN_ROUTE", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
        }
        List<PageData> hiddenList = safetyenvironmentalService.edit(pd);
        pd.put("hiddenList", hiddenList);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 修改
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/explain")
    // @RequiresPermissions("safetyenvironmental:edit")
    @ResponseBody
    public Object explain() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
        pd.put("ACTION_USER", Jurisdiction.getName());    //操作人
        if (StringUtils.isNotBlank(pd.getString("INSPECTION_ORIGINATOR_SIGN_IMG"))) {
            MultipartFile img = BASE64DecodedMultipartFile.base64ToMultipart(pd.getString("INSPECTION_ORIGINATOR_SIGN_IMG"));
            String suffixName = img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
            if (!"pdf".equals(suffixName) && !"jpg".equals(suffixName) && !"jpeg".equals(suffixName) && !"png".equals(suffixName) && !"mp4".equals(suffixName)) {
                errInfo = "fail";
                map.put("result", errInfo);
                map.put("msg", "文件格式不正确！");
                return map;
            }
            String ffile = DateUtil.getDays();
            String fileName = this.get32UUID() + img.getOriginalFilename().substring(img.getOriginalFilename().lastIndexOf("."));
            smb.sshSftp(img, fileName, Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile);

            pd.put("INSPECTION_ORIGINATOR_SIGN_IMG", Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
        }
        safetyenvironmentalService.explain(pd);

        pd.put("inspector", Jurisdiction.getUSER_ID());
        noticeCorpUtils.FailPleadind(pd);
        map.put("pd", pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 删除
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    // @RequiresPermissions("safetyenvironmental:del")
    @ResponseBody
    public Object delete() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        safetyenvironmentalService.delete(pd);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/hide")
    // @RequiresPermissions("safetyenvironmental:del")
    @ResponseBody
    public Object hide() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        PageData pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));
        pd.put("hide", "1");
        safetyenvironmentalService.delete(pd);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 批量删除
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/deleteAll")
    // @RequiresPermissions("safetyenvironmental:del")
    @ResponseBody
    public Object deleteAll() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("OPERATOR", Jurisdiction.getUSER_ID());    //修改人
        pd.put("OPERATTIME", DateUtil.date2Str(new Date()));    //修改时间
        String DATA_IDS = pd.getString("DATA_IDS");
        if (Tools.notEmpty(DATA_IDS)) {
            String[] ArrayDATA_IDS = DATA_IDS.split(",");
            pd.put("ArrayDATA_IDS", ArrayDATA_IDS);    //待删除ids
            safetyenvironmentalService.deleteAll(pd);
            errInfo = "success";
        } else {
            errInfo = "fail";
        }
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * 导出到excel
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
    // @RequiresPermissions("toExcel")
    public ModelAndView exportExcel() throws Exception {
        ModelAndView mv = new ModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<String> titles = new ArrayList<String>();
        titles.add("检查发起人");    //1
        titles.add("被检查单位");    //2
        titles.add("被检查单位现场负责人");    //3
        titles.add("申辩内容");    //4
        titles.add("被检查单位现场负责人签字");    //5
        titles.add("被检查单位现场负责人签字时间");    //6
        titles.add("检查类型");    //7
        titles.add("检查场所");    //8
        titles.add("检查开始时间");    //9
        titles.add("检查结束时间");    //10
        titles.add("状态(0.暂存 1.检查人待确认、2.被检查人待确认、3.归档 -1.检查人异议打回 -2被检查人申辩)");    //11
        titles.add("是否删除(0:有效 1：删除)");    //12
        titles.add("添加人");    //13
        titles.add("添加时间");    //14
        titles.add("修改人");    //15
        titles.add("修改时间");    //16
        titles.add("企业ID");    //17
        dataMap.put("titles", titles);
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        List<PageData> varOList = safetyenvironmentalService.listAll(pd);
        List<PageData> varList = new ArrayList<PageData>();
        for (int i = 0; i < varOList.size(); i++) {
            PageData vpd = new PageData();
            vpd.put("var1", varOList.get(i).getString("INSPECTION_ORIGINATOR_ID"));        //1
            vpd.put("var2", varOList.get(i).getString("INSPECTED_DEPARTMENT_ID"));        //2
            vpd.put("var3", varOList.get(i).getString("INSPECTED_SITEUSER_ID"));        //3
            vpd.put("var4", varOList.get(i).getString("INSPECTED_EXPLAIN"));        //4
            vpd.put("var5", varOList.get(i).getString("INSPECTED_SITEUSER_SIGN_IMG"));        //5
            vpd.put("var6", varOList.get(i).getString("INSPECTED_SITEUSER_SIGN_TIME"));        //6
            vpd.put("var7", varOList.get(i).getString("INSPECTION_TYPE"));        //7
            vpd.put("var8", varOList.get(i).getString("INSPECTION_PLACE"));        //8
            vpd.put("var9", varOList.get(i).getString("INSPECTION_TIME_START"));        //9
            vpd.put("var10", varOList.get(i).getString("INSPECTION_TIME_END"));        //10
            vpd.put("var11", varOList.get(i).getString("INSPECTION_STATUS"));        //11
            vpd.put("var12", varOList.get(i).getString("ISDELETE"));        //12
            vpd.put("var13", varOList.get(i).getString("CREATOR"));        //13
            vpd.put("var14", varOList.get(i).getString("CREATTIME"));        //14
            vpd.put("var15", varOList.get(i).getString("OPERATOR"));        //15
            vpd.put("var16", varOList.get(i).getString("OPERATTIME"));        //16
            vpd.put("var17", varOList.get(i).getString("CORPINFO_ID"));        //17
            varList.add(vpd);
        }
        dataMap.put("varList", varList);
        ObjectExcelView erv = new ObjectExcelView();
        mv = new ModelAndView(erv, dataMap);
        return mv;
    }

    /**
     * 列表
     *
     * @throws Exception
     */
    @RequestMapping(value = "/statistics/branch")
    @ResponseBody
    public Object statisticsBranch(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        if (StringUtils.isEmpty(pd.getString("PARENT_ID"))) {
            pd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
        }
        page.setPd(pd);
        List<PageData> varList = departmentService.listDept(page);
        for (PageData dept : varList) {
            pd.put("DEPARTMENT_ID", dept.getString("DEPARTMENT_ID"));
            PageData data = safetyenvironmentalService.statisticsBranch(pd);    //分公司安全环保检查考核分数统计
            dept.put("HIDDEN_FIND", data.get("HIDDEN_FIND"));
            dept.put("HIDDEN_ASSESS", data.get("HIDDEN_ASSESS"));
            dept.put("ASSESS_SCORE", data.get("ASSESS_SCORE"));
        }
        map.put("page", page);
        map.put("varList", varList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @throws Exception
     */
    @RequestMapping(value = "/statistics/branchV2")
    @ResponseBody
    public Object statisticsBranchV2(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        if (StringUtils.isEmpty(pd.getString("PARENT_ID"))) {
            pd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
        }
        List<PageData> varList = departmentService.getSonIdsByParid(pd);

        List<PageData> dataAllList = safetyenvironmentalService.statisticsBranchGroupDept(pd);
        for (PageData dept : varList) {
            String sonIds = dept.getString("ids");
            if (sonIds != null) {
                dept.put("NEXTCOUNT", sonIds.split(",").length);
            }
            Double HIDDEN_FIND = 0d;
            Double HIDDEN_ASSESS = 0d;
            Double ASSESS_SCORE = 0d;
            for (PageData dataItem : dataAllList) {
                String itemDataDepat = dataItem.getString("INSPECTED_DEPARTMENT_ID");
                if (sonIds.indexOf(itemDataDepat) != -1) {
                    HIDDEN_FIND += new Double(dataItem.getString("HIDDEN_FIND"));
                    HIDDEN_ASSESS += new Double(dataItem.getString("HIDDEN_ASSESS"));
                    ASSESS_SCORE += new Double(dataItem.getString("ASSESS_SCORE"));
                }
            }
            dept.put("HIDDEN_FIND", HIDDEN_FIND);
            dept.put("HIDDEN_ASSESS", HIDDEN_ASSESS);
            dept.put("ASSESS_SCORE", ASSESS_SCORE);
        }
        map.put("varList", varList);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 下载
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/download")
    public void download(HttpServletResponse response) throws Exception {
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            pd = safetyenvironmentalService.findById(pd);
            String FILEPATH = pd.getString("INSPECTED_EXPLAIN_FILEPATH");
            String FILENAME = pd.getString("INSPECTED_EXPLAIN_FILENAME");
            //服务器
            FileDownload.mfFileDownload(response, Const.HTTPFILEURL + FILEPATH, FILENAME);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("=========文件下载异常：可能要下载的文件已经没有了=========");
        }
    }

    /**
     * 下载
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/downloadExplain")
    public void downloadExplain(HttpServletResponse response) throws Exception {
        PageData pd = this.getPageData();
        try {
            pd = explainService.findById(pd);
            String FILEPATH = pd.getString("INSPECTED_EXPLAIN_FILEPATH");
            String FILENAME = pd.getString("INSPECTED_EXPLAIN_FILENAME");
            //服务器
            FileDownload.mfFileDownload(response, Const.HTTPFILEURL + FILEPATH, FILENAME);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 列表
     *
     * @throws Exception
     */
    @RequestMapping(value = "/statistics/jointstock")
    @ResponseBody
    public Object statisticsJointStock() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        if (StringUtils.isBlank(pd.getString("CORPINFO_ID"))) {
            if ("admin".equals(Jurisdiction.getUsername())) {
                throw new RuntimeException("admin用户无法使用该功能");
            }
            pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
        }
        List<PageData> varList = safetyenvironmentalService.statisticsJointStock(pd);    //股份公司安全环保检查考核分数统计
        map.put("varList", varList);
        map.put("result", errInfo);
        return map;
    }

    @RequestMapping(value = "/getExplain")
    @ResponseBody
    public Object getExplain() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = this.getPageData();
        List<PageData> list = explainService.findExplainById(pd);
        map.put("list", list);
        map.put("result", errInfo);
        return map;
    }

    /**
     * 列表
     *
     * @param page
     * @throws Exception
     */
    @RequestMapping(value = "/checkList")
    // @RequiresPermissions("safetyenvironmental:list")
    @ResponseBody
    public Object checkList(Page page) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String KEYWORDS = pd.getString("KEYWORDS");                        //关键词检索条件
        if (Tools.notEmpty(KEYWORDS)) pd.put("KEYWORDS", KEYWORDS.trim());
        pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());    //企业ID
        pd.put("waffle", Jurisdiction.getUSER_ID());
        page.setPd(pd);
        List<PageData> varList = safetyenvironmentalService.checkList(page);    //列出SafetyEnvironmental列表
        /* 针对验收部分特殊处理 */
        for (PageData vector : varList) {
            if (StringUtils.isNotBlank(vector.getString("INSPECTION_STATUS")) &&
                    ("6".equals(vector.getString("INSPECTION_STATUS"))
                            || "5".equals(vector.getString("INSPECTION_STATUS"))
//                            || "7".equals(vector.getString("INSPECTION_STATUS"))
                    )
            ) {
                PageData condition = new PageData();
                condition.put("FOREIGN_ID", vector.getString("INSPECTION_ID"));
                List<PageData> waffle = hiddenService.findByKey(condition);
                if (waffle == null || waffle.isEmpty()) {
                    continue;
                }
                Long number = waffle.stream()
                        .filter(n ->
                                Jurisdiction.getUSER_ID().equals(n.getString("CREATOR")) &&
                                        (StringUtils.isNotBlank(n.getString("STATE")) && ("4".equals(n.getString("STATE")) || "8".equals(n.getString("STATE")))) &&
                                        (StringUtils.isBlank(n.getString("FINAL_CHECK")) || "2".equals(n.getString("FINAL_CHECK")))
                        )
                        .count();
                if (number > 0) {
                    vector.put("checkout", 1);
                }
            }
        }
        map.put("varList", varList);
        map.put("page", page);
        map.put("result", errInfo);
        return map;
    }

    @RequestMapping(value = "/getFlow")
    @ResponseBody
    @SuppressWarnings("all")
    public Object getFlow() throws Exception {
        Map<String, Object> response = new HashMap<>();
        response.put("result", "success");
        PageData condition = this.getPageData();
        PageData safety = safetyenvironmentalService.findById(condition);
        if (safety == null || safety.size() <= 0) {
            response.put("result", "error");
            response.put("errorMessage", "数据异常");
        }
        // 1、整理基础数据
        Overseer overseer = new Overseer();
        List<Node> nodes = overseer.getSafetyWorkFlow();
        if(safety.getString("HIDDEN_ID") == null){
            nodes = nodes.stream().filter(item -> !"4,5".contains(item.getId())).collect(Collectors.toList());
        }
        // 初始话安全环保发起人、被检查人数据
        nodes.stream().forEach(n -> n.safety_creator_util(safety));
        // 2、整理特殊数据
        // 2、1检查人将检查状态

        List<PageData> inspectors = inspectorService.listAll(condition);
        nodes.stream()
                .filter(n -> "2".equals(n.getOrder()))
                .forEach(n -> n.safety_inspector_util(inspectors));
        //隐患指派流程
        if(safety.getString("HIDDEN_ID") != null) {
            List<PageData> hiddenz = safetyenvironmentalService.findByyin(condition);
            if (hiddenz != null && hiddenz.size() > 0) {
                nodes.stream()
                        .filter(n -> "4".equals(n.getOrder()))
                        .forEach(n -> n.safety_hiddenz(hiddenz));
            }
            // 2、2 隐患发现人状态
            condition.put("FOREIGN_ID", condition.getString("INSPECTION_ID"));
            List<PageData> hiddens = hiddenService.findByKey(condition);
            nodes.stream()
                    .filter(n -> "5".equals(n.getOrder()))
                    .forEach(n -> n.safety_hiddenCreator_util(hiddens));
        }
        // 2、3 考评人
        List<PageData> assess = assessService.findByMainId(condition);
        if (assess != null && assess.size() > 0) {
            nodes.stream()
                    .filter(n -> "6".equals(n.getOrder()))
                    .forEach(n -> n.safety_assessor_util(assess));
        }
        response.put("nodes", nodes);
        response.put("from", overseer.getSafetyForm());
        return response;
    }

    //隐患流程图的方法
    @RequestMapping(value = "/getFlowChart")
    @ResponseBody
    @SuppressWarnings("all")
    public Object getFlowChart() throws Exception {
        Map<String, Object> response = new HashMap<>();
        response.put("result", "success");
        PageData condition = this.getPageData();
        PageData safe = hiddenService.findById(condition);
        if (safe == null || safe.size() <= 0) {
            response.put("result", "error");
            response.put("errorMessage", "数据异常");
        }
        // 1、整理基础数据
        Overseer overseer = new Overseer();
        List<Node> nodes = overseer.getFlow();
        //初始数据 隐患发现人数据  安全环保检查验收人
        nodes.stream().forEach(n -> n.safe_creator(safe));
        //隐患确认人 确认信息
//        List<PageData> qr = hiddenService.findByQue(condition);
//        if (qr != null && qr.size() > 0) {
//            nodes.stream()
//                    .filter(n -> "1".equals(n.getOrder()))
//                    .forEach(n -> n.safe_qr(qr));
//        }
        //整改负责人 整改流程
        List<PageData> zg = hiddenService.findByYin(condition);
        if (zg != null && zg.size() > 0) {
            nodes.stream()
                    .filter(n -> "1".equals(n.getOrder()))
                    .forEach(n -> n.safe_zg(zg));
        }
        //特殊处置审核信息
//        List<PageData> ts = hiddenService.findByTs(condition);
//        if (ts != null && ts.size() > 0) {
//            nodes.stream()
//                    .filter(n -> "3".equals(n.getOrder()))
//                    .forEach(n -> n.safe_ts(ts));
//
//        }
//		//验收人 安环验收
        List<PageData> ys = hiddenCheckService.listAll(condition);
        if (ys != null && ys.size() > 0) {
            nodes.stream()
                    .filter(n -> "2".equals(n.getOrder()))
                    .forEach(n -> n.safe_ys(ys));
        }
        response.put("nodes", nodes);
        response.put("from", overseer.getFlowForm());
        return response;
    }
}
