package com.zcloud.controller.system;

import com.zcloud.controller.base.BaseController;
import com.zcloud.entity.Page;
import com.zcloud.entity.PageData;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.system.DictionariesCorpService;
import com.zcloud.service.system.UserInfoService;
import com.zcloud.service.system.UsersService;
import com.zcloud.util.Jurisdiction;
import com.zcloud.util.Tools;
import net.sf.json.JSONArray;
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：数据字典处理类(企业级)
 * 作者：luoxiaobao
 * 官网：www.qdkjchina.com
 */
@Controller
	@RequestMapping("/dictionariesCorp")
public class DictionariesCorpController extends BaseController {

	@Autowired
	private DictionariesCorpService dictionariesCorpService;
	@Autowired
	private UsersService usersService;
	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 显示列表ztree
	 * @return
	 */
	@RequestMapping(value="/listAllDict")
	// @RequiresPermissions("dictionaries:list")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "监测类型管理",instructionsType = "列表")
	public Object listAllDict()throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", "0");	//企业ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDict(pd));
		String json = arr.toString();
		json = json.replaceAll("DICTIONARIES_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "url");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}

//	/**列表
//	 * @param page
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/list")
//	// @RequiresPermissions("dictionaries: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();
//		pd = this.getPageData();
//		String KEYWORDS = pd.getString("KEYWORDS");						//关键词检索条件
//		if(Tools.notEmpty(KEYWORDS))pd.put("KEYWORDS", KEYWORDS.trim());
//		String DICTIONARIES_ID = null == pd.get("DICTIONARIES_ID")?"":pd.get("DICTIONARIES_ID").toString();
//		pd.put("DICTIONARIES_ID", DICTIONARIES_ID);						//上级ID
//		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
//		page.setPd(pd);
//		List<PageData>	varList = dictionariesCorpService.list(page);		//列出Dictionaries列表
//		if("".equals(DICTIONARIES_ID) || "0".equals(DICTIONARIES_ID)) {
//			map.put("PARENT_ID", "0");									//上级ID
//		}else {
//			map.put("PARENT_ID", dictionariesCorpService.findById(pd).getString("PARENT_ID"));	//上级ID
//		}
//		map.put("varList", varList);
//		map.put("page", page);
//		map.put("result", errInfo);
//		return map;
//	}
	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	// @RequiresPermissions("dictionaries: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());
		String DICTIONARIES_ID = null == pd.get("DICTIONARIES_ID")?"":pd.get("DICTIONARIES_ID").toString();
		pd.put("DICTIONARIES_ID", DICTIONARIES_ID);						//上级ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		page.setPd(pd);
		List<PageData>	varList = dictionariesCorpService.list(page);		//列出Dictionaries列表
		if("".equals(DICTIONARIES_ID) || "0".equals(DICTIONARIES_ID)) {
			map.put("PARENT_ID", "0");									//上级ID
		}else {
			map.put("PARENT_ID", dictionariesCorpService.findById(pd).getString("PARENT_ID"));	//上级ID
		}
		map.put("varList", varList);
		map.put("page", page);
		map.put("result", errInfo);
		return map;
	}

	/**去新增页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goAdd")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "监测类型管理",instructionsType = "新增页面")
	public Object goAdd()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		String DICTIONARIES_ID = null == pd.get("DICTIONARIES_ID")?"":pd.get("DICTIONARIES_ID").toString();
		pd.put("DICTIONARIES_ID", DICTIONARIES_ID);						//上级ID
		map.put("pds",dictionariesCorpService.findById(pd));				//传入上级所有信息
		map.put("result", errInfo);
		return map;
	}

	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "监测类型管理",instructionsType = "新增")
	public Object add() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("DICTIONARIES_ID", this.get32UUID());	//主键
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		dictionariesCorpService.save(pd);
		map.put("result", errInfo);
		return map;
	}

	/**判断编码是否存在
	 * @return
	 */
	@RequestMapping(value="/hasBianma")
	@ResponseBody
	public Object hasBianma(){
		Map<String,String> map = new HashMap<String,String>();
		String errInfo = "success";
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
			if(dictionariesCorpService.findByBianma(pd) != null){
				errInfo = "error";
			}
		} catch(Exception e){
			errInfo = "error";
		}
		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 = dictionariesCorpService.findById(pd);							//根据ID读取
		map.put("pd", pd);												//放入视图容器
		pd.put("DICTIONARIES_ID",pd.get("PARENT_ID").toString());		//用作上级信息
		map.put("pds",dictionariesCorpService.findById(pd));				//传入上级所有信息
		map.put("result", errInfo);										//返回结果
		return map;
	}

	/**去修改页面
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/findByBianma")
	@ResponseBody
	public Object findByBianma()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
		map.put("DICTIONARIES_ID",dictionariesCorpService.findByBianma(pd).get("DICTIONARIES_ID"));				//传入上级所有信息
		map.put("result", errInfo);										//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/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("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		dictionariesCorpService.edit(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**
	 * 删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "监测类型管理",instructionsType = "删除")
	public Object delete() throws Exception{
		Map<String,String> map = new HashMap<String,String>();
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", pd.getString("DICTIONARIES_ID"));
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		String errInfo = "success";
		if(dictionariesCorpService.listSubDictByParentId(pd).size() > 0){//判断是否有子级，是：不允许删除
			errInfo = "error";
		}else{
			PageData data = dictionariesCorpService.findById(pd);					//根据ID读取
			if("yes".equals(data.getString("YNDEL")))return null;		//当禁止删除字段值为yes, 则禁止删除，只能从手动从数据库删除
			if(null != data.get("TBSNAME") && !"".equals(data.getString("TBSNAME"))){
				String TBFIELD = data.getString("TBFIELD");
				if(Tools.isEmpty(TBFIELD))TBFIELD = "BIANMA"; 		//如果关联字段没有设置，就默认字段为 BIANMA
				data.put("TBFIELD", TBFIELD);
				String[] table = data.getString("TBSNAME").split(",");
				for(int i=0;i<table.length;i++){
					data.put("thisTable", table[i]);
					try {
						if(Integer.parseInt(dictionariesCorpService.findFromTbs(data).get("zs").toString())>0){//判断是否被占用，是：不允许删除(去排查表检查字典表中的编码字段)
							errInfo = "error";
							break;
						}
					} catch (Exception e) {
							errInfo = "error2";
							break;
					}
				}
			}
		}
		if("success".equals(errInfo)){
			if (pd.get("DICTTYPE") != null) {
				if ("APPLICABLE_PERSONNEL".equals(pd.getString("DICTTYPE"))){
					usersService.clearLearnerCategory(pd);    //清除在线学习人员分类
				} else if ("POSITION".equals(pd.getString("DICTTYPE"))
						|| "JOB_TITLE".equals(pd.getString("DICTTYPE"))
						|| "WORK_TYPE".equals(pd.getString("DICTTYPE"))) {
					userInfoService.clearDict(pd);    //清除人员字典信息（职务、职称、工种）
				}
			}
			dictionariesCorpService.delete(pd);	//执行删除
		}
		map.put("result", errInfo);
		return map;
	}

	/**获取连级数据
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getLevels")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "数据采集阈值设定",instructionsType = "获取级联数据")
	public Object getLevels() 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
		String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
		DICTIONARIES_ID = Tools.isEmpty(DICTIONARIES_ID)?"0":DICTIONARIES_ID;
		pd.put("PARENT_ID", DICTIONARIES_ID);	//企业ID
		List<Dictionaries>	varList = dictionariesCorpService.listSubDictByParentId(pd); //用传过来的ID获取此ID下的子列表数据
		List<PageData> pdList = new ArrayList<PageData>();
		for(Dictionaries d :varList){
			PageData pdf = new PageData();
			pdf.put("DICTIONARIES_ID", d.getDICTIONARIES_ID());
			pdf.put("BIANMA", d.getBIANMA());
			pdf.put("NAME", d.getNAME());
			pdList.add(pdf);
		}
		map.put("list", pdList);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**
	 * 显示列表ztree (用于代码生成器引用数据字典)
	 * @return
	 */
	@RequestMapping(value="/listAllDictToCreateCode")
	@ResponseBody
	public Object listAllDictToCreateCode()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", "0");	//上级ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToCreateCode(pd));
		String json = arr.toString();
		json = json.replaceAll("DICTIONARIES_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "click");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	@RequestMapping(value="/listHylxDictToCreateCode")
	@ResponseBody
	public Object listHylxDictToCreateCode()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", "f2598ba72e864eadabf0ca4b664d26b9");	//上级ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToCreateCode(pd));
		String json = arr.toString();
		json = json.replaceAll("DICTIONARIES_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "click");
//		List<PageData> zdicPdList = new ArrayList<PageData>();
//		PageData dic = new PageData();
//		dic.put("DICTIONARIES_ID",pd.getString("DICTIONARIES_ID"));
//		dic=this.dictionariesCorpService.findById(dic);
//		PageData node = new PageData();
//		node.put("id", dic.get("DICTIONARIES_ID"));
//		node.put("parentId", dic.get("PARENT_ID"));
//		node.put("name", dic.get("NAME"));
//		node.put("icon", "../../../assets/images/user.gif");
//		zdicPdList.add(node);
//		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToSelect(pd.getString("DICTIONARIES_ID"),zdicPdList));
//		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}
	@RequestMapping(value="/listJjlxDictToCreateCode")
	@ResponseBody
	public Object listJjlxDictToCreateCode()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", "688d2cf1c6cd4dab999a0106e09aec83");	//上级ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToCreateCode(pd));
		String json = arr.toString();
		json = json.replaceAll("DICTIONARIES_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "click");
//		List<PageData> zdicPdList = new ArrayList<PageData>();
//		PageData dic = new PageData();
//		dic.put("DICTIONARIES_ID",pd.getString("DICTIONARIES_ID"));
//		dic=this.dictionariesCorpService.findById(dic);
//		PageData node = new PageData();
//		node.put("id", dic.get("DICTIONARIES_ID"));
//		node.put("parentId", dic.get("PARENT_ID"));
//		node.put("name", dic.get("NAME"));
//		node.put("icon", "../../../assets/images/user.gif");
//		zdicPdList.add(node);
//		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToSelect(pd.getString("DICTIONARIES_ID"),zdicPdList));
//		map.put("zTreeNodes", (null == arr ?"":"{\"treeNodes\":" + arr.toString() + "}"));
		map.put("zTreeNodes", json);
		map.put("result", errInfo);
		return map;
	}
	/*导入exclint jj=0;
	String pid="";
	String pid1="";
	String pid2="";
	for(PageData lpd:listPd) {
		jj++;
		PageData dic=new PageData();
		if(null!=lpd.get("var0")&&!"".equals(lpd.get("var0"))) {
			dic.put("DICTIONARIES_ID", this.get32UUID());
			dic.put("NAME", lpd.get("var4"));
			dic.put("BIANMA", lpd.get("var0"));
			dic.put("PARENT_ID", "f2598ba72e864eadabf0ca4b664d26b9");
			dic.put("ORDER_BY", jj);
			dic.put("YNDEL", "NO");
			dictionariesCorpService.save(dic);
			pid=dic.getString("DICTIONARIES_ID");
		}
		if(null!=lpd.get("var1")&&!"".equals(lpd.get("var1"))) {
			dic.put("DICTIONARIES_ID", this.get32UUID());
			dic.put("NAME", lpd.get("var4"));
			dic.put("BIANMA", lpd.get("var1"));
			dic.put("PARENT_ID", pid);
			dic.put("ORDER_BY", jj);
			dic.put("YNDEL", "NO");
			dictionariesCorpService.save(dic);
			pid1=dic.getString("DICTIONARIES_ID");
		}
		if(null!=lpd.get("var2")&&!"".equals(lpd.get("var2"))) {
			dic.put("DICTIONARIES_ID", this.get32UUID());
			dic.put("NAME", lpd.get("var4"));
			dic.put("BIANMA", lpd.get("var2"));
			dic.put("PARENT_ID", pid1);
			dic.put("ORDER_BY", jj);
			dic.put("YNDEL", "NO");
			dictionariesCorpService.save(dic);
			pid2=dic.getString("DICTIONARIES_ID");
		}
		if(null!=lpd.get("var3")&&!"".equals(lpd.get("var3"))) {
			dic.put("DICTIONARIES_ID", this.get32UUID());
			dic.put("NAME", lpd.get("var4"));
			dic.put("BIANMA", lpd.get("var3"));
			dic.put("PARENT_ID", pid2);
			dic.put("ORDER_BY", jj);
			dic.put("YNDEL", "NO");
			dictionariesCorpService.save(dic);
		}*/
	/**
	 * 显示列表ztree (用于代码生成器引用数据字典)
	 * @return
	 */
	@RequestMapping(value="/listAllDictToParId")
	@ResponseBody
	@LogAnno(menuType= "监测预警",menuServer= "重大危险源监测预警",instructionsOperate = "监测类型管理",instructionsType = "显示列表")
	public Object listAllDictToParId()throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();
		pd.put("PARENT_ID", pd.getString("parentId"));	//上级ID
		pd.put("CORPINFO_ID", Jurisdiction.getCORPINFO_ID());	//企业ID
		JSONArray arr = JSONArray.fromObject(dictionariesCorpService.listAllDictToCreateCode(pd));
		String json = arr.toString();
		json = json.replaceAll("DICTIONARIES_ID", "id").replaceAll("PARENT_ID", "pId").replaceAll("NAME", "name").replaceAll("subDict", "nodes").replaceAll("hasDict", "checked").replaceAll("treeurl", "click");
		map.put("zTreeNodes", json);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("msmlogin: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(",");
			dictionariesCorpService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}


}
