package com.zcloud.controller.corp;

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.corp.CorpTypeService;
import com.zcloud.service.corp.CorpTypeToDeptService;
import com.zcloud.util.ObjectExcelView;
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.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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 说明：企业类型
 * 作者：shaojie
 * 时间：2021-03-18
 * 官网：www.qdkjchina.com
 */
@Controller
@RequestMapping("/corptype")
public class CorpTypeController extends BaseController {

	@Autowired
	private CorpTypeService corptypeService;
	@Autowired
	private CorpTypeToDeptService corptypetodeptService;
	/**新增
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/add")
	// @RequiresPermissions("corptype:add")
	@ResponseBody
	@Transactional
	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("CORPTYPE_ID", this.get32UUID());	//主键
		corptypeService.save(pd);
		if(pd.get("cityMap")!=null && pd.get("cityMap")!="") {
			Map<String, String> cityMap =  JSONObject.parseObject(pd.get("cityMap").toString(),Map.class);
			System.out.println(cityMap);
			for (Map.Entry<String, String> entry : cityMap.entrySet()) {
				System.out.println(entry);
				PageData ctod = new PageData();
				ctod.put("CORPTYPETODEPT_ID", this.get32UUID());	//主键
				ctod.put("BIANMA", entry.getKey());
				ctod.put("DEPARTMENT_ID", entry.getValue());
				ctod.put("CORPTYPE_ID", pd.get("CORPTYPE_ID"));
				corptypetodeptService.save(ctod);
			}
		}

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

	/**列表
	 * @param page
	 * @throws Exception
	 */
	@RequestMapping(value="/corptypelist")
	@ResponseBody
	public Object corptypelist() throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		PageData pd = new PageData();
		pd = this.getPageData();

		pd = corptypeService.corptypelist(pd);	//列出areacorptype列表
		map.put("varOList", pd);
		map.put("result", errInfo);
		return map;
	}

	/**删除
	 * @param out
	 * @throws Exception
	 */
	@RequestMapping(value="/delete")
	// @RequiresPermissions("corptype: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();
		corptypeService.delete(pd);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**修改
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/edit")
	// @RequiresPermissions("corptype: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();
		corptypetodeptService.delete(pd);
		corptypeService.edit(pd);
		if(pd.get("cityMap")!=null && pd.get("cityMap")!="") {
			Map<String, String> cityMap =  JSONObject.parseObject(pd.get("cityMap").toString(),Map.class);
			System.out.println(cityMap);
			for (Map.Entry<String, String> entry : cityMap.entrySet()) {
				System.out.println(entry);
				PageData ctod = new PageData();
				ctod.put("CORPTYPETODEPT_ID", this.get32UUID());	//主键
				ctod.put("BIANMA", entry.getKey());
				ctod.put("DEPARTMENT_ID", entry.getValue());
				ctod.put("CORPTYPE_ID", pd.get("CORPTYPE_ID"));
				corptypetodeptService.save(ctod);
			}
		}
		map.put("result", errInfo);
		return map;
	}

//	/**列表
//	 * @param page
//	 * @throws Exception
//	 */
//	@RequestMapping(value="/list")
//	// @RequiresPermissions("corptype:list")
//	@ResponseBody
//	public Object list() throws Exception{
//		Map<String,Object> map = new HashMap<String,Object>();
//		String errInfo = "success";
//		PageData pd = new PageData();
//		pd = this.getPageData();
//		List<PageData> varList = corptypeService.listAllByParentId(pd);
//		pd.put("CORPTYPE_ID", pd.get("PARENT_ID"));
//		map.put("pd", corptypeService.findById(pd));									//传入父菜单所有信息
//		map.put("varList", varList);
//		map.put("CITY_CODE", Jurisdiction.getUserCityCode());
//		map.put("result", errInfo);
//		return map;
//	}

	 /**去修改页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/goEdit")
	// @RequiresPermissions("corptype:edit")
	@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 = corptypeService.findById(pd);	//根据ID读取
		map.put("pd", pd);
		map.put("ctodList", corptypetodeptService.listAll(pd));
		map.put("result", errInfo);
		return map;
	}

	 /**批量删除
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/deleteAll")
	// @RequiresPermissions("corptype: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();
		String DATA_IDS = pd.getString("DATA_IDS");
		if(Tools.notEmpty(DATA_IDS)){
			String ArrayDATA_IDS[] = DATA_IDS.split(",");
			corptypeService.deleteAll(ArrayDATA_IDS);
			errInfo = "success";
		}else{
			errInfo = "error";
		}
		map.put("result", errInfo);				//返回结果
		return map;
	}

	 /**导出到excel
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/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("类型名称");	//1
		titles.add("父类型");	//2
		titles.add("备注");	//3
		dataMap.put("titles", titles);
		List<PageData> varOList = corptypeService.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("NAME"));	    //1
			vpd.put("var2", varOList.get(i).getString("PARENT_ID"));	    //2
			vpd.put("var3", varOList.get(i).getString("DESCR"));	    //3
			varList.add(vpd);
		}
		dataMap.put("varList", varList);
		ObjectExcelView erv = new ObjectExcelView();
		mv = new ModelAndView(erv,dataMap);
		return mv;
	}
    /**
     * 显示列表ztree
     *
     * @return
     */
    @RequestMapping(value = "/listAllCorpTypeMent")
    @ResponseBody
	@LogAnno(menuType= "双重预防",menuServer= "企业管理",instructionsOperate = "企业信息",instructionsType = "显示列表")
    public Object listAllCorpTypeMent() throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String errInfo = "success";
        List<PageData> menusBase = corptypeService.listMentDictionByPId("0");
        List<PageData> menuLNotBase = corptypeService.listMentDictionByPId("");
        for (PageData menu : menusBase) {
            menu.put("label",menu.getString("NAME"));
            List<PageData> menus = iterateMenus(menuLNotBase, menu.getString("CORPTYPE_ID"));
            if(menu.size() !=0){
                menu.put("children",menus);
            }
        }
        JSONArray arr = JSONArray.fromObject(menusBase);
        String json = arr.toString().replaceAll("CORPTYPE_ID","id").replaceAll("\"children\":\\[\\],","");
        map.put("zTreeNodes", json);
        map.put("result", errInfo);
        return map;
    }
    public List<PageData> iterateMenus(List<PageData> menuVoList, String pid) {
        List<PageData> result = new ArrayList<PageData>();
        for (PageData menu : menuVoList) {
            if("0".equals(menu.getString("CORPTYPE_ID"))) {
                continue;
            }
            menu.put("label",menu.getString("NAME"));
            // 获取菜单的id
            String menuid = menu.getString("CORPTYPE_ID");
            // 获取菜单的父id
            String parentid = menu.getString("PARENT_ID");
            if(Tools.isEmpty(pid)) {
                continue;
            }
            if (parentid.equals(pid)) {
                // 递归查询当前子菜单的子菜单
                List<PageData> iterateMenu = iterateMenus(menuVoList,menuid);
                if(iterateMenu.size() !=0){
                    menu.put("children",iterateMenu);
                }
                result.add(menu);
            }
        }
        return result;
    }

}
