/**
 * 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.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.modules.sys.dao.OfficeDao;
import com.jeeplus.modules.sys.dao.RoleDao;
import com.jeeplus.modules.sys.entity.*;
import com.jeeplus.modules.sys.service.MainDictDetailService;
import com.jeeplus.modules.sys.service.MainDictService;
import com.jeeplus.modules.sys.utils.UserUtils;
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.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典管理Controller
 * @author 马鹏波
 * @version 2018-05-30
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/mainDict")
public class MainDictController extends BaseController {

	@Autowired
	private MainDictService mainDictService;
	@Autowired
	private MainDictDetailService mainDictDetailService;
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private OfficeDao officeDao;
	@ModelAttribute
	public MainDict get(@RequestParam(required=false) String id) {
		MainDict entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = mainDictService.get(id);
		}
		if (entity == null){
			entity = new MainDict();
		}
		return entity;
	}
	
	/**
	 * 字典列表页面
	 */
	@RequiresPermissions("sys:mainDict:list")
	@RequestMapping(value = {"list", ""})
	public String list(MainDict mainDict, HttpServletRequest request, HttpServletResponse response, Model model) {
		String company=request.getParameter("company");
        User user = UserUtils.getUser();
        boolean admin = user.isAdmin();
		List<Role> roleList=new ArrayList<>();
		if(company==null||"".equals(company)){
			if(admin){
				Role role=new Role();
				Office office=new Office();
				office.setId("1");
				office.setName("系统默认");
				role.setOffice(office);
				roleList.add(role);
			}else{
				roleList =  roleDao.getManagerRoleList(user.getId(),UserUtils.getSelectCompany().getId());
				if(roleList!=null&&roleList.size()>0){
					String dictType="2";
					for(Role r:roleList){
						if("gly".equals(r.getEnname())){
							dictType="";
							break;
						}
					}
					mainDict.setDictType(dictType);
				}
			}
		}else{
			if(admin){
					Role role=new Role();
					Office office=new Office();
					office.setId("1");
					office.setName("系统默认");
					role.setOffice(office);
					roleList.add(role);
				mainDict.setCompany(company);
			}else{
				Office office=officeDao.get(company);
				if(office.getType().equals("3")){
					mainDict.setDictType("2");
				}
				roleList =  roleDao.getManagerRoleList(user.getId(),UserUtils.getSelectCompany().getId());
				mainDict.setCompany(company);
			}
		}
		Page<MainDict> page = mainDictService.findPage(new Page<MainDict>(request, response), mainDict); 
		model.addAttribute("page", page);
		model.addAttribute("list", roleList);
		model.addAttribute("mainDict", mainDict);
		return "modules/sys/mainDictList";
	}

	/**
	 * 查看，增加，编辑字典表单页面
	 */
	@RequiresPermissions(value={"sys:mainDict:view","sys:mainDict:add","sys:mainDict:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(MainDict mainDict, Model model, HttpServletRequest request) {
		String view = request.getParameter("view");
		String typeName= request.getParameter("typeName");
		String company= request.getParameter("company");
		if("view".equals(view)){
			view = "modules/sys/mainDictFormView";
		}else if("1".equals(view)){//系统默认
			List<MainDictDetail> list = mainDictDetailService.findList(mainDict.getId(),"1");
			model.addAttribute("list",list);
			view = "modules/sys/mainDictFormDetail";
		}else if("2".equals(view)){//自定义
			List<MainDictDetail> list = mainDictDetailService.findList(mainDict.getId(),company);
			model.addAttribute("list",list);
			view = "modules/sys/mainDictFormDetailZdy";
		}else{
			view = "modules/sys/mainDictForm";
		}
		mainDict.setOffice(officeDao.get(company));
		model.addAttribute("mainDict", mainDict);
		return view;
	}
	/**
	 * 查看，增加，编辑字典表单页面
	 */
	@RequiresPermissions(value={"sys:mainDict:view","sys:mainDict:add","sys:mainDict:edit"},logical=Logical.OR)
	@RequestMapping(value = "defalt")
	public String defalt(MainDict mainDict, Model model, HttpServletRequest request) {
		String view = request.getParameter("view");
		String typeName= request.getParameter("typeName");
		model.addAttribute("mainDict", mainDict);
		return "modules/sys/mainDictFormDetail";
	}
	/**
	 * 保存字典
	 */
	@RequiresPermissions(value={"sys:mainDict:add","sys:mainDict:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(MainDict mainDict, Model model, HttpServletRequest request,RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, mainDict)){
			return form(mainDict, model, request);
		}
		boolean admin = UserUtils.getUser().isAdmin();
		if(!admin){
			addMessage(redirectAttributes, "只有超级管理员才有权限！");
			return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
		}
		if(!mainDict.getIsNewRecord()){//编辑表单保存
			MainDict t = mainDictService.get(mainDict.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(mainDict, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			mainDictService.save(t);//保存
		}else{//新增表单保存
			mainDictService.save(mainDict);//保存
		}
		addMessage(redirectAttributes, "保存字典成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
	}
	
	/**
	 * 删除字典
	 */
	@RequiresPermissions("sys:mainDict:del")
	@RequestMapping(value = "delete")
	public String delete(MainDict mainDict, RedirectAttributes redirectAttributes) {
		boolean admin = UserUtils.getUser().isAdmin();
		if(!admin){
			addMessage(redirectAttributes, "只有超级管理员才有权限！");
			return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
		}
		mainDictService.delete(mainDict);
		addMessage(redirectAttributes, "删除字典成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
	}
	
	/**
	 * 批量删除字典
	 */
	@RequiresPermissions("sys:mainDict:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			mainDictService.delete(mainDictService.get(id));
		}
		addMessage(redirectAttributes, "删除字典成功");
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("sys:mainDict:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(MainDict mainDict, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "字典"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MainDict> page = mainDictService.findPage(new Page<MainDict>(request, response, -1), mainDict);
    		new ExportExcel("字典", MainDict.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出字典记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("sys:mainDict:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<MainDict> list = ei.getDataList(MainDict.class);
			for (MainDict mainDict : list){
				try{
					mainDictService.save(mainDict);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条字典记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条字典记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入字典失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
    }
	
	/**
	 * 下载导入字典数据模板
	 */
	@RequiresPermissions("sys:mainDict:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "字典数据导入模板.xlsx";
    		List<MainDict> list = Lists.newArrayList(); 
    		new ExportExcel("字典数据", MainDict.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/sys/mainDict/?repage";
    }
	/*@ResponseBody
	@RequestMapping(value = "typeName")
	public String checkNo(String typeName,String oldTypeName) {
		if (typeName !=null && typeName.equals(oldTypeName)) {
			return "true";
		} else if (typeName !=null) {
			MainDict mainDict = mainDictService.getIdByName(typeName);
			if(mainDict==null)
				return "true";
		}
		return "false";
	}*/

	@RequestMapping("typeName")
	@ResponseBody
	public AjaxJson typeName(String typeName,String id){
		AjaxJson ajaxJson = new AjaxJson();
		try {
			Boolean flag = mainDictService.getTypeName(typeName,id);
			ajaxJson.getBody().put("isUsed",flag);
		}catch (Exception e){
			logger.error("校验类型异常：",e);
			ajaxJson.setSuccess(false);
		}
		return ajaxJson;
	}


}