package com.ssm.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
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.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.ssm.model.system.SysDictionary;
import com.ssm.model.system.SysUser;
import com.ssm.model.validator.SysDictionaryValidator;
import com.ssm.service.system.SysDictionaryService;
import com.ssm.util.Util;
import com.ssm.util.page.PagedResult;
import com.ssm.web.Const;
import com.ssm.web.RoleLimit;

@RequestMapping("sysDictionary")
@Controller
public class SysDictionaryController {
	
	@Autowired
	private SysDictionaryService sysDictionaryService;
	
	@RoleLimit(pid = "sysDictionary", mid = "dictionaryList")
	@RequestMapping(value="dictionaryList")
	public String dictionaryList(HttpSession session, Model model){
		String currentTab = (String) session.getAttribute("currentTab");
		currentTab = currentTab == null ?  "tab1" : currentTab;
		List<SysDictionary> categroy = sysDictionaryService.selectConstCategory();
		model.addAttribute("categroyList", categroy);
		model.addAttribute("currentTab", currentTab);
		return "sysdictionary/dictionaryList";
	}
	
	/**
	 * 查询字典种类
	 * @param model
	 * @param condition
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="initDataList")
	public String initDataList(Model model, SysDictionary condition, Integer pageNo, Integer pageSize){
		condition.setNamespace(StringUtils.isNotBlank(condition.getNamespace())? condition.getNamespace() : null);
		condition.setDictvalue(StringUtils.isNotBlank(condition.getDictvalue())? condition.getDictvalue() : null);
		condition.setNamespace("CONST_CATEGORY");
		PagedResult<SysDictionary> pageResult = sysDictionaryService.findByCondition(condition, pageNo, pageSize);
		model.addAttribute("list", pageResult);
		model.addAttribute("condition", condition);
		return "sysdictionary/dataList";
	}
	
	/**
	 * 查询字典的常量值
	 * @param model
	 * @param condition
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="initDicitionaryDataList")
	public String initDicitionaryDataList(Model model, SysDictionary condition, Integer pageNo, Integer pageSize){
		condition.setNamespace(StringUtils.isNotBlank(condition.getNamespace())? condition.getNamespace() : null);
		condition.setDictname(StringUtils.isNotBlank(condition.getDictname())? condition.getDictname() : null);
		Map<String, String> namespaceMap = new HashMap<String, String>();
		List<SysDictionary> categroy = sysDictionaryService.selectConstCategory();
		if(!categroy.isEmpty()){
			for(SysDictionary sd : categroy){
				namespaceMap.put(sd.getDictvalue(), sd.getDictname());
			}
		}
		PagedResult<SysDictionary> pageResult = sysDictionaryService.selectByCondition(condition, pageNo, pageSize);
		model.addAttribute("list", pageResult);
		model.addAttribute("condition", condition);
		model.addAttribute("namespaceMap", namespaceMap);
		return "sysdictionary/constDataList";
	}
	
	/**
	 * 添加字典常量
	 * @param currentTab
	 * @return
	 */
	@RoleLimit(pid = "sysDictionary", mid = "dictionaryAdd")
	@RequestMapping(value="dictionaryAdd")
	public String dictionaryAdd(HttpSession session, Model model, @RequestParam("currentTab") String currentTab){
		session.setAttribute("currentTab", currentTab);
		if(!model.containsAttribute("dictionary"))
			model.addAttribute("dictionary", new SysDictionary());
		if("tab1".equalsIgnoreCase(currentTab)){
			List<SysDictionary> categroy = sysDictionaryService.selectConstCategory();
			model.addAttribute("categroyList", categroy);
			return "sysdictionary/addDictionary";
		} else {
			return "sysdictionary/addDictionaryCategory";
		}
	}
	
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@InitBinder("dictionary")
	public void InitBinder(DataBinder binder){
		binder.setValidator(new SysDictionaryValidator());
	}			
	
	/**
	 * 添加字典
	 * @param session
	 * @param model
	 * @param dictionary
	 * @param result
	 * @return
	 */
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="addDictionaryexe")
	public String addDictionaryexe(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("dictionary") SysDictionary dictionary, BindingResult result){
		String currentTab = (String) session.getAttribute("currentTab");
		if(result.hasErrors()) {
			return dictionaryAdd(session, model, currentTab);
		} else{
			String namespace = dictionary.getNamespace();
			String value = dictionary.getDictvalue();
			SysDictionary sd = sysDictionaryService.selectByNamespaceAndValue("CONST_CATEGORY", namespace);
			if(sd == null){
				result.addError(new FieldError("dictionary", "dictname", "分组 "+namespace+" 不存在"));
				return dictionaryAdd(session, model, currentTab);
			} else{
				SysDictionary sdn = sysDictionaryService.selectByNamespaceAndValue(namespace, value);
				if(sdn != null){
					result.addError(new FieldError("dictionary", "dictname", "分组"+namespace+"里已经存在常量 "+value));
					return dictionaryAdd(session, model, currentTab);
				} else {
					dictionary.setIsactive(true);
					dictionary.setSubitems(0);
					SysUser user = Util.getUserSession(request);
					dictionary.setCreateduserid(user.getUserid());
					dictionary.setCreateddatetime(new Date());
					sysDictionaryService.saveSysDictionary(dictionary);
				}
			}
		}
		return "redirect:/sysDictionary/dictionaryList";
	}
	
	/**
	 * 添加字典 分组
	 * @param session
	 * @param model
	 * @param dictionary
	 * @param result
	 * @return
	 */
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="addDictionaryCategoryexe")
	public String addDictionaryCategoryexe(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("dictionary") SysDictionary dictionary, BindingResult result){
		String currentTab = (String) session.getAttribute("currentTab");
		if(result.hasErrors()) {
			return dictionaryAdd(session, model, currentTab);
		} else{
			String value = dictionary.getDictvalue();
			SysDictionary sd = sysDictionaryService.selectByNamespaceAndValue("CONST_CATEGORY", value);
			if(sd != null){
				result.addError(new FieldError("dictionary", "dictname", "分组"+value+"已存在"));
				return dictionaryAdd(session, model, currentTab);
			} else {
				dictionary.setNamespace("CONST_CATEGORY");
				dictionary.setIsactive(true);
				dictionary.setSubitems(0);
				SysUser user = Util.getUserSession(request);
				dictionary.setCreateduserid(user.getUserid());
				dictionary.setCreateddatetime(new Date());
				sysDictionaryService.saveSysDictionary(dictionary);
			}
		}
		return "redirect:/sysDictionary/dictionaryList";
	}
	
	/**
	 * 进入编辑页面
	 * @param session
	 * @param model
	 * @param dictid
	 * @return
	 */
	@RoleLimit(pid = "sysDictionary", mid = "dictionaryEdit")
	@RequestMapping(value="dictionaryEdit")
	public String dictionaryEdit(HttpSession session, Model model, @RequestParam("dictid") Integer dictid){
		SysDictionary dictionary = sysDictionaryService.selectById(dictid);
		if(!model.containsAttribute("dictionary"))
			model.addAttribute("dictionary",dictionary != null ? dictionary : new SysDictionary());
		if("CONST_CATEGORY".equalsIgnoreCase(dictionary.getNamespace())){
			session.setAttribute("currentTab", "tab2");
			return "sysdictionary/dictionaryCategoryEdit";
		} else {
			List<SysDictionary> categroy = sysDictionaryService.selectConstCategory();
			model.addAttribute("categroyList", categroy);
			session.setAttribute("currentTab", "tab1");
			return "sysdictionary/dictionaryEdit";
		}
	}
	
	/**
	 * 编辑保存
	 * @param session
	 * @param model
	 * @param dictionary
	 * @param result
	 * @return
	 */
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="editDictionaryexe")
	public String editDictionaryexe(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("dictionary") SysDictionary dictionary, BindingResult result){
		if(result.hasErrors()) {
			return dictionaryEdit(session, model, dictionary.getDictid());
		} else{
			String namespace = dictionary.getNamespace();
			String value = dictionary.getDictvalue();
			SysDictionary old = sysDictionaryService.selectById(dictionary.getDictid());
			SysDictionary sd = sysDictionaryService.selectByNamespaceAndValue("CONST_CATEGORY", namespace);
			if(sd == null){
				result.addError(new FieldError("dictionary", "dictname", "分组 "+namespace+" 不存在"));
				return dictionaryEdit(session, model, dictionary.getDictid());
			} else{
				if(old.getNamespace().equals(namespace) && old.getDictvalue().equalsIgnoreCase(value)){
					SysUser user = Util.getUserSession(request);
					dictionary.setLastupdateuserid(user.getUserid());
					dictionary.setLastupdatedatetime(new Date());
					sysDictionaryService.updateSysDictionary(dictionary);
				} else {
					SysDictionary sdn = sysDictionaryService.selectByNamespaceAndValue(namespace, value);
					if(sdn != null){
						result.addError(new FieldError("dictionary", "dictname", "分组"+namespace+"里已经存在常量 "+value));
						return dictionaryEdit(session, model, dictionary.getDictid());
					} else {
						SysUser user = (SysUser) session.getAttribute(Const.USER_SESSION_KEY);
						dictionary.setLastupdateuserid(user.getUserid());
						dictionary.setLastupdatedatetime(new Date());
						sysDictionaryService.updateSysDictionary(dictionary);
					}
				}
				
			}
		}
		return "redirect:/sysDictionary/dictionaryList";
	}
	
	/**
	 * 编辑分组保存
	 * @param session
	 * @param model
	 * @param dictionary
	 * @param result
	 * @return
	 */
	@Transactional(value="txManager")
	@RoleLimit(pid = Const.SYSTEM_ROLE_LIMIT_PID, mid = Const.SYSTEM_ROLE_LIMIT_MID)
	@RequestMapping(value="editDictionaryCategoryexe")
	public String editDictionaryCategoryexe(HttpServletRequest request, HttpSession session, Model model, 
			@Validated @ModelAttribute("dictionary") SysDictionary dictionary, BindingResult result){
		SysDictionary oldDictionary = sysDictionaryService.selectById(dictionary.getDictid());
		if(result.hasErrors()) {
			return dictionaryEdit(session, model, dictionary.getDictid());
		} else{
			
			if(oldDictionary.getDictvalue().equalsIgnoreCase(dictionary.getDictvalue()) ){
				SysUser user = Util.getUserSession(request);
				dictionary.setLastupdateuserid(user.getUserid());
				dictionary.setLastupdatedatetime(new Date());
				sysDictionaryService.updateSysDictionary(dictionary);
			} else {
				String value = dictionary.getDictvalue();
				SysDictionary sd = sysDictionaryService.selectByNamespaceAndValue("CONST_CATEGORY", value);
				if(sd != null){
					result.addError(new FieldError("dictionary", "dictname", "分组 "+value+" 已存在"));
					return dictionaryEdit(session, model, dictionary.getDictid());
				} else{
					SysUser user = Util.getUserSession(request);
					dictionary.setLastupdateuserid(user.getUserid());
					dictionary.setLastupdatedatetime(new Date());
					sysDictionaryService.updateSysDictionary(dictionary);
					//查询原来该分组下的常量
					List<SysDictionary> list = sysDictionaryService.selectByNamespace(oldDictionary.getDictvalue());
					if(!list.isEmpty()){
						for(SysDictionary dict : list){
							dict.setLastupdateuserid(user.getUserid());
							dict.setLastupdatedatetime(new Date());
							dict.setNamespace(dictionary.getDictvalue());
							sysDictionaryService.updateSysDictionary(dict);
						}
					}
				}
			}
			
		}
		return "redirect:/sysDictionary/dictionaryList";
	}
	
	/**
	 * 激活和反激活 字典
	 * @param dictid
	 * @return
	 */
	@RoleLimit(pid = "sysDictionary", mid = "updateDictionaryEnable")
	@Transactional(value="txManager")
	@RequestMapping(value="updateDictionaryEnable", method=RequestMethod.POST)
	public Map<String, Object> updateDictionaryEnable(@RequestParam("dictid") Integer dictid){
		Map<String, Object> record = new HashMap<String, Object>();
		record.put("success", true);
		SysDictionary dictionary = sysDictionaryService.selectById(dictid);
		if(dictionary != null){
			if(dictionary.getIsactive()) { 
				dictionary.setIsactive(false);
				record.put("userStatus", true);
			} else {
				dictionary.setIsactive(true);
				record.put("userStatus", false);
			}
			int count = sysDictionaryService.updateSysDictionary(dictionary);
			if(count <= 0)
				record.put("success", false);
		} else {
			record.put("success", false);
		}
		return record;
	}
	
	
}
