package com.palmnest.webapp.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.palmnest.application.Constants;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.bean.Page;
import com.palmnest.application.bean.Pagenation;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.dto.OutTreeDTO;
import com.palmnest.application.dto.WebPageResultDto;
import com.palmnest.application.dto.output.ElementDto;
import com.palmnest.dao.SearchException;
import com.palmnest.model.Element;
import com.palmnest.model.ElementGroup;
import com.palmnest.model.User;
import com.palmnest.service.AppUserService;
import com.palmnest.service.ElementGroupManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
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.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 数据字典管理Controller
 *
 * @author ldb 2014-07-17
 */
@Slf4j
@Controller
@RequestMapping("/system/elementgroup*")
public class ElementGroupController extends BaseFormController {


	private ElementGroupManager elementGroupManager;

	public ElementGroupManager getElementGroupManager() {
		return elementGroupManager;
	}

	@Autowired
	public void setElementGroupManager(ElementGroupManager elementGroupManager) {
		this.elementGroupManager = elementGroupManager;
	}

	@Autowired
	private AppUserService appUserService;

	/**
	 * 跳转页面 后续放开
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping()
	public ModelAndView query(HttpServletRequest request, HttpServletResponse response) {
		initFunctionOperate(request); // 初始化功能操作权限
		return new ModelAndView("admin/elementgroupList");
	}

	/**
	 * 按条件查询数据字典列表
	 *
	 * @param elementGroup
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public WebPageResultDto getList(@ModelAttribute("elementGroup") ElementGroup elementGroup,
									HttpServletRequest request, HttpServletResponse response) {
		try {
			int pageNo = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer
					.valueOf(request.getParameter("pageNo")) : 1;
			List<Criterion> lst = new ArrayList<Criterion>();

			if (StringUtils.isNotEmpty(elementGroup.getGroupcode())) {
				lst.add(Restrictions.like("groupcode",
						"%" + elementGroup.getGroupcode() + "%"));
			}
			if (StringUtils.isNotEmpty(elementGroup.getGroupname())) {
				lst.add(Restrictions.like("groupname",
						"%" + elementGroup.getGroupname() + "%"));
			}
			// 过滤掉删除的记录
			lst.add(Restrictions.ne("isenabled", ElementConstant.YESORNO_0));

			Pagenation<ElementGroup> p   = elementGroupManager.queryElementGroup(pageNo, lst);
			List<Long>               ids = new ArrayList<Long>();
			for (ElementGroup elementgroup : p.getItems()) {
				ids.add(elementgroup.getId());
				Map<Long, String> element = elementGroupManager.getElementIds(ids);
				elementgroup.setExtraData(element.get(elementgroup.getId()));
				elementgroup.setFuncName("其它");
				if (elementgroup.getItemId() != null) {
					Element ele = elementGroupManager.getElementId(elementgroup.getItemId());
					elementgroup.setFuncName(ele.getItemname());
				}

			}
//			Map<Long, String> element = elementGroupManager.getElementIds(ids);
//			if (element != null && element.size() != 0)
//				p.setExtraData(element);
			WebPageResultDto dto = new WebPageResultDto("200", "成功", p.getItems());
			dto.setCount((long) p.getTotalCount());
			return dto;
		} catch (SearchException se) {
			log.error("查询数据字典列表异常 getList ==========>" + se.getMessage());
		}

		return new WebPageResultDto("100", "查询失败", null);
	}

	/**
	 * 跳转到添加界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/preAdd*")
	public ModelAndView preAdd(HttpServletRequest request,
							   HttpServletResponse response) {
		Model            model    = new ExtendedModelMap();
		List<ElementDto> elements = getElementList();// 所属功能列表
		model.addAttribute("funcList", elements);
		return new ModelAndView("admin/elementgroupAdd", model.asMap());
	}

	/**
	 * 跳转到编辑界面
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/preModify*")
	public ModelAndView preModify(HttpServletRequest request,
								  HttpServletResponse response) {
		Model model = new ExtendedModelMap();
		int pageNo = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer
				.valueOf(request.getParameter("pageNo")) : 1;
		List<Criterion> lst = new ArrayList<Criterion>();
		String          _id = request.getParameter("id");
		ElementGroup elementGroup = this.elementGroupManager
				.getElementGroupId(Long.valueOf(_id));
		lst.add(Restrictions.eq("elementGroup.id", elementGroup.getId()));
		// 过滤掉删除的记录
		lst.add(Restrictions.ne("isenabled", ElementConstant.YESORNO_0));
		Pagenation<Element> p        = elementGroupManager.queryElement(pageNo, lst);
		List<ElementDto>    elements = getElementList();// 所属功能列表
		model.addAttribute("funcList", elements);
		model.addAttribute("elementGroup", elementGroup);
		model.addAttribute("page", p);
		return new ModelAndView("admin/elementgroupModify", model.asMap());
	}

	/**
	 * 保存Group
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/saveElementGroup*")
	public ModelAndView saveGroup(@ModelAttribute("elementGroup") ElementGroup elementGroup,
								  HttpServletRequest request, HttpServletResponse response) {
		long optversion = this.elementGroupManager
				.getTabMaxOptVersion(Constants.TB_DICTIONARY_GROUP);
		Model model = new ExtendedModelMap();

		// 获取当前用户
		User user = getUserManager().getUserByUsername(request.getRemoteUser());
		if (elementGroup != null && elementGroup.getId() != null) {
			elementGroup.setLastUpdatedBy(user.getUsername() + ","
					+ user.getFullName());// 修改人
			elementGroup.setLastUpdatedTime(new Date());// 修改时间
			elementGroup.setOpratetype(ElementConstant.OPRATETYPE_UPD);
		} else {
			elementGroup.setCreateBy(user.getUsername() + ","
					+ user.getFullName());// 添加人
			elementGroup.setCreatedTime(new Date());// 添加时间
			elementGroup.setOpratetype(ElementConstant.OPRATETYPE_ADD);
		}
		elementGroup.setOprateversion(optversion + 1);
		elementGroup.setIsenabled(ElementConstant.YESORNO_1);

		ElementGroup New_elementGroup = this.elementGroupManager.save(elementGroup);
		model.addAttribute("elementGroup", New_elementGroup);
		List<ElementDto> elements = getElementList();// 所属功能列表
		model.addAttribute("funcList", elements);
		return new ModelAndView("admin/elementgroupModify", model.asMap());
	}

	/**
	 * 保存element
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/saveElement*")
	public ModelAndView saveElement(@ModelAttribute("element") Element element,
									HttpServletRequest request, HttpServletResponse response) {
		// 获取当前用户
		User            user         = getUserManager().getUserByUsername(request.getRemoteUser());
		Model           model        = new ExtendedModelMap();
		int             pageNo       = StringUtils.isNotEmpty(request.getParameter("pageNo")) ? Integer.parseInt(request.getParameter("pageNo")) : 1;
		List<Criterion> lst          = new ArrayList<Criterion>();
		ElementGroup    elementGroup = this.elementGroupManager.getElementGroupId(element.getElementGroup().getId());
		long            optversion   = this.elementGroupManager.getTabMaxOptVersion(Constants.TB_DICTIONARY_ITEM);
		if (element != null) {
			if (element.getId() != null) {
				element.setLastUpdatedBy(user.getUsername() + "," + user.getFullName());// 修改人
				element.setLastUpdatedTime(new Date());// 修改时间
				element.setOpratetype(ElementConstant.OPRATETYPE_UPD);
				element.setElementGroup(elementGroup);
			} else {
				element.setCreateBy(user.getUsername() + "," + user.getFullName());// 添加人
				element.setCreatedTime(new Date());// 添加时间
				element.setOpratetype(ElementConstant.OPRATETYPE_ADD);
			}
		}
		element.setOprateversion(optversion + 1);
		element.setIsenabled(ElementConstant.YESORNO_1);
		Element New_element = null;
		if (StringUtils.isNotEmpty(element.getItemname())) {
			New_element = this.elementGroupManager.saveElement(element);
		}
		lst.add(Restrictions.eq("elementGroup.id", elementGroup.getId()));
		Pagenation<Element> p = elementGroupManager.queryElement(pageNo, lst);
		model.addAttribute("element", New_element);
		model.addAttribute("elementGroup", elementGroup);
		model.addAttribute("page", p);
		return new ModelAndView("admin/elementgroupModify", model.asMap());
	}

	/**
	 * Element 编辑
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/elementModify*")
	public ModelAndView elementModify(HttpServletRequest request,
									  HttpServletResponse response) {
		Model  model = new ExtendedModelMap();
		String _id   = request.getParameter("id");
		model.addAttribute("element",
				elementGroupManager.getElementId(Long.valueOf(_id)));
		model.addAttribute("elementGroup",
				elementGroupManager.getElementId(Long.valueOf(_id)));
		return new ModelAndView("admin/elementModify", model.asMap());
	}

	/**
	 * 删除ElementGroup数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/deleteGroup*", method = RequestMethod.POST)
	public void deleteGroup(HttpServletRequest request,
							HttpServletResponse response) {
		String[] items = request.getParameterValues("id");
		if (!ArrayUtils.isEmpty(items)) {
			Long[] ids = new Long[items.length];
			for (int i = 0; i < items.length; i++)
				ids[i] = Long.valueOf(items[i]);
			elementGroupManager.removeElementGroups(ids);
		}
	}

	/**
	 * 删除Element数据
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/deleteElement*", method = RequestMethod.POST)
	public void deleteElement(HttpServletRequest request,
							  HttpServletResponse response) {
		String[] items = request.getParameterValues("id");
		if (!ArrayUtils.isEmpty(items)) {
			Long[] ids = new Long[items.length];
			for (int i = 0; i < items.length; i++)
				ids[i] = Long.valueOf(items[i]);
			elementGroupManager.removeElement(ids);
		}
	}

	/**
	 * 设备分类树
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/allElementGroup*", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody
	List<OutTreeDTO> queryTypeTree(HttpServletRequest request,
								   HttpServletResponse response) {
		List<ElementGroup> list  = elementGroupManager.getAllDataList();
		List<OutTreeDTO>   trees = new ArrayList<OutTreeDTO>();
		for (ElementGroup type : list) {
			OutTreeDTO obj = new OutTreeDTO();
			obj.setId(type.getGroupcode()); // 节点点id
			obj.setName(type.getGroupcode() + "(" + type.getGroupname() + ")"); // 节点名称
			obj.setpId("0"); // 父节点id
			trees.add(obj);
		}
		// 根节点
		OutTreeDTO obj1 = new OutTreeDTO();
		obj1.setId("0");
		obj1.setName("选择数据字典");
		obj1.setpId("-1");
		obj1.setLevel("0");
		trees.add(obj1);
		return trees;
	}


	/**
	 * 获取所属功能列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/funcList")
	@ResponseBody
	public AppResultDto funcList(HttpServletRequest request) {
		return AppResultUtil.createSuccesDto(getElementList());
	}

	public List<ElementDto> getElementList() {
		// 获取所属功能列表
		List<Element>    elements = elementGroupManager.getElementsByGroupName("funcList");
		List<ElementDto> list     = new ArrayList<ElementDto>();

		// 默认添加'其它'分类
		ElementDto other = new ElementDto();
		other.setItemname("其它");
		other.setSort(0L);
		list.add(other);

		if (elements != null && elements.size() > 0) {
			for (Element e : elements) {
				ElementDto dto = new ElementDto(e.getId(), e.getItemname(), e.getItemcode());
				dto.setSort(e.getOrderno());
				list.add(dto);
			}

			Collections.sort(list, new Comparator<ElementDto>() {
				public int compare(ElementDto o1, ElementDto o2) {
					return (int) (o1.getSort() - o2.getSort());
				}
			});
		}
		return list;
	}


	// ------------------------ 项目常用选项配置部分 start ------------------------

	/**
	 * 去项目配置列表页
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/toOrgSettingListPage")
	public ModelAndView toOrgSettingListPage(HttpServletRequest request) {
		Model model = new ExtendedModelMap();
		initPageOrgInfo(request, model);
		return new ModelAndView("admin/orgSettingList", model.asMap());
	}

	/**
	 * 获取项目配置列表
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/orgSettingList")
	@ResponseBody
	public WebPageResultDto orgSettingList(HttpServletRequest request) {

		String orgId     = request.getParameter("orgId");// 项目id
		String groupName = request.getParameter("groupName");// 数据字典组名称
		String funcId    = request.getParameter("funcId");// 所属功能
		String pageSize  = request.getParameter("pageSize");
		String pageNo    = request.getParameter("pageNo");

		if (org.apache.commons.lang3.StringUtils.isBlank(pageNo)) {
			pageNo = "1";
		}

		if (org.apache.commons.lang3.StringUtils.isBlank(pageSize)) {
			pageSize = "10";
		}

//		if (org.apache.commons.lang3.StringUtils.isBlank(orgId)){
//			return new WebPageResultDto("100","项目id为空!",null);
//		}
		log.info("ElementGroupController orgSettingList=======>orgId:{},groupName:{},funcId:{},pageSize:{},pageNo:{}", orgId, groupName, funcId, pageSize, pageNo);

		HashMap<String, String> map = new HashMap<String, String>();
		map.put("orgId", orgId);
		map.put("groupName", groupName);
		map.put("funcId", funcId);

		try {
			Page             pagenation = elementGroupManager.orgSettingList(Integer.parseInt(pageNo), Integer.parseInt(pageSize), map);
			WebPageResultDto dto        = new WebPageResultDto("200", "成功", pagenation.getItems());
			dto.setCount(pagenation.getTotalCount());
			return dto;
		} catch (Exception e) {
			log.error("查询列表失败 orgSettingList ===>" + e.getMessage());
			return new WebPageResultDto("100", "查询列表失败", null);
		}
	}

	/**
	 * 获取项目配置列表详情
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/orgSettingDetail")
	@ResponseBody
	public AppResultDto orgSettingInfo(HttpServletRequest request) {
		String groupId = request.getParameter("groupId");
		String orgId   = request.getParameter("orgId");
		if (org.apache.commons.lang3.StringUtils.isAnyBlank(groupId, orgId)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		log.info("ElementGroupController orgSettingInfo===>groupId:{},orgId:{}", groupId, orgId);

		Map<String, Object> result = new HashMap<String, Object>();
		List<ElementDto>    list   = elementGroupManager.getOrgElementGroupInfo(Integer.parseInt(orgId), Long.parseLong(groupId));
		ElementGroup        group  = elementGroupManager.getElementGroupId(Long.parseLong(groupId));

		if (group.getItemId() != null) {
			Element element = elementGroupManager.getElementId(group.getItemId());
			result.put("funcName", element.getItemname());
		} else {
			result.put("funcName", "其它");
		}

		result.put("groupName", group.getGroupname());
		result.put("setting", list);
		return AppResultUtil.createSuccesDto(result);
	}


	/**
	 * 新增/修改 项目配置
	 *
	 * @param request
	 * @return
	 */
	@RequestMapping("/saveUpdateOrgSetting")
	@ResponseBody
	public AppResultDto saveUpdateOrgSetting(HttpServletRequest request) {
		String groupId = request.getParameter("groupId");
		String orgId   = request.getParameter("orgId");
		if (org.apache.commons.lang3.StringUtils.isAnyBlank(groupId, orgId)) {
			return AppResultUtil.createErrorDto("100", "必填参数为空");
		}
		log.info("ElementGroupController saveUpdateOrgSetting===>groupId:{},orgId:{}", groupId, orgId);

		String elements = request.getParameter("elements");// 配置列表

		try {
			if (org.apache.commons.lang3.StringUtils.isNotBlank(elements)) {
				List<ElementDto> dtos      = new ArrayList<ElementDto>();
				JSONArray        jsonArray = JSON.parseArray(elements);
				for (int i = 0; i < jsonArray.size(); i++) {
					com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
					ElementDto                      dto    = new ElementDto();
					dto.setId(object.getLong("id"));
					dto.setItemname(object.getString("itemname"));
					dto.setSort(object.getLong("sort"));
					dtos.add(dto);
				}

				elementGroupManager.saveUpdateOrgSetting(dtos, Integer.parseInt(orgId), Long.parseLong(groupId));
			}
			return AppResultUtil.createSuccesDto();
		} catch (Exception e) {
			log.error("保存修改项目配置异常========>:" + e.getMessage());
			return AppResultUtil.createErrorDto("100", "操作失败");
		}
	}

	// ------------------------ 项目常用选项配置部分 end ------------------------
}
