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.Response;
import com.zcloud.entity.system.Dictionaries;
import com.zcloud.logs.LogAnno;
import com.zcloud.service.system.DictionariesService;
import com.zcloud.util.Tools;
import com.zcloud.util.Warden;
import net.sf.json.JSONArray;
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.RequestParam;
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("/dictionaries")
public class DictionariesController extends BaseController {

    @Autowired
    private DictionariesService dictionariesService;

    /**
     * 显示列表ztree
     *
     * @return
     */
    @RequestMapping(value = "/listAllDict")
    // @RequiresPermissions("dictionaries:list")
    @ResponseBody
    public Object listAllDict() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDict("0"));
        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
    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
        page.setPd(pd);
        List<PageData> varList = dictionariesService.list(page);        //列出Dictionaries列表
        if ("".equals(DICTIONARIES_ID) || "0".equals(DICTIONARIES_ID)) {
            map.put("PARENT_ID", "0");                                    //上级ID
        } else {
            map.put("PARENT_ID", dictionariesService.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
    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", dictionariesService.findById(pd));                //传入上级所有信息
        map.put("result", errInfo);
        return map;
    }

    /**
     * 新增
     *
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    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());    //主键
        dictionariesService.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();
            if (dictionariesService.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 = dictionariesService.findById(pd);                            //根据ID读取
        map.put("pd", pd);                                                //放入视图容器
        pd.put("DICTIONARIES_ID", pd.get("PARENT_ID").toString());        //用作上级信息
        map.put("pds", dictionariesService.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();
        map.put("DICTIONARIES_ID", dictionariesService.findByBianma(pd).get("DICTIONARIES_ID"));                //传入上级所有信息
        map.put("result", errInfo);                                        //返回结果
        return map;
    }

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

    /**
     * 删除
     *
     * @param DICTIONARIES_ID
     * @param
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String DICTIONARIES_ID) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        PageData pd = new PageData();
        pd.put("DICTIONARIES_ID", DICTIONARIES_ID);
        String errInfo = "success";
        if (dictionariesService.listSubDictByParentId(DICTIONARIES_ID).size() > 0) {//判断是否有子级，是：不允许删除
            errInfo = "error";
        } else {
            pd = dictionariesService.findById(pd);                    //根据ID读取
            if ("yes".equals(pd.getString("YNDEL"))) return null;        //当禁止删除字段值为yes, 则禁止删除，只能从手动从数据库删除
            if (null != pd.get("TBSNAME") && !"".equals(pd.getString("TBSNAME"))) {
                String TBFIELD = pd.getString("TBFIELD");
                if (Tools.isEmpty(TBFIELD)) TBFIELD = "BIANMA";        //如果关联字段没有设置，就默认字段为 BIANMA
                pd.put("TBFIELD", TBFIELD);
                String[] table = pd.getString("TBSNAME").split(",");
                for (int i = 0; i < table.length; i++) {
                    pd.put("thisTable", table[i]);
                    try {
                        if (Integer.parseInt(dictionariesService.findFromTbs(pd).get("zs").toString()) > 0) {//判断是否被占用，是：不允许删除(去排查表检查字典表中的编码字段)
                            errInfo = "error";
                            break;
                        }
                    } catch (Exception e) {
                        errInfo = "error2";
                        break;
                    }
                }
            }
        }
        if ("success".equals(errInfo)) {
            dictionariesService.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();
        String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
        DICTIONARIES_ID = Tools.isEmpty(DICTIONARIES_ID) ? "0" : DICTIONARIES_ID;
        List<Dictionaries> varList = dictionariesService.listSubDictByParentId(DICTIONARIES_ID); //用传过来的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;
    }

    /**
     * 获取连级数据
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getLevelsByCourseware")
    @ResponseBody
    public Object getLevelsByCourseware() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
        pd.put("DICTIONARIES_ID", (Tools.isEmpty(DICTIONARIES_ID) ? "f6a7c4f5602f46e291d06b1390a3f820" : DICTIONARIES_ID));
        List<Dictionaries> varList = dictionariesService.listSubDictByParentIdAndCourseware(pd); //通过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;
    }

    /**
     * 获取连级数据
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getLevelsAndSCount")
    @ResponseBody
    @LogAnno(menuType = "双重预防", menuServer = "企业管理", instructionsOperate = "企业信息", instructionsType = "获取连级数据 ")
    public Object getLevelsAndSCount() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
        DICTIONARIES_ID = Tools.isEmpty(DICTIONARIES_ID) ? "0" : DICTIONARIES_ID;
        List<PageData> varList = dictionariesService.listSubDictByParentIdAndSunCount(DICTIONARIES_ID); //用传过来的ID获取此ID下的子列表数据
        List<PageData> pdList = new ArrayList<PageData>();
        for (PageData d : varList) {
            PageData pdf = new PageData();
            pdf.put("DICTIONARIES_ID", d.getString("DICTIONARIES_ID"));
            pdf.put("BIANMA", d.getString("BIANMA"));
            pdf.put("NAME", d.getString("NAME"));
            pdf.put("zcount", d.get("zcount"));
            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";
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode("0"));
        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();
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode("f2598ba72e864eadabf0ca4b664d26b9"));
        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.dictionariesService.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(dictionariesService.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();
//		String errInfo = "success";
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode("688d2cf1c6cd4dab999a0106e09aec83"));
        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.dictionariesService.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(dictionariesService.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");
			dictionariesService.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");
			dictionariesService.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");
			dictionariesService.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");
			dictionariesService.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();
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode(pd.getString("parentId")));
        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;
    }

    /**
     * 显示列表ztree (用于代码生成器引用数据字典)
     *
     * @return
     */
    @RequestMapping(value = "/listDictToParId")
    @ResponseBody
    public Object listDictToParId() throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode(pd.getString("parentId")));

        String json = arr.toString().replaceAll("", "");
        json = json.replaceAll("DICTIONARIES_ID", "id")
                .replaceAll("PARENT_ID", "pId")
                .replaceAll("NAME", "name").replaceAll("subDict", "nodes")
                .replaceAll("hasDict", "checked").replaceAll("treeurl", "click");
        String jsonb = json.replaceAll(",\"nodes\":\\[\\]", "");
        map.put("zTreeNodes", jsonb);
        map.put("result", errInfo);                //返回结果
        return map;
    }

    /**
     * description:
     * accidentType-风险点
     * hiddenLevel-隐患级别
     *
     * @return tree or list
     * @throws Exception all
     */
    @RequestMapping(value = "/getInfo")
    @ResponseBody
    @LogAnno(menuType = "教育培训", menuServer = "在线学习与考试", instructionsOperate = "我的任务", instructionsType = "获取连级数据")
    public Response getInfo() throws Exception {
        Response response = Response.getResponse();
        try {
            PageData request = this.getPageData();
            if (StringUtils.isBlank(request.getString("vectors"))) throw new RuntimeException("未找到要获取的数据字典类型");
            List<String> vectors = Warden.getList(request.getString("vectors"),String.class);
            for (String vector: vectors) {
                switch (vector) {
                    case "accidentType":
                        //事故类型
                        response.put("accidentType", dictionariesService.getTreeById("cee1190ea96a4ca9b7bca81e11f0d0f8"));
                        continue;
                    case "hiddenLevel":
                        // 隐患级别
                        response.put("hiddenLevel", dictionariesService.getTreeById("5e7cf8620ba54ad89719d0be62133c7a"));
                        continue;
                    case "riskCauses":
                        // 风险成因
                        response.put("riskCauses", dictionariesService.listSubDictByParentId("1bacbc4c1f6544718519c0d470dfeb62"));
                        continue;
                    case "riskLevel":
                        // 风险分级
                        response.put("riskLevel", dictionariesService.getTreeById("5a81e63ec0e94d919b3138bc01dbef6b"));
                        continue;
                    default:
                }
            }
            return response.OK();
        } catch (Exception e) {
            e.printStackTrace();
            return response.errorMessage(e.getMessage());
        }
    }
    @RequestMapping(value="/listSelectTree")
    @ResponseBody
    public Object listSelectTree()throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
        DICTIONARIES_ID = Tools.isEmpty(DICTIONARIES_ID)?"0":DICTIONARIES_ID;
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode(DICTIONARIES_ID));
        String json = arr.toString();
        json = json.replaceAll("BIANMA", "id")
                .replaceAll("PARENT_ID", "pId")
                .replaceAll("NAME", "name")
                .replaceAll("subDict", "nodes")
                .replaceAll("hasDict", "checked")
                .replaceAll("\"nodes\":\\[\\],", "")
                .replaceAll("treeurl", "click");
//
        map.put("zTreeNodes", json);
        map.put("result", errInfo);
        return map;
    }

    @RequestMapping(value="/listSelectTreeByTkiTree")
    @ResponseBody
    public Object listSelectTreeByTkiTree()throws Exception{
        Map<String,Object> map = new HashMap<String,Object>();
        String errInfo = "success";
        PageData pd = new PageData();
        pd = this.getPageData();
        String DICTIONARIES_ID = pd.getString("DICTIONARIES_ID");
        DICTIONARIES_ID = Tools.isEmpty(DICTIONARIES_ID)?"0":DICTIONARIES_ID;
        JSONArray arr = JSONArray.fromObject(dictionariesService.listAllDictToCreateCode(DICTIONARIES_ID));
        String json = arr.toString();
        json = json.replaceAll("BIANMA", "id")
                .replaceAll("PARENT_ID", "pId")
                .replaceAll("NAME", "name")
                .replaceAll("subDict", "children")
                .replaceAll("hasDict", "checked")
                .replaceAll("treeurl", "click");
        map.put("zTreeNodes", json);
        map.put("result", errInfo);
        return map;
    }
}
