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

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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.service.OfficeService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sysmtree.service.SysMtreeService;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workcatalogueitem.entity.WorkCatalogueItem;
import com.jeeplus.modules.workcatalogueitem.service.WorkCatalogueItemService;
import com.jeeplus.modules.workstockcontract.entity.WorkStockContract;
import com.jeeplus.modules.workstockcontract.service.WorkStockContractService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringEscapeUtils;
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.workstock.entity.WorkStock;
import com.jeeplus.modules.workstock.service.WorkStockService;

/**
 * 物品采购Controller
 * @author lw
 * @version 2018-07-13
 */
@Controller
@RequestMapping(value = "${adminPath}/workstock/workStock")
public class WorkStockController extends BaseController {

	@Autowired
	private WorkStockService workStockService;
	@Autowired
	private WorkCatalogueItemService workCatalogueItemService;
	@Autowired
	protected RuntimeService runtimeService;
	@Autowired
	protected WorkStockContractService workStockContractService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@ModelAttribute
	public WorkStock get(@RequestParam(required=false) String id) {
		WorkStock entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workStockService.get(id);
		}
		if (entity == null){
			entity = new WorkStock();
		}
		return entity;
	}
	
	/**
	 * 物品采购列表页面
	 */
	@RequiresPermissions("workstock:workStock:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkStock workStock, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkStock> page = workStockService.findPage(new Page<WorkStock>(request, response), workStock); 
		model.addAttribute("page", page);
		return "modules/workstock/workStockList";
	}

	/**
	 * 查看，增加，编辑物品采购表单页面
	 */
	//@RequiresPermissions(value={"workstock:workStock:view","workstock:workStock:add","workstock:workStock:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkStock workStock, Model model) {
		String view = "workStockForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workStockView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workStock.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);
				workStock.setAct(act);
				view = "workStockModify";
			}
		}
		// 环节编号
		String taskDefKey = workStock.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("zjl".equals(taskDefKey)
		)){
			view = "workStockAudit";
		}
		else  if (StringUtils.isNotBlank(taskDefKey) && "xzzg".equals(taskDefKey)){
			if(workStock.getAcceptDate()== null){
				workStock.setAcceptDate(new Date());
			}
			if(StringUtils.isBlank(workStock.getAcceptName())){
				workStock.setAcceptName(UserUtils.getUser().getName());
			}
			view = "workStockAcceptAudit";
		}else  if (StringUtils.isNotBlank(taskDefKey) && "xzzgs".equals(taskDefKey)){
			view = "workStocksAudit";
		}
		if (StringUtils.isBlank(workStock.getId())){
			workStock.setCreateBy(UserUtils.getUser());
			workStock.setCreateDate(new Date());
			workStock.setOfficeName(UserUtils.getSelectOffice().getTopCompany());
		}

		model.addAttribute("workStock", workStock);
		return "modules/workstock/"+view;
	}

	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkStock workStock,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workStock)){
			return form(workStock, model);
		}

		User user = workStock.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workStock.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
		}
		workStock.setStatus("1"); //暂存状态
		workStock.setCompanyId(UserUtils.getSelectCompany().getId());
		workStock.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workStock.getProcessInstanceId()) && workStock.getProcessInstanceId().equals("NULL")){
			workStock.setProcessInstanceId("");
		}
		if(!workStock.getIsNewRecord()){//编辑表单保存
			WorkStock t = workStockService.get(workStock.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workStock, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workStockService.save(t);//保存
		}else{//新增表单保存
			workStockService.save(workStock);//保存
		}
		addMessage(redirectAttributes, "保存采购申请成功");
		return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
	}

	/**
	 * 保存
	 * 启动流程
	 */
	@RequestMapping(value = "save")
	public String save(WorkStock workStock,
					   Model model,
					   RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workStock)){
			return form(workStock, model);
		}
		User user = workStock.getCreateBy();
		String sta = workStock.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
		}
		//状态设置为审核中
		workStock.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workStockService.get(workStock.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workStock.setCompanyId(UserUtils.getSelectCompany().getId());
			workStock.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workStockService.save(workStock, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "采购申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "采购申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "采购申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:" + adminPath +"/workstock/workStock/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkStock workStock, Model model,
							RedirectAttributes redirectAttributes) {
		try {
			try{
				// 对不同环节的业务逻辑进行操作
				String taskDefKey = workStock.getAct().getTaskDefKey();
				List<User> users = null;
				if ("zjl".equals(taskDefKey)){
					users = UserUtils.getByProssType(workStock.getProcessInstanceId(),2);
					if (users==null )
						users = UserUtils.getByRoleActivityEnname("xzzg",3,workStock.getOfficeId(),"14",workStock.getCreateBy());
				}else  if ("xzzg".equals(taskDefKey)){
					users = UserUtils.getByProssType(workStock.getProcessInstanceId(),3);
					if (users==null )
						users = UserUtils.getByRoleActivityEnname("xzzg",3,workStock.getOfficeId(),"14",workStock.getCreateBy());
				}else  if ("xzzgs".equals(taskDefKey)){
					users = UserUtils.getByProssType(workStock.getProcessInstanceId(),3);
				}else if ("modifyApply".equals(taskDefKey)){
					users = UserUtils.getByProssType(workStock.getProcessInstanceId(),1);
				}
				String flag = workStock.getAct().getFlag();
				if ("yes".equals(flag) && (users==null || users.size()==0)){
					addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
				}else {
					String str = workStockService.auditSave(workStock,users);
					addMessage(redirectAttributes, str);
				}
			}catch (Exception e){
				addMessage(redirectAttributes, "审批失败");
			}
			
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workStock.getHome()) && "home".equals(workStock.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workstock/workStock/?repage";
		}
	}
	/**
	 * 删除物品采购
	 */
	@RequiresPermissions("workstock:workStock:del")
	@RequestMapping(value = "delete")
	public String delete(WorkStock workStock, RedirectAttributes redirectAttributes) {
		workStockService.delete(workStock);
		addMessage(redirectAttributes, "删除物品采购成功");
		return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
	}
	
	/**
	 * 批量删除物品采购
	 */
	@RequiresPermissions("workstock:workStock:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workStockService.delete(workStockService.get(id));
		}
		addMessage(redirectAttributes, "删除物品采购成功");
		return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workstock:workStock:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkStock workStock, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "物品采购"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkStock> page = workStockService.findPage(new Page<WorkStock>(request, response, -1), workStock);
    		new ExportExcel("物品采购", WorkStock.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出物品采购记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
    }

	/**
	 * 导入Excel数据

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

	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkStock workStock,Model model) {
		model.addAttribute("processInstanceId", workStock.getProcessInstanceId());
		return "modules/workstock/workTrack";
	}
	/**
	 * 强制撤回
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkStock workStock,RedirectAttributes redirectAttributes){
		workStockService.cancelInvalidate(workStock);
		return "redirect:"+Global.getAdminPath()+"/workstock/workStock/?repage";
	}
	@RequestMapping(value = "getRow")
	@ResponseBody
	public String getPNumberr() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkCatalogueItem workCatalogueItem = workCatalogueItemService.get(obj);
		if(workCatalogueItem!=null){
			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("id",workClientInfo.getId());
		/*if("1".equals(workClientInfo.getCompanyType())){
			map.put("companyType","政府部门");
		}else if("2".equals(workClientInfo.getCompanyType())){
			map.put("companyType","国企");
		}else if("3".equals(workClientInfo.getCompanyType())){
			map.put("companyType","民企");
		}else if("4".equals(workClientInfo.getCompanyType())){
			map.put("companyType","外资");
		}else if("5".equals(workClientInfo.getCompanyType())){
			map.put("companyType","其他");
		}*/
		/*if("1".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","电力");
		}else if("2".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","房地产");
		}else if("3".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","化工");
		}else if("4".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","农业");
		}else if("5".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","交通");
		}else if("6".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","水利");
		}else if("7".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","水运");
		}else if("8".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","教育");
		}else if("9".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","卫生");
		}else if("10".equals(workClientInfo.getCompanyIndustry())){
			map.put("companyIndustry","服务");
		}*/
		return JsonMapper.toJsonString(map);
	}

	@RequestMapping(value = "getContract")
	public String getContract(WorkStockContract workStockContract, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		workStockContract.setCompanyId(UserUtils.getSelectCompany().getId());
		workStockContract.setStatus("5");
		workStockContract.setCompleteStatus("1");
		Page<WorkStockContract> page = workStockContractService.findPage(new Page<WorkStockContract>(request, response),  workStockContract);
		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", workStockContract);
		model.addAttribute("page", page);
		//return "modules/sys/gridselect";
		return "modules/sys/gridselectstockcontract";
	}

	@RequestMapping(value = "setInfo")
	@ResponseBody
	public String setInfo() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("contractId");
		WorkStockContract workStockContract = workStockContractService.get(obj);
		if(workStockContract!=null){
			map.put("supplierName",workStockContract.getSupplierName());

		}
		return JsonMapper.toJsonString(map);
	}
}