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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
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.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workcatalogueitem.service.WorkCatalogueItemService;
import com.jeeplus.modules.workitem.service.WorkItemService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.jeeplus.modules.workitem.entity.WorkItem;
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.workscrap.entity.WorkScrap;
import com.jeeplus.modules.workscrap.service.WorkScrapService;

/**
 * 报废管理Controller
 * @author lw
 * @version 2018-07-16
 */
@Controller
@RequestMapping(value = "${adminPath}/workscrap/workScrap")
public class WorkScrapController extends BaseController {

	@Autowired
	private WorkScrapService workScrapService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkItemService workItemService;
	@Autowired
	private WorkCatalogueItemService workCatalogueItemService;
	@ModelAttribute
	public WorkScrap get(@RequestParam(required=false) String id) {
		WorkScrap entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workScrapService.get(id);
		}
		if (entity == null){
			entity = new WorkScrap();
		}
		return entity;
	}

	/**
	 * 报废管理列表页面
	 */
	@RequiresPermissions("workscrap:workScrap:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkScrap workScrap, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkScrap> page = workScrapService.findPage(new Page<WorkScrap>(request, response), workScrap);
		model.addAttribute("page", page);
		return "modules/workscrap/workScrapList";
	}

	/**
	 * 查看，增加，编辑报废管理表单页面
	 */
	//@RequiresPermissions(value={"workscrap:workScrap:view","workscrap:workScrap:add","workscrap:workScrap:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkScrap workScrap, Model model) {
		String view = "workScrapForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workScrapView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workScrap.getProcessInstanceId());
			if (processInstance!=null) {
				Task taskInfok = actTaskService.getCurrentTaskInfo(processInstance);
				Act act = new Act();
				act.setTaskId(taskInfok.getId());
				act.setTaskName(taskInfok.getName());
				act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
				act.setProcDefId(taskInfok.getProcessDefinitionId());
				act.setProcInsId(taskInfok.getProcessInstanceId());
				act.setTask(taskInfok);
				workScrap.setAct(act);
				view = "workScrapModify";
				return "modules/workscrap/"+view;
			}
		}
		// 环节编号
		String taskDefKey = workScrap.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey)){
			view = "workScrapAudit";
		}
		if(StringUtils.isBlank(workScrap.getId())){
			workScrap.setCreateBy(UserUtils.getUser());
			workScrap.setScrapDate(new Date());
			workScrap.setOfficeName(UserUtils.getSelectOffice().getTopCompany());
		}
		model.addAttribute("workScrap", workScrap);
		return "modules/workscrap/"+view;
	}
	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkScrap workScrap,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workScrap)){
			return form(workScrap, model);
		}
		User user = workScrap.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workScrap.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
		}
		workScrap.setStatus("1"); //暂存状态
		workScrap.setCompanyId(UserUtils.getSelectCompany().getId());
		workScrap.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workScrap.getProcessInstanceId()) && workScrap.getProcessInstanceId().equals("NULL")){
			workScrap.setProcessInstanceId("");
		}
		if(!workScrap.getIsNewRecord()){//编辑表单保存
			WorkScrap t = workScrapService.get(workScrap.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workScrap, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workScrapService.save(t);//保存
		}else{//新增表单保存
			workScrapService.save(workScrap);//保存
		}
		addMessage(redirectAttributes, "保存报废管理成功");
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
	}
	/**
	 * 保存报废管理
	 */
	@RequiresPermissions(value={"workscrap:workScrap:add","workscrap:workScrap:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkScrap workScrap, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workScrap)){
			return form(workScrap, model);
		}
		User user = workScrap.getCreateBy();
		String sta = workScrap.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
		}
		//状态设置为审核中
		workScrap.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workScrapService.get(workScrap.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workScrap.setCompanyId(UserUtils.getSelectCompany().getId());
			workScrap.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workScrapService.save(workScrap, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "报废申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "报废申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "报废申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkScrap workScrap, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			List<User> users = UserUtils.getByProssType(workScrap.getProcessInstanceId(),1);
			String flag = workScrap.getAct().getFlag();
			if ("yes".equals(flag) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str =workScrapService.auditSave(workScrap,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "项目登记流程审批失败");
		}

		if (StringUtils.isNotBlank(workScrap.getHome()) && "home".equals(workScrap.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
		}
	}

	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkScrap workScrap,RedirectAttributes redirectAttributes){
		workScrapService.cancelInvalidate(workScrap);
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkScrap workScrap,Model model) {
		model.addAttribute("processInstanceId", workScrap.getProcessInstanceId());
		return "modules/workscrap/workTrack";
	}

		/**
         * 删除报废管理
         */
	@RequiresPermissions("workscrap:workScrap:del")
	@RequestMapping(value = "delete")
	public String delete(WorkScrap workScrap, RedirectAttributes redirectAttributes) {
		workScrapService.delete(workScrap);
		addMessage(redirectAttributes, "删除报废管理成功");
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
	}

	/**
	 * 批量删除报废管理
	 */
	@RequiresPermissions("workscrap:workScrap:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workScrapService.delete(workScrapService.get(id));
		}
		addMessage(redirectAttributes, "删除报废管理成功");
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workscrap:workScrap:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkScrap workScrap, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "报废管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkScrap> page = workScrapService.findPage(new Page<WorkScrap>(request, response, -1), workScrap);
    		new ExportExcel("报废管理", WorkScrap.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出报废管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workscrap/workScrap/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workscrap:workScrap: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<WorkScrap> list = ei.getDataList(WorkScrap.class);
			for (WorkScrap workScrap : list){
				try{
					workScrapService.save(workScrap);
					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()+"/workscrap/workScrap/?repage";
    }

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


	/**
	 * 选择固定资产
	 */
	@RequestMapping(value = "selectitem")
	public String selectitem(WorkItem item, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		item.setState("1");
		item.setIsAssets("1");
		Page<WorkItem> page = workItemService.findScrapPage(new Page<WorkItem>(request, response), item);
		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", item);
		model.addAttribute("page", page);
		return "modules/sys/gridselectscrap";
	}
	/**
	 * 选择物品
	 */
	@RequestMapping(value = "selectitems")
	public String selectitems(WorkCatalogueItem workCatalogueItem, boolean isSingle,String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		workCatalogueItem.setRemoveFlat("0");
		Page<WorkCatalogueItem> page = workCatalogueItemService.findPage(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("isSingle", isSingle);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", workCatalogueItem);
		model.addAttribute("page", page);
		return "modules/sys/gridselectstock";
	}
	//获取item
	@RequestMapping(value = "getItem")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkItem workItem = workItemService.get(obj);
		if(workItem!=null){
			if(workItem.getWorkCatalogueItem()!=null){
				String cItemId = workItem.getWorkCatalogueItem().getId();
				if(StringUtils.isNotBlank(cItemId)){
					WorkCatalogueItem workCatalogueItem = workCatalogueItemService.get(cItemId);
					if(workCatalogueItem !=null){
						map.put("cName",workCatalogueItem.getName());
						map.put("cNumber",workCatalogueItem.getNumber());
						map.put("cType",DictUtils.getMainDictLabel(workCatalogueItem.getType(),"item_type",""));
						map.put("cModel",workCatalogueItem.getModel());
						String s = StringEscapeUtils.unescapeHtml4(DictUtils.getMainDictLabel(workCatalogueItem.getPrimaryUnit(),"full_count_unit",""));
						map.put("cPrimaryUnit",s);
					}
				}
			}
		}
		return JsonMapper.toJsonString(map);
	}

	//获取item
	@RequestMapping(value = "getItems")
	@ResponseBody
	public WorkCatalogueItem getPNumberrs(String id) throws ParseException {
		WorkItem workItem = workItemService.get(id);
		WorkCatalogueItem workCatalogueItem = new WorkCatalogueItem();
		if(workItem!=null){
			if(workItem.getWorkCatalogueItem()!=null){
				String cItemId = workItem.getWorkCatalogueItem().getId();
				if(StringUtils.isNotBlank(cItemId)){
					 workCatalogueItem = workCatalogueItemService.get(cItemId);
				}
			}
		}
		return  workCatalogueItem;
	}
}