package com.zcloud.controller.app.inspection;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.hotWorkApplication.NodeApp;
import com.zcloud.entity.hotWorkApplication.Overseer;
import com.zcloud.service.bus.NoticeCorpUtil;
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.system.DepartmentService;
import com.zcloud.util.*;
import org.apache.commons.lang.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

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

	@Autowired
	private SafetyEnvironmentalService safetyenvironmentalService;
	@Autowired
	private SafetyEnvironmentalInspectorService safetyEnvironmentalInspectorService;
	@Autowired
	private SafetyEnvironmentalExplainService explainService;
	@Autowired
	private HiddenService hiddenService;
	@Autowired
	private DepartmentService departmentService;
	@Resource
	private SafetyEnvironmentalInspectorService inspectorService;
	@Resource
	private SafetyEnvironmentalAssessService assessService;
	@Autowired
	private NoticeCorpUtil noticeCorpUtil;
	@Autowired
	private Smb smb;


	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(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());
		page.setPd(pd);
		List<PageData>	varList = safetyenvironmentalService.list(page);	//列出SafetyEnvironmental列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	@ResponseBody
	public Object add(@RequestParam(value="FFILE",required=false) MultipartFile file) 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", pd.getString("CREATOR"));	//检查发起人
		pd.put("ISDELETE", "0");	//是否删除(0:有效 1：删除)
		pd.put("CREATOR", pd.getString("CREATOR"));	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
		pd.put("OPERATOR", pd.getString("CREATOR"));	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		pd.put("CORPINFO_ID", pd.getString("CORPINFO_ID"));	//企业ID
		pd.put("ACTION_USER", pd.getString("ACTION_USER"));	//操作人
		String ffile = DateUtil.getDays();
		if (file != null && StringUtils.isNotBlank(pd.getString("INSPECTION_USER_OPINION"))){
			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 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);
			pd.put("CONFIRM_MESSAGE",pd.getString("INSPECTION_USER_OPINION"));
			pd.put("CONFIRM_MESSAGE_TIME",DateUtil.date2Str(new Date()));
		}
		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")
	@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")
	@ResponseBody
	public Object edit(@RequestParam(value="FFILE",required=false) MultipartFile file) 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", pd.getString("OPERATOR"));	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		pd.put("ACTION_USER", pd.getString("ACTION_USER"));	//操作人
		String ffile = DateUtil.getDays();
		if (file != null && StringUtils.isNotBlank(pd.getString("INSPECTION_USER_OPINION"))){
			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 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);
			pd.put("CONFIRM_MESSAGE",pd.getString("INSPECTION_USER_OPINION"));
			pd.put("CONFIRM_MESSAGE_TIME",DateUtil.date2Str(new Date()));
		}
		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(@RequestParam(value="FFILE",required=false) MultipartFile[] files) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if (files != null && files.length > 0) {
			MultipartFile file = files[0];
			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("INSPECTION_ORIGINATOR_SIGN_IMG",  Const.FILEPATHFILE + pd.getString("CORPINFO_ID") + "/" + ffile + "/" + fileName);
		}
		safetyenvironmentalService.explain(pd);
		pd.put("inspector",pd.getString("OPERATOR"));
		noticeCorpUtil.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("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		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;
	}

	/**安全环保检查待办作业数统计
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/countCheck")
	@ResponseBody
	public Object countCheck() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData confirmCount = safetyEnvironmentalInspectorService.confirmCount(pd);  //检查人确认数
		PageData checkedCount = safetyenvironmentalService.checkedCount(pd);  //被检查人签字数
		PageData repulseCount = safetyenvironmentalService.repulseCount(pd); //打回数
		PageData repulseAndCheckCount = safetyenvironmentalService.repulseAndCheckCountCount(pd); //指派+验收数

		map.put("result", errInfo);
		map.put("confirmCount", confirmCount);
		map.put("checkedCount",checkedCount);
		map.put("repulseCount",repulseCount);
		map.put("repulseAndCheckCount",repulseAndCheckCount);
		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;
	}

	/**一公司app首页安全环保检查统计
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/countHome")
	@ResponseBody
	public Object countHome() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData count = safetyEnvironmentalInspectorService.countHome(pd);  //一公司app首页安全环保检查统计
		map.put("result", errInfo);
		map.put("count", count);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/pleadList")
	@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());
		page.setPd(pd);
		List<PageData>	varList = safetyenvironmentalService.pleadList(page);	//列出SafetyEnvironmental列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}


	/**列表
	 * 规则: 如果当前人是，被检查人，检查人，参与人则可以查询到此条数据
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/checkList")
	@ResponseBody
	public Object checkList(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("waffle",pd.getString("ARCHIVE_USER_ID"));
		page.setPd(pd);
		List<PageData>	varList = safetyenvironmentalService.checkList(page);	//列出SafetyEnvironmental列表
		/* 针对验收部分特殊处理 */
		String user_id = pd.getString("ARCHIVE_USER_ID");
		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);  //d
				if (waffle == null || waffle.isEmpty()){
					continue;
				}
				Long number = waffle.stream()
						.filter(n ->
								user_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="/showFlowChart")
	@ResponseBody
	public  Object showFlowChart() throws Exception{
		HashMap<String, Object> response = new HashMap<>();
		response.put("result","success");
		PageData condition = this.getPageData();
		condition.put("INSPECTION_ID",condition.getString("ID"));
		PageData safety = safetyenvironmentalService.findById(condition);
		if (safety == null || safety.size() <= 0) {
			response.put("result", "error");
			response.put("errorMessage", "数据异常");
		}
		// 1、整理基础数据
		Overseer overseer = new Overseer();
		List<NodeApp> nodes = overseer.getSafetyAppWorkFlow();
		// 初始话安全环保发起人、被检查人数据
		nodes.get(0).safety_order(safety);
		if(safety.getString("HIDDEN_ID") == null){
			nodes = nodes.stream().filter(item -> !"隐患指派,隐患发现人验收".contains(item.getTitle())).collect(Collectors.toList());
		}
		nodes.stream().forEach(n -> n.safety_creator_util(safety));
		for (NodeApp nodeApp : nodes) {
			if (StringUtils.isNotBlank(nodeApp.getActive()))
				overseer.setSafetyAppVector(nodeApp.getOrder());
		}
		// 2、整理特殊数据
		// 2、1检查人将检查状态
		if ("1,2,3,4".contains(safety.getString("order"))) {
			List<PageData> inspectors = inspectorService.listAll(condition);
			nodes.stream()
					.filter(n -> "1".equals(n.getOrder()))
					.forEach(n -> n.safety_inspector_util(inspectors));
		}


		//隐患指派流程
		if(safety.getString("HIDDEN_ID") != null){
			if ("3,4".contains(safety.getString("order"))) {
				List<PageData> hiddenz = safetyenvironmentalService.findByyin(condition);
				if (hiddenz != null && hiddenz.size() > 0) {
					nodes.stream()
							.filter(n -> "3".equals(n.getOrder()))
							.forEach(n -> n.safety_hiddenz(hiddenz));
				}
			}
		}

		if ("4".equals(safety.getString("order"))) {
			// 2、2 隐患发现人状态
			condition.put("FOREIGN_ID", condition.getString("INSPECTION_ID"));
			List<PageData> hiddenList = hiddenService.findByKey(condition);
			if(hiddenList != null && hiddenList.size()>0){
				condition.put("HIDDEN_ID", hiddenList.get(0).getString("HIDDEN_ID"));
				List<PageData> hiddens = hiddenService.findByKeyHiddencheck(condition);
				List<PageData> newHiddens = hiddens.stream()
						.filter(pd -> "1".equals(pd.getString("STATUS")))
						.collect(Collectors.toList());

				nodes.stream()
						.filter(n -> "4".equals(n.getOrder()))
						.forEach(n -> n.safety_hiddenCreator_util(newHiddens));
			}

		}
		// 2、3 考评人
//		List<PageData> assess = assessService.findByMainId(condition);
//		if (assess != null && assess.size() > 0) {
//			nodes.stream()
//					.filter(n -> "5".equals(n.getOrder()))
//					.forEach(n -> n.safety_assessor_util(assess));
//		}
		response.put("varList", nodes);
		response.put("active" ,overseer.getSafetyAppVector());
		return response;
	}
}
