package com.zcloud.controller.risk;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.risk.IdentificationPartsService;
import com.zcloud.service.risk.RiskUnitService;
import com.zcloud.service.system.DepartmentService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.*;
import net.sf.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.*;

/**
 * 说明：风险单元
 * 作者：luoxiaobao
 * 时间：2020-12-30
 * 官网：www.zcloudchina.com
 */
@Controller
@RequestMapping("/riskunit")
public class RiskUnitController extends BaseController {

	@Autowired
	private RiskUnitService riskunitService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private IdentificationPartsService identificationpartsService;
	@Autowired
	private UsersService usersService;

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("riskunit:add")
	@ResponseBody
	@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();
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		pd.put("CHECK_NAME", pd.getString("RISKUNITNAME"));
		//pd.put("DEPARTMENT_ID",Jurisdiction.getDEPARTMENT_ID());
		List<PageData> list = riskunitService.listAll(pd);
		if(list!=null&&list.size()>0) {
//			map.put("result", "failed");
//			map.put("exception", "风险点（单元）已存在，请修改后重试");
//			return map;
			errInfo = "error";
			map.put("result", errInfo);
			map.put("msg", "风险点（单元）已存在，请修改后重试");
			return map;

		}
//		errInfo = "error";
//		map.put("result", errInfo);
//		map.put("msg", "目录有子集，不允许删除");
		pd.put("RISKUNIT_ID", this.get32UUID());	//主键
		pd.put("CREATOR", Jurisdiction.getUsername());	//添加人
		pd.put("CREATTIME", DateUtil.date2Str(new Date()));	//添加时间
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间

		pd.put("ISDELETE", "0");	//是否删除 1-是  0-否
		riskunitService.save(pd);
		map.put("result", errInfo);
		return map;
	}


	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goAdd")
	@ResponseBody
	public Object goAdd() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
//		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);

		//获取部门下拉树
		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept=this.departmentService.findByCorpId(dept);
		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

		PageData node = new PageData();
		node.put("id", dept.get("DEPARTMENT_ID"));
		node.put("parentId", dept.get("PARENT_ID"));
		node.put("name", dept.get("NAME"));
		node.put("icon", "../../../assets/images/user.gif");
		zdepartmentPdList.add(node);
		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));

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

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("riskunit: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();
		List<PageData> list = identificationpartsService.listAll(pd);
		if(list!=null && list.size()>0) {
//			map.put("result", "failed");				//返回结果
			map.put("msg", "该风险点(单元)下有辨识部位，请删除所有的辨识部位再删除");
			return map;
		}
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		riskunitService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("riskunit: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();
		pd.put("CHECK_NAME", pd.getString("NAME"));
		List<PageData> list = riskunitService.listAll(pd);
		if(list!=null&&list.size()>0 &&
				!list.get(0).getString("RISKUNIT_ID").equals(pd.getString("RISKUNIT_ID"))) {
			map.put("result", "failed");
			map.put("msg", "风险点（单元）已存在，请修改后重试");
			return map;
		}
		pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
		pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
		riskunitService.edit(pd);
		map.put("result", errInfo);
		return map;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("riskunit:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "列表")
	public Object list(Page page) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		PageData npd = new PageData();
		pd = this.getPageData();
		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
		if(Tools.notEmpty(KEYWORDS))npd.put("KEYWORDS", KEYWORDS.trim());
		npd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		npd.put("ISMAIN", Jurisdiction.getIS_MAIN());
		npd.put("ISSUPERVISE", Jurisdiction.getISSUPERVISE());
		npd.put("DEPARTMENT_ID", Jurisdiction.getDEPARTMENT_ID());
		pd.put("USER_ID",Jurisdiction.getUSER_ID());
		PageData cpd = new PageData();
		cpd = usersService.findById(pd);
		npd.put("ISLEADER", cpd.getString("ISLEADER"));
		if(cpd.getString("ISLEADER") != null && cpd.getString("ISLEADER").equals("1")){
			String DEPARTMENT_ID = npd.getString("DEPARTMENT_ID");
			String ids = departmentService.getDEPARTMENT_IDS(DEPARTMENT_ID);
			ids=npd.getString("DEPARTMENT_ID")+","+ids;   //把自己部门插入进去
			if(ids!=null && Tools.notEmpty(ids)&& ids.lastIndexOf(",")>-1) {
				ids = ids.substring(0,ids.lastIndexOf(","));
				npd.put("DEPARTMENT_IDS", ids.split(","));
			}else {
				npd.put("DEPARTMENT_IDS", DEPARTMENT_ID);
			}
		}
		String DEPTIDS = pd.getString("DEPTIDS");
		if(Tools.notEmpty(DEPTIDS)) {
			String DEPT_IDS[] = DEPTIDS.split(",");
			npd.put("DEPT_IDS", DEPT_IDS);
		}

		page.setPd(npd);
		List<PageData>	varList = riskunitService.list(page);	//列出RiskUnit列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("riskunit:edit")
	@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 = riskunitService.findById(pd);	//根据ID读取

		//获取部门下拉树
//		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
//		String ZDEPARTMENT_ID = Jurisdiction.getDEPARTMENT_ID();
//		ZDEPARTMENT_ID = "".equals(ZDEPARTMENT_ID)?"0":ZDEPARTMENT_ID;
//		PageData dept = new PageData();
//		dept.put("DEPARTMENT_ID",ZDEPARTMENT_ID);
//		dept=this.departmentService.findById(dept);

		//获取部门下拉树
		List<PageData> zdepartmentPdList = new ArrayList<PageData>();
		PageData dept = new PageData();
		dept.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		dept=this.departmentService.findByCorpId(dept);
		String ZDEPARTMENT_ID = dept.getString("DEPARTMENT_ID");

		PageData node = new PageData();
		node.put("id", dept.get("DEPARTMENT_ID"));
		node.put("parentId", dept.get("PARENT_ID"));
		node.put("name", dept.get("NAME"));
		node.put("icon", "../../../assets/images/user.gif");
		zdepartmentPdList.add(node);
		JSONArray arr = JSONArray.fromObject(departmentService.listAllDepartmentToSelect(ZDEPARTMENT_ID,zdepartmentPdList));
		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
		map.put("pd", pd);
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("riskunit:del")
	@ResponseBody
	public Object deleteAll() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		String err="";
		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(",");
			for (String id : ArrayDATA_IDS) {
				PageData unit = new PageData();
				unit.put("RISKUNIT_ID", id);
				List<PageData> list = identificationpartsService.listAll(unit);
//				if(list!=null && list.size()>0) {
//					continue;
//				}
				if(list!=null && list.size()>0) {
//			map.put("result", "failed");				//返回结果
					map.put("msg", "该风险点(单元)下有辨识部位，请删除所有的辨识部位再删除");
					return map;
				}
				pd.put("RISKUNIT_ID", id);
				pd.put("OPERATOR", Jurisdiction.getUsername());	//修改人
				pd.put("OPERATTIME", DateUtil.date2Str(new Date()));	//修改时间
				riskunitService.delete(pd);
			}
//			riskunitService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/excel")
//	// @RequiresPermissions("toExcel")
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "导出到excel")
	public ModelAndView exportExcel() throws Exception{
		ModelAndView mv = new ModelAndView();
		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(",");
			pd.put("ArrayDATA_IDS",ArrayDATA_IDS);
		}
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
		Map<String,Object> dataMap = new HashMap<String,Object>();
		List<String> titles = new ArrayList<String>();
		titles.add("所属企业");	//1
		titles.add("风险点（单元）名称");	//2
		titles.add("所属部门");	//3
		dataMap.put("titles", titles);
		List<PageData> varOList = riskunitService.listOut(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("CORP_NAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("RISKUNITNAME"));	    //2
			vpd.put("var3", varOList.get(i).getString("DEPT_NAME"));	    //6
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/getRisByUnitId")
	// @RequiresPermissions("riskunit:list")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "查看风险点详情信息")
	public Object getRisByUnitId(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());
		pd.put("RISK_UNIT_ID", pd.getString("RISK_UNIT_ID"));
		page.setPd(pd);
		List<PageData>	varList = riskunitService.getRisByUnitId(page);	//列出RiskUnit列表
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
//	@RequestMapping(value="/excelModel")
////	// @RequiresPermissions("toExcel")
//	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "导出模板")
//	public void exportExcelModel(HttpServletResponse response) throws Exception{
//
//		FileDownload.fileDownload(response, PathUtil.getProjectpath() + Const.FILEPATHFILE + "riskunitExcelTemplate.xls", "riskunitExcelTemplate.xls");
//	}

	/**从EXCEL导入到数据库
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/readExcel")
	@SuppressWarnings("unchecked")
	@ResponseBody
	@Transactional
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "上传附件")
	public Object readExcel(@RequestParam(value = "FFILE", required = false) MultipartFile file) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		String errInfo = "success";
		StringBuffer errorStr = new StringBuffer();
		if (null != file && !file.isEmpty()) {
			File tempFile = new File(file.getOriginalFilename()); //新建file
			FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile); //将MultipartFile复制到File
			List<PageData> listPd = (List) ObjectExcelRead.readExcel(tempFile, 1, 0, 0); // 执行读EXCEL操作,读出的数据导入List
																									// 2:从第3行开始；0:从第A列开始；0:第0个sheet
			/**
			 * var0 :风险点（单元） var1 :所属部门
			 */

			try {
				if (listPd.size() < 1) {
					map.put("result", "error"); // 返回结果
					map.put("resultStr", "Excel数据为空，请检查数据后，重新上传！");
					FileUtils.deleteQuietly(tempFile);//删除临时文件
					return map;
				}
				List<PageData> riskunitList = new ArrayList<>();
				PageData pdCorpId = new PageData();
				pdCorpId.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
				pdCorpId.put("ISDELETE", "0");
				List<PageData> departAll = departmentService.listAll(pdCorpId);
				Map<String, Object> departMapAll = new HashMap<>();
				for (PageData pageData : departAll) {
					departMapAll.put(Tools.excelHandle(pageData.getString("NAME")), pageData);
				}
				List<PageData> riskunitListAll = riskunitService.listAll(pdCorpId);
				Map<String, Object> riskunitMapAll = new HashMap<>();
				for (PageData pageData : riskunitListAll) {
					riskunitMapAll.put(pageData.getString("DEPARTMENT_ID") + Tools.excelHandle(pageData.getString("RISKUNITNAME")),
							pageData);
				}
				List<String> header = new ArrayList<>();
				header.add("所属部门");
				header.add("风险点（单元）");
				Map<String, Object> hasRiskUnit = new HashMap<>();
				int succeeNum = 1;
				for (PageData lpd : listPd) {
					succeeNum++;
					for (int i = 0; i < header.size(); i++) {
						if (!lpd.containsKey("var" + i)) {
							errorStr.append("<p>第" + succeeNum + "行的\"" + header.get(i) + "\"无数据</p>");
							continue;
						}
						if (Tools.isEmpty(lpd.get("var" + i))) {
							errorStr.append("<p>第" + succeeNum + "行的\"" + header.get(i) + "\"无数据</p>");
							continue;
						}
					}

					String departVar = Tools.isEmpty(lpd.get("var0")) ? "" : Tools.excelHandle(lpd.get("var0"));
					String riskNameVar = Tools.isEmpty(lpd.get("var1")) ? "" : Tools.excelHandle(lpd.get("var1"));

					if (!departMapAll.containsKey(departVar)) {
						errorStr.append(
								"<p>第" + succeeNum + "行:" + "未找到名称为\"" + departVar + "\"的" + header.get(0) + "</p>");
						continue;
					}
					PageData depart = (PageData) departMapAll.get(departVar);
					if (riskunitMapAll.containsKey(depart.getString("DEPARTMENT_ID") + riskNameVar)) {
						errorStr.append("<p>第" + succeeNum + "行:" + "在" + departVar + "部门下已经存在名称为\"" + riskNameVar + "\"的"
								+ header.get(1) + "</p>");
						continue;
					}
					if (hasRiskUnit.containsKey(departVar + riskNameVar)) {
						errorStr.append("<p>第" + succeeNum + "行:" + "数据重复，请重新检查内容！" + "</p>");
						continue;
					}
					hasRiskUnit.put(departVar + riskNameVar, "1");
					PageData riskunit = new PageData();
					riskunit.put("DEPARTMENT_ID", depart.getString("DEPARTMENT_ID"));
					riskunit.put("RISKUNITNAME", lpd.get("var1"));
					riskunit.put("RISKUNIT_ID", this.get32UUID());
					riskunit.put("ISDELETE", "0");
					riskunit.put("CREATOR", Jurisdiction.getUsername());
					riskunit.put("CREATTIME", DateUtil.date2Str(new Date()));
					riskunit.put("OPERATOR", Jurisdiction.getUsername());
					riskunit.put("OPERATTIME", DateUtil.date2Str(new Date()));
					riskunit.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());
					riskunitList.add(riskunit);
				}
				if (Tools.isEmpty(errorStr.toString())) {
					for (PageData riskunit : riskunitList) {
						riskunitService.save(riskunit);
					}
					errorStr.append("成功导入" + riskunitList.size() + "条数据!");
				} else {
					errInfo = "error";
				}

				FileUtils.deleteQuietly(tempFile);//删除临时文件
			} catch (Exception e) {
				map.put("result", "fail"); // 返回结果
				map.put("resultStr", errorStr.toString());
				FileUtils.deleteQuietly(tempFile);//删除临时文件
				return map;
			}
		}
		map.put("result", "success");				//返回结果
		map.put("resultType", errInfo);				//返回message类型
		map.put("isExcel","1");				//返回类型
		map.put("resultStr", errorStr.toString());
		return map;
	}



	 /**判断同一个部门下，风险点（单元）名字	是否重复
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/hasName")
	@ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "风险管控",instructionsOperate = "风险点（单元）",instructionsType = "判断同一个部门下，风险点（单元）名字\t是否重复")
	public Object hasName() throws Exception{
		Map<String, Object> map = new HashMap<>();
		PageData pd = new PageData();
		pd = this.getPageData();
		String errInfo = "success";
		PageData risk = new PageData();

		risk.put("DEPARTMENT_ID", pd.getString("DEPARTMENT_ID"));
		risk.put("CHECK_NAME",pd.getString("CHECK_NAME"));
		List<PageData> list = riskunitService.listAll(risk);
		if(list.size()>0) {
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		map.put("count", list.size());
		return map;
	}
}
