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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.collect.Maps;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workitem.entity.WorkItem;
import org.apache.commons.lang3.StringEscapeUtils;
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 com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workcatalogueitem.service.WorkCatalogueItemService;

/**
 * 物品目录Controller
 * @author chenyuping
 * @version 2018-07-10
 */
@Controller
@RequestMapping(value = "${adminPath}/workcatalogueitem/workCatalogueItem")
public class WorkCatalogueItemController extends BaseController {
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private WorkCatalogueItemService workCatalogueItemService;
	
	@ModelAttribute
	public WorkCatalogueItem get(@RequestParam(required=false) String id) {
		WorkCatalogueItem entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workCatalogueItemService.get(id);
		}
		if (entity == null){
			entity = new WorkCatalogueItem();
		}
		return entity;
	}
	
	/**
	 * 物品目录列表页面
	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkCatalogueItem workCatalogueItem, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkCatalogueItem> page = workCatalogueItemService.findPage(new Page<WorkCatalogueItem>(request, response), workCatalogueItem); 
		model.addAttribute("page", page);
		return "modules/workcatalogueitem/workCatalogueItemList";
	}

	/**
	 * 查看，增加，编辑物品目录表单页面
	 */
	@RequiresPermissions(value={"workcatalogueitem:workCatalogueItem:view","workcatalogueitem:workCatalogueItem:add","workcatalogueitem:workCatalogueItem:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkCatalogueItem workCatalogueItem, Model model) {
		model.addAttribute("workCatalogueItem", workCatalogueItem);
		String view = "workCatalogueItemForm";
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workCatalogueItemview";
		}
		return "modules/workcatalogueitem/"+view;
	}

	/**
	 * 保存物品目录
	 */
	@RequiresPermissions(value={"workcatalogueitem:workCatalogueItem:add","workcatalogueitem:workCatalogueItem:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkCatalogueItem workCatalogueItem, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workCatalogueItem)){
			return form(workCatalogueItem, model);
		}
		if(!workCatalogueItem.getIsNewRecord()){//编辑表单保存
			WorkCatalogueItem t = workCatalogueItemService.get(workCatalogueItem.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workCatalogueItem, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workCatalogueItemService.save(t);//保存
		}else{//新增表单保存
			workCatalogueItem.setOfficeId(UserUtils.getSelectOffice().getId());
			workCatalogueItem.setCompanyId(UserUtils.getSelectCompany().getId());
			workCatalogueItemService.save(workCatalogueItem);//保存
		}
		addMessage(redirectAttributes, "保存物品目录成功");
		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
	}


	/**
	 * 采购新增目录
	 */
	@RequestMapping(value = "contractsave")
	@ResponseBody
	public String contractsave(WorkCatalogueItem workCatalogueItem,
											   Model model, RedirectAttributes redirectAttributes,
											   HttpServletRequest request
	) throws Exception{
		HashMap<Object, Object> map = Maps.newHashMap();
		try {
			if(!workCatalogueItem.getIsNewRecord()){//编辑表单保存
				WorkCatalogueItem t = workCatalogueItemService.get(workCatalogueItem.getId());//从数据库取出记录的值
				MyBeanUtils.copyBeanNotNull2Bean(workCatalogueItem, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
				workCatalogueItemService.save(t);//保存
				map.put("str","修改成功");
			}else{//新增表单保存
				//保存当前人的公司
				workCatalogueItem.setOfficeId(UserUtils.getSelectOffice().getId());
				workCatalogueItem.setCompanyId(UserUtils.getSelectCompany().getId());
				workCatalogueItemService.save(workCatalogueItem);//保存
				map.put("str","新增成功");
			}
			map.put("name",workCatalogueItem.getName());
			map.put("number",workCatalogueItem.getNumber());
			map.put("type",workCatalogueItem.getType());
			map.put("types", DictUtils.getMainDictLabel(workCatalogueItem.getType(),"item_type",""));
			map.put("model",workCatalogueItem.getModel());
			map.put("primaryUnit",workCatalogueItem.getPrimaryUnit());
			String s = StringEscapeUtils.unescapeHtml4(DictUtils.getMainDictLabel(workCatalogueItem.getPrimaryUnit(),"full_count_unit",""));
			map.put("primaryUnits",s);
			map.put("catalogueItemId",workCatalogueItem.getId());
			map.put("msg","true");
		}catch (Exception e){
			map.put("id",workCatalogueItem.getId());
			map.put("msg","false");
		}
		return  JsonMapper.toJsonString(map);
	}
	/**
	 * 删除物品目录
	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem:del")
	@RequestMapping(value = "delete")
	public String delete(WorkCatalogueItem workCatalogueItem, RedirectAttributes redirectAttributes) {
		workCatalogueItemService.delete(workCatalogueItem);
		addMessage(redirectAttributes, "删除物品目录成功");
		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
	}

	/**
	 * 移除恢复物品目录
	 */
	/*@RequiresPermissions("workcatalogueitem:workCatalogueItem:update")*/
	@RequestMapping(value = "update")
	public String update(WorkCatalogueItem workCatalogueItem, RedirectAttributes redirectAttributes, HttpServletRequest request) {
		String flat =request.getParameter("flat");
		if("2".equals(flat)){
			workCatalogueItem.setRemoveFlat("1");
			workCatalogueItemService.removeFlat(workCatalogueItem);
			addMessage(redirectAttributes, "移除物品目录成功");
		}
		if("3".equals(flat)){
			workCatalogueItem.setRemoveFlat("0");
			workCatalogueItemService.removeFlat(workCatalogueItem);
			addMessage(redirectAttributes, "恢复物品目录成功");
		}

		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
	}
	
	/**
	 * 批量删除物品目录
	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workCatalogueItemService.delete(workCatalogueItemService.get(id));
		}
		addMessage(redirectAttributes, "删除物品目录成功");
		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkCatalogueItem workCatalogueItem, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物品目录"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkCatalogueItem> page = workCatalogueItemService.findPage(new Page<WorkCatalogueItem>(request, response, -1), workCatalogueItem);
    		new ExportExcel("物品目录", WorkCatalogueItem.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物品目录记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem: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<WorkCatalogueItem> list = ei.getDataList(WorkCatalogueItem.class);
			for (WorkCatalogueItem workCatalogueItem : list){
				try{
					workCatalogueItemService.save(workCatalogueItem);
					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()+"/workcatalogueitem/workCatalogueItem/?repage";
    }
	
	/**
	 * 下载导入物品目录数据模板
	 */
	@RequiresPermissions("workcatalogueitem:workCatalogueItem:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物品目录数据导入模板.xlsx";
    		List<WorkCatalogueItem> list = Lists.newArrayList(); 
    		new ExportExcel("物品目录数据", WorkCatalogueItem.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workcatalogueitem/workCatalogueItem/?repage";
    }



	/**
	 * 选择固定资产
	 */
	@RequestMapping(value = "selectCatalog")
	public String selectItem(WorkCatalogueItem workCatalogueItem, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkCatalogueItem> page = workCatalogueItemService.findCatalogPage(new Page<WorkCatalogueItem>(request, response),  workCatalogueItem);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", workCatalogueItem);
		model.addAttribute("page", page);
		return "modules/sys/gridselectCatalog";
	}
}