package com.zcloud.controller.hiddenDangerCheckStandard;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.check.*;
import com.zcloud.service.corp.CorpInfoService;
import com.zcloud.service.hidden.HiddenService;
import com.zcloud.service.hiddenDangerCheckStandard.*;
import com.zcloud.service.offduty.OffDutyService;
import com.zcloud.service.risk.IdentificationPartsService;
import com.zcloud.service.sms.MSMLoginService;
import com.zcloud.service.sms.SMSManagementService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.ImgFilesService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.DateUtil;
import com.zcloud.util.ObjectExcelView;
import com.zcloud.util.SendMessageUtil;
import com.zcloud.util.Tools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * 说明：清单检查记录 作者：luoxiaobao 时间：2021-01-04 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/app/customCheckRecord")
public class AppCustomCheckRecordController extends BaseController {

	@Autowired
	private CustomCheckRecordService customCheckRecordService;
	@Autowired
	private CustomCheckRecordItemService customCheckRecordItemService;
	@Autowired
	private CustomItemService customItemService;
	@Autowired
	private CustomService customService;

	@Autowired
	private CustomHiddenService customHiddenService;
	@Autowired
	private CustomCheckUserService customCheckUserService;
	@Autowired
	private CorpInfoService corpinfoService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private SMSManagementService smsmanagementService;
	@Autowired
	private MSMLoginService msmloginService;
	@Autowired
	private IdentificationPartsService identificationPartsService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private ImgFilesService imgFilesService;
	@Autowired
	private OffDutyService offDutyService;
	@Autowired
	private SysDateService sysDateService;
	@Autowired
	private ListDisableTimeService listDisableTimeService;
	@Autowired
	private SendMessageUtil sendMessageUtil;
	/**
	 * 新增
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单排查",instructionsType = "新增记录")
	public Object add() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		if (pd.get("CHECKRECORD_ID") == null || Tools.isEmpty(pd.getString("CHECKRECORD_ID"))) {
			pd.put("CHECKRECORD_ID", this.get32UUID()); // 主键
			pd.put("ISDELETE", "0"); // 是否删除
			pd.put("CREATTIME", DateUtil.date2Str(new Date())); // 创建时间
			pd.put("FINISHED", "0"); // 是否完成
			pd.put("ISSTATISTICS", "1");
			pd.put("TYPE", "1");
			customCheckRecordService.save(pd);
		}

		if (pd.get("ITEMS") != null && !pd.get("ITEMS").equals("")) {
			List<JSONObject> list = (List<JSONObject>) JSON.parse(pd.get("ITEMS").toString());
			for (JSONObject json : list) {
				PageData item = new PageData();
				item.put("RECORDITEM_ID", json.get("RECORDITEM_ID")); // 主键
				item = customCheckRecordItemService.findById(item);
				if (item == null) {
					item = new PageData();
					item.put("RECORDITEM_ID", json.get("RECORDITEM_ID")); // 主键
					item.put("CUSTOM_ITEM_ID", json.get("CUSTOM_ITEM_ID"));
					PageData chei = customItemService.findById(item);
					item.put("ISNORMAL", json.get("ISNORMAL"));
					item.put("CHECK_RESULT", json.get("CHECK_RESULT"));
					item.put("CHECKRECORD_ID", pd.get("CHECKRECORD_ID"));
					item.put("CUSTOM_ID", pd.get("CUSTOM_ID"));
					item.put("CHECK_CATEGORY", chei.get("CHECK_CATEGORY"));
					item.put("CHECK_CATEGORY_NAME", chei.get("CHECK_CATEGORY_NAME"));
					item.put("CHECK_ITEM", chei.get("CHECK_ITEM"));
					item.put("CHECK_ITEM_NAME", chei.get("CHECK_ITEM_NAME"));
					item.put("CHECK_CONTENT", chei.get("CHECK_CONTENT"));
					item.put("CHECK_STANDARD", chei.get("CHECK_STANDARD"));
					item.put("REFERENCE_BASIS", chei.get("REFERENCE_BASIS"));
					item.put("COMMON_ITEM_SORT", chei.get("COMMON_ITEM_SORT"));
					item.put("LONGITUDE", pd.get("LONGITUDE"));
					item.put("LATITUDE", pd.get("LATITUDE"));
					item.put("CORPINFO_ID", pd.get("CORPINFO_ID"));
					item.put("ISDELETE", pd.get("0"));
					item.put("CREATOR_ID", pd.get("USER_ID"));
					item.put("CREATOR_NAME", pd.get("CREATOR"));
					item.put("CREATE_TIME", DateUtil.date2Str(new Date()));
					customCheckRecordItemService.save(item);
				} else {
					item.put("LONGITUDE", pd.get("LONGITUDE"));
					item.put("LATITUDE", pd.get("LATITUDE"));
					item.put("ISNORMAL", json.get("ISNORMAL"));
					item.put("CHECK_RESULT", json.get("CHECK_RESULT"));
					customCheckRecordItemService.edit(item);
				}

			}
		}
		if (pd.get("IDS") != null && !pd.get("IDS").equals("")) {
			String ids = pd.get("IDS").toString();
			String ArrayDATA_IDS[] = ids.split(",");
			PageData hiddens = new PageData();
			hiddens.put("CHECKRECORD_ID", pd.get("CHECKRECORD_ID"));
			PageData list = customService.findById(pd);
			if(list.getString("TYPE").equals("listType0001")){
				hiddens.put("STATE", "0");
			}else{
				hiddens.put("STATE", "1");
			}
			hiddens.put("IDS", ArrayDATA_IDS);
			customHiddenService.updateAll(hiddens);
		}
		map.put("result", errInfo);
		return map;
	}








	/**
	 * 完成检查
	 *
	 * @param
	 * @throws Exception
	 */
	// /app/checkrecord/finish
	@RequestMapping(value = "/finish")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "完成检查")
	public Object finish() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData sysdate = new PageData();
		sysdate.put("DATE", pd.get("CHECK_TIME"));
		sysdate = sysDateService.findByDate(sysdate);
		PageData list = customService.findById(pd);
		String periodstart = "";
		String periodend = "";
		if(!list.get("TYPE").toString().equals("listType0005")) {
			switch (list.get("PERIOD").toString()) {
			case "checkPeriod0001":
				periodstart = sysdate.getString("DAY_START");
				periodend = sysdate.getString("DAY_END");
				break;
			case "checkPeriod0002":
				periodstart = sysdate.getString("WEEK_START");
				periodend = sysdate.getString("WEEK_END");
				break;
			case "checkPeriod0003":
				periodstart = sysdate.getString("XUN_START");
				periodend = sysdate.getString("XUN_END");
				break;
			case "checkPeriod0004":
				periodstart = sysdate.getString("MONTH_START");
				periodend = sysdate.getString("MONTH_END");
				break;
			case "checkPeriod0005":
				periodstart = sysdate.getString("QUARTER_START");
				periodend = sysdate.getString("QUARTER_END");
				break;
			case "checkPeriod0006":
				periodstart = sysdate.getString("YEAR_START");
				periodend = sysdate.getString("YEAR_END");
				break;
			case "checkPeriod0007":
				periodstart = sysdate.getString("HALFYEAR_START");
				periodend = sysdate.getString("HALFYEAR_END");
				break;
			}
			pd.put("PERIODSTART", periodstart);
			pd.put("PERIODEND", periodend);
		} else {
			pd.put("PERIODSTART", list.get("START_DATE"));
			pd.put("PERIODEND", list.get("END_DATE"));
		}
		pd.put("FINISHED", "1"); // 是否完成
		customCheckRecordService.edit(pd);
		customCheckUserService.delete(pd);
		if (pd.get("OTHER") != null && !pd.get("OTHER").equals("")) {
			List<JSONObject> list1 = (List<JSONObject>) JSON.parse(pd.get("OTHER").toString());
			for (JSONObject json : list1) {
				if (json.get("DEPARTMENT_ID") != null && json.get("DEPARTMENT_ID") != "" && json.get("USER_ID") != null
						&& json.get("USER_ID") != "") {
					PageData other = new PageData();
					other.put("CHECKUSER_ID", this.get32UUID()); // 主键
					other.put("CHECKRECORD_ID", pd.get("CHECKRECORD_ID"));
					other.put("DEPARTMENT_ID", json.get("DEPARTMENT_ID"));
					other.put("USER_ID", json.get("USER_ID"));
					other.put("DEPARTMENT_NAME", json.get("DEPARTMENT_NAME"));
					other.put("USER_NAME", json.get("USER_NAME"));
					customCheckUserService.save(other);
				}
			}
		}
		customHiddenService.submit(pd);// 清单内隐患提交
		customHiddenService.submitList(pd);// 其他隐患提交
		List<PageData> hList = customHiddenService.getHiddenByRecord(pd);// 查询隐患，并发短信
		if (hList.size() > 0) {
			for (PageData h : hList) {
				if ("2".equals(h.get("RECTIFICATIONTYPE").toString())) {// 给整改人发送短信，暂时先用发验证码代替
					// 发短信
					PageData mes = new PageData();
					mes.put("RECEIVER_ID", h.get("RECTIFICATIONOR"));// 收信人userid
					mes.put("templateCode", "SMS_215820677");// 短信模板编码
					mes.put("CORPINFO_ID", pd.get("CORPINFO_ID"));// 企业id

					// 参数集合
					List<PageData> paramsList = new ArrayList<PageData>();
					// 第1个参数
					PageData params1 = new PageData();
					params1.put("name", "time");// 存入短信模板中的参数名称
					params1.put("value", h.get("RECTIFICATIONDEADLINE"));// 存入上面参数名称所传递的值
					paramsList.add(params1);

					sendMessageUtil.sendMessages(mes, paramsList);
				}
			}
		}

		map.put("result", errInfo);
		return map;
	}

	@RequestMapping(value = "/goMapWeui")
	@ResponseBody
	public Object goMapWeui() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData checkrecord = customCheckRecordService.findById(pd);
		List<PageData> varList = customCheckRecordItemService.listAllForMap(checkrecord);
		pd.put("CORPINFO_ID", checkrecord.get("CORPINFO_ID"));
		PageData cinfo = corpinfoService.findById(pd);
		checkrecord.put("FIND_CHECKRECORD_ID", checkrecord.get("CHECKRECORD_ID"));
		List<PageData> hdList = customHiddenService.listAll(checkrecord);
		map.put("varList", varList);
		map.put("hdList", hdList);
		map.put("pd", pd);
		map.put("cinfo", cinfo);
		map.put("checkrecord", checkrecord);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 删除
	 *
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value = "/delete")
	// @RequiresPermissions("checkrecord:del")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "删除检查记录")
	public Object delete() throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		customCheckRecordService.delete(pd);
		map.put("result", errInfo); // 返回结果
		return map;
	}

	/**
	 * 修改
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/edit")
	// @RequiresPermissions("checkrecord:edit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "修改")
	public Object edit() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		customCheckRecordService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 指定辨识部位检查记录
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/recordByIde")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "指定辨识部位检查记录")
	public Object recordByIde() 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());
		List<PageData> varList = customCheckRecordService.recordByIde(pd);
		map.put("varList", varList);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 列表
	 *
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "检查记录列表")
	public Object list() 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());
		PageData ls = customService.findById(pd);

		List<PageData> varList = customCheckRecordService.appdatalist(pd);
		map.put("varList", varList);
		map.put("ls", ls);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 去修改页面获取数据
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEdit")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "去修改页面获取数据")
	public Object goEdit() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd = customCheckRecordService.findById(pd); // 根据ID读取
		PageData users = customCheckUserService.getCheckUser(pd);
		List<PageData> varList = customCheckRecordItemService.listAll(pd);
		pd.put("USERS", users.get("USERS"));
		PageData pd2 = new PageData();
		pd2.put("FOREIGN_KEY",pd.get("CHECKRECORD_ID"));
		pd2.put("TYPE","13");
		List<PageData> qianming = imgFilesService.listAll(pd2);


		map.put("qianming", qianming);
		map.put("varList", varList);
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}


	/**
	 * 去修改页面获取数据Weui
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEditWeui")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "去修改页面获取数据")
	public Object goEditWeui() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String IDENTIFICATION_ID = pd.getString("IDENTIFICATION_ID");
		pd = customCheckRecordService.findById(pd); // 根据ID读取
		PageData users = customCheckUserService.getCheckUser(pd);
		pd.put("IDENTIFICATION_ID", IDENTIFICATION_ID);
		List<PageData> varList = customCheckRecordItemService.listAll(pd);
		PageData idData  = new PageData();
		idData.put("IDENTIFICATIONPARTS_ID", IDENTIFICATION_ID);
		idData = identificationPartsService.findById(idData);
		pd.put("USERS", users.get("USERS"));
		map.put("varList", varList);
		map.put("pd", pd);
		map.put("idData", idData);
		map.put("result", errInfo);
		return map;
	}

	/**
	 * 批量删除
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/deleteAll")
	// @RequiresPermissions("checkrecord:del")
	@ResponseBody
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "批量删除")
	public Object deleteAll() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DATA_IDS = pd.getString("DATA_IDS");
		if (Tools.notEmpty(DATA_IDS)) {
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			customCheckRecordService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		} else {
			errInfo = "error";
		}
		map.put("result", errInfo); // 返回结果
		return map;
	}

	/**
	 * 导出到excel
	 *
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value = "/excel")
	@LogAnno(menuType= "手机",menuServer= "隐患排查",instructionsOperate = "清单检查情况",instructionsType = "导出到excel")
	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("清单ID"); // 1
		titles.add("清单名称"); // 2
		titles.add("企业"); // 3
		titles.add("添加人"); // 4
		titles.add("创建时间"); // 5
		titles.add("修改人"); // 6
		titles.add("修改时间"); // 7
		titles.add("是否删除"); // 8
		dataMap.put("titles", titles);
		List<PageData> varOList = customCheckRecordService.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("CUSTOM_ID")); // 1
			vpd.put("var2", varOList.get(i).getString("LIST_NAME")); // 2
			vpd.put("var3", varOList.get(i).getString("CORPINFO_ID")); // 3
			vpd.put("var4", varOList.get(i).getString("CREATOR")); // 4
			vpd.put("var5", varOList.get(i).getString("CREATTIME")); // 5
			vpd.put("var6", varOList.get(i).getString("OPERATOR")); // 6
			vpd.put("var7", varOList.get(i).getString("OPERATTIME")); // 7
			vpd.put("var8", varOList.get(i).get("ISDELETE").toString()); // 8
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv, dataMap);
		return mv;
	}

	@RequestMapping(value = "/goMap")
	@ResponseBody
	public Object goMap() throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		PageData checkrecord = customCheckRecordService.findById(pd);
		List<PageData> varList = customCheckRecordItemService.listAllForMap(checkrecord);
		PageData cinfo = corpinfoService.findById(pd);
		checkrecord.put("FIND_CHECKRECORD_ID", checkrecord.get("CHECKRECORD_ID"));
		List<PageData> hdList = customHiddenService.listAll(checkrecord);
		map.put("varList", varList);
		map.put("hdList", hdList);
		map.put("pd", pd);
		map.put("cinfo", cinfo);
		map.put("checkrecord", checkrecord);
		map.put("result", errInfo);
		return map;
	}

}
