/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.web;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.MainDictDao;
import com.jeeplus.modules.sys.entity.MainDict;
import com.jeeplus.modules.sys.entity.MainDictDetail;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.MainDictDetailService;
import com.jeeplus.modules.sys.service.MainDictService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workjobgrade.entity.WorkJobGrade;
import org.apache.shiro.authz.annotation.Logical;
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.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 字典明细Controller
 * @author 马鹏波
 * @version 2018-05-30
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/mainDictDetail")
public class MainDictDetailController extends BaseController {

	@Autowired
	private MainDictDetailService mainDictDetailService;
	@Autowired
	private MainDictService mainDictService;
	@Autowired
	private MainDictDao mainDictDao;

	@ModelAttribute
	public MainDictDetail get(@RequestParam(required=false) String id) {
		MainDictDetail entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = mainDictDetailService.get(id);
		}
		if (entity == null){
			entity = new MainDictDetail();
		}
		return entity;
	}
	
	/**
	 * 字典明细列表页面
	 */
	@RequestMapping(value = {"list", ""})
	public String list(MainDictDetail mainDictDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<MainDictDetail> page =  mainDictDetailService.findPage(new Page<MainDictDetail>(request, response),mainDictDetail);
		model.addAttribute("page", page);
		return "modules/sys/mainDictDetailList";
	}

	/**
	 * 查看，增加，编辑字典明细表单页面
	 */
	@RequestMapping(value = "form")
	public String form(MainDictDetail mainDictDetail, Model model,HttpServletRequest request) {
		String view = request.getParameter("view");
		String dictId = request.getParameter("dictId");
		String company = request.getParameter("company");
		if("view".equals(view)){
			view = "modules/sys/mainDictDetailFormView";
		}else{
			view = "modules/sys/mainDictDetailForm";
		}
		MainDict mainDict = mainDictService.get(dictId);
		mainDictDetail.setBranchOffice(company);
		model.addAttribute("mainDictDetail", mainDictDetail);
		model.addAttribute("mainDict",mainDict);
		return view;
	}

	/**
	 * 保存字典明细
	 */
	@RequestMapping(value = "save")
	@Transactional
	public String save(MainDictDetail mainDictDetail, Model model, HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, mainDictDetail)){
			return form(mainDictDetail, model, request);
		}
		boolean admin = UserUtils.getUser().isAdmin();
		if(!"0".equals(mainDictDetail.getParentId()) && !Strings.isNullOrEmpty(mainDictDetail.getParentId())){
			MainDictDetail md = mainDictDetailService.get(mainDictDetail.getParentId());
			if(md != null){
				mainDictDetail.setEndFlag("1");//是末级
				mainDictDetail.setParentIds(md.getParentIds()+mainDictDetail.getParentId()+",");
				mainDictDetail.setParentNames((!Strings.isNullOrEmpty(md.getParentNames()))?md.getParentNames()+"/"+md.getDetailName():md.getDetailName());
			}else{
				mainDictDetail.setParentIds("0,");
			}
			md.setEndFlag("0");//不是末级
			mainDictDetailService.upateEndFlag(md);
		}else{
			mainDictDetail.setEndFlag("1");//是末级
			mainDictDetail.setParentId("0");
			mainDictDetail.setParentIds("0,");
		}
		if(admin){
			mainDictDetail.setLevel("1");//系统默认
		}else{
			mainDictDetail.setLevel("2");//非系统默认
		}
		mainDictDetail.setCompany(UserUtils.getSelectCompany());
		if(!mainDictDetail.getIsNewRecord()){//编辑表单保存
			MainDictDetail t = mainDictDetailService.get(mainDictDetail.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(mainDictDetail, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			mainDictDetailService.save(t);//保存
		}else{//新增表单保存
			mainDictDetailService.save(mainDictDetail);//保存
		}
		addMessage(redirectAttributes, "保存字典明细成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDictDetail/?typeId="+mainDictDetail.getTypeId()+"&repage";
	}
	
	/**
	 * 删除字典明细
	 */
	@RequestMapping(value = "delete")
	public String delete(MainDictDetail mainDictDetail, RedirectAttributes redirectAttributes) {
		mainDictDetailService.delete(mainDictDetail);
		addMessage(redirectAttributes, "删除字典明细成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDictDetail/?repage";
	}
	
	/**
	 * 批量删除字典明细
	 */
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			mainDictDetailService.delete(mainDictDetailService.get(id));
		}
		addMessage(redirectAttributes, "删除字典明细成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDictDetail/?repage";
	}
	

	/**
	 * 下载导入字典明细数据模板
	 */
	@RequiresPermissions("sys:mainDictDetail:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "字典明细数据导入模板.xlsx";
    		List<MainDictDetail> list = Lists.newArrayList(); 
    		new ExportExcel("字典明细数据", MainDictDetail.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/mainDictDetail/?repage";
    }

	/**
	 * 获取机构JSON数据。
	 *
	 * @param extId    排除的ID
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required = false) String extId,
											  @RequestParam(required = false) Boolean isAll,
											  @RequestParam(required = false) String typeId,
											  @RequestParam(required = false) String typeName,
											  @RequestParam(required = false) String company,
											  HttpServletResponse response) {
		MainDict mainDict = mainDictService.getIdByName(typeName);
		if(mainDict != null){
			typeId = mainDict.getId();
		}
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MainDictDetail> list = mainDictDetailService.findList(typeId,company);
		for (int i = 0; i < list.size(); i++) {
			MainDictDetail e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pIds", e.getParentIds());
				map.put("pId", e.getParentId());
				map.put("name", e.getDetailName());
				map.put("key", e.getDetailKey());
				if (e.getEndFlag() != null && "0".equals(e.getEndFlag())) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
	/**
	 * 指标字典列表页面
	 */
	@RequiresPermissions("workexample:workExampleIndices:index")
	@RequestMapping(value = {"index"})
	public String index(MainDictDetail mainDictDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/workexample/workCaseIndex";
	}
	/**
	 * 指标字典列表页面
	 */
	@RequiresPermissions("workexample:workexample:treeIndex")
	@RequestMapping(value = {"treeIndex"})
	public String treeIndex(MainDictDetail mainDictDetail, HttpServletRequest request, HttpServletResponse response, Model model) {
		return "modules/workexample/workCaseViewIndex";
	}

	/**
	 * 获取机构JSON数据。
	 *
	 * @param extId    排除的ID
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "treeDataByType")
	public List<Map<String, Object>> treeDataByType(@RequestParam(required = false) String extId,
											  @RequestParam(required = false) Boolean isAll,
											  @RequestParam(required = false) String typeId,
											  @RequestParam(required = false) Integer type,
											  @RequestParam(required = false) String typeName,
											  HttpServletResponse response) {
		MainDict mainDict = mainDictService.getIdByName(typeName);
		if(mainDict != null){
			typeId = mainDict.getId();
		}
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MainDictDetail> list = mainDictDetailService.findListByType(typeId);
		for (int i = 0; i < list.size(); i++) {
			MainDictDetail e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId != null && !extId.equals(e.getId()) && e.getParentIds().indexOf("," + extId + ",") == -1))) {
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getDetailName());
				map.put("pIds", e.getParentIds());
				map.put("key", e.getDetailKey());
				if (e.getEndFlag() != null && "0".equals(e.getEndFlag())) {
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}


	/**
	 * 获取字典明细数据
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getDictDetail")
	public Map<Object, Object> treeData(HttpServletRequest request) {
		Map<Object,Object> map = new HashMap<>();
		String dictId = request.getParameter("dictId");
		String company = request.getParameter("company");
		List<MainDictDetail> list = null;
		List<MainDictDetail> sortedList = new ArrayList<>();
		list = mainDictDetailService.findList( dictId,company);//点击自定义的时候  只查询所在分公司的
		if(list!=null&&list.size()>0) {
			this.sortList(sortedList,list,null);
			}
		map.put("list",sortedList);
		return map;
	}

	private void sortList(List<MainDictDetail> sortedList, List<MainDictDetail> list,MainDictDetail parent) {
		Iterator<MainDictDetail> iterator = list.iterator();
		while (iterator.hasNext()){
			MainDictDetail next = iterator.next();
			if(next==null)continue;
			if(parent==null) {
				sortedList.add(next);
				iterator.remove();
				this.sortList(sortedList,list,next);
				next.setParentId("0");
				iterator = list.iterator();
			}else {
				if(parent.getId().equals(next.getParentId())){
					sortedList.add(next);
					iterator.remove();
					this.sortList(sortedList,list,next);
					iterator = list.iterator();
				}
			}
		}
	}
	/**
	 * 获取默认字典数据
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getDictDetailDefalt")
	public Map<Object, Object> getDictDetailDefalt(HttpServletRequest request) {
		Map<Object,Object> map = new HashMap<>();
		List<MainDictDetail> sortedList = new ArrayList<>();
		String dictId = request.getParameter("dictId");
		String company = request.getParameter("company");
		List<MainDictDetail> list = mainDictDetailService.getDictDetailDefalt(dictId);
		if(list!=null&&list.size()>0) {
			this.sortList(sortedList,list,null);
		}
		map.put("list",sortedList);
		return map;
	}
	/**
	 * 更改删除标志
	 * @return
	 */
	@RequestMapping(value = "updateDelFlag")
	@ResponseBody
	public Map<Object, Object> updateDelFlag(HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String dictDetailId = request.getParameter("dictDetailId");
		String delflag = request.getParameter("delflag");
		int i = mainDictDetailService.updateDelFlag(delflag,dictDetailId);
		map.put("flag",(i>0)?true:false);
		return map;
	}

	/**
	 * 更改删除标志
	 * @return
	 */
	@RequestMapping(value = "getdetailName")
	@ResponseBody
	public Map<Object, Object> getdetailName(HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String dictDetailId = request.getParameter("dictDetailId");
		String typeName = request.getParameter("typeName");
		MainDict mainDict = mainDictService.getIdByName(typeName);
		if(mainDict != null){
			MainDictDetail mainDictDetail = new MainDictDetail();
			mainDictDetail.setTypeId(mainDict.getId());
			mainDictDetail.setCompany(UserUtils.getSelectCompany());
			mainDictDetail.setDetailKey(dictDetailId);
			MainDictDetail mdd = mainDictDetailService.getNameByIdAndKey(mainDictDetail);
			map.put("labelname",mdd.getDetailName());
			map.put("labelid",mdd.getId());
		}else{
			map.put("labelname",null);
			map.put("labelid",null);
		}
		return map;
	}

	/*@RequestMapping(value = "syncDict")
	@ResponseBody
	public Map<Object, Object> syncDict(MainDictDetail mainDictDetail,HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String dictId = request.getParameter("dictId");
		String typeName=request.getParameter("typeName");
		mainDictDetail.setTypeId(dictId);
		boolean mainDictDetails = mainDictDetailService.syncDict(mainDictDetail);
		map.put("flag",mainDictDetails);
		return map;
	}*/
//同步默认字典
	@RequestMapping(value = "syncDict")
	@ResponseBody
	public Map<Object, Object> syncDict(MainDictDetail mainDictDetail,HttpServletRequest request){
		Map<Object,Object> map = new HashMap<>();
		String dictId = request.getParameter("dictId");
		String company=request.getParameter("company");
		boolean mainDictDetails = mainDictDetailService.syncDict(dictId,company);
		map.put("flag",mainDictDetails);
		return map;
	}

	@RequestMapping("detailKey")
	@ResponseBody
	public AjaxJson typeName(String detailKey, String typeId, String id, String branchOffice){
		AjaxJson ajaxJson = new AjaxJson();
		try {
			Boolean flag = mainDictDetailService.getDetailKey(detailKey,typeId,id,branchOffice);
			ajaxJson.getBody().put("isUsed",flag);
		}catch (Exception e){
			logger.error("校验键值异常：",e);
			ajaxJson.setSuccess(false);
		}
		return ajaxJson;
	}
	@RequestMapping("selectFlag")
	@ResponseBody
	public Boolean selectFlag(HttpServletRequest request){
		boolean admin = UserUtils.getUser().isAdmin();
		if(admin){
			return true;
		}
		String dictId = request.getParameter("dictId");
		MainDictDetail mainDictDetail=new MainDictDetail();
		mainDictDetail.setTypeId(dictId);
		Boolean flag = mainDictDetailService.selectFlag(mainDictDetail);
		return flag;
	}

}