/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.workstockcontract.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.utils.UserUtils;
import com.jeeplus.modules.worksupplier.service.WorkSupplierService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
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.transaction.annotation.Transactional;
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.worksupplier.entity.WorkSupplier;
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.workstockcontract.entity.WorkStockContract;
import com.jeeplus.modules.workstockcontract.service.WorkStockContractService;

/**
 * 采购合同Controller
 * @author lw
 * @version 2018-07-11
 */
@Controller
@RequestMapping(value = "${adminPath}/workstockcontract/workStockContract")
public class WorkStockContractController extends BaseController {

	@Autowired
	private WorkStockContractService workStockContractService;
	@Autowired
	private HttpServletRequest request;
	@Autowired
	private ActTaskService actTaskService;
	@Autowired
	private WorkSupplierService workSupplierService;
	@ModelAttribute
	public WorkStockContract get(@RequestParam(required=false) String id) {
		WorkStockContract entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workStockContractService.get(id);
		}
		if (entity == null){
			entity = new WorkStockContract();
		}
		return entity;
	}
	
	/**
	 * 采购合同列表页面
	 */
	@RequiresPermissions("workstockcontract:workStockContract:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkStockContract workStockContract, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkStockContract> page = workStockContractService.findPage(new Page<WorkStockContract>(request, response), workStockContract); 
		model.addAttribute("page", page);
		return "modules/workstockcontract/workStockContractList";
	}

	/**
	 * 查看，增加，编辑采购合同表单页面
	 */
	//@RequiresPermissions(value={"workstockcontract:workStockContract:view","workstockcontract:workStockContract:add","workstockcontract:workStockContract:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkStockContract workStockContract, Model model) {
		String view = "workStockContractForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		if("1".equals(tabId)){
			view = "workStockContractView";
		}else if("3".equals(tabId)){
			ProcessInstance processInstance = actTaskService.getProcIns(workStockContract.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);
				workStockContract.setAct(act);
				view = "workStockContractModify";
			}
		}else if("5".equals(tabId)){
			model.addAttribute("workStockContract", workStockContract);
			view = "workStockContractForms";
			return "modules/workstockcontract/"+view;
		}
		// 环节编号
		String taskDefKey = workStockContract.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && ("hzbzr".equals(taskDefKey))){
			view = "workStockContractAudit";
		}else if(StringUtils.isNotBlank(taskDefKey) &&("gzr".equals(taskDefKey))){
			view = "workStockContractgzAudit";
		}else if (StringUtils.isNotBlank(taskDefKey) && ("sqr".equals(taskDefKey))){
			view = "workStockContractSqrAudit";
		}
		if(StringUtils.isBlank(workStockContract.getCompleteStatus())){
			workStockContract.setCompleteStatus("1");//未完成
			workStockContract.setOfficeName(UserUtils.getSelectOffice().getTopCompany());
		}
		model.addAttribute("workStockContract", workStockContract);
		return "modules/workstockcontract/"+view;
	}
	/**
	 * 暂存
	 */
	@RequestMapping(value = "store")
	public String store(WorkStockContract workStockContract,
						Model model,
						RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workStockContract)){
			return form(workStockContract, model);
		}
		User user = workStockContract.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workStockContract.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
		}
		workStockContract.setStatus("1"); //暂存状态
		workStockContract.setCompanyId(UserUtils.getSelectCompany().getId());
		workStockContract.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workStockContract.getProcessInstanceId()) && workStockContract.getProcessInstanceId().equals("NULL")){
			workStockContract.setProcessInstanceId("");
		}
		if(!workStockContract.getIsNewRecord()){//编辑表单保存
			WorkStockContract t = workStockContractService.get(workStockContract.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workStockContract, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workStockContractService.save(t);//保存
		}else{//新增表单保存
			workStockContractService.save(workStockContract);//保存
		}
		addMessage(redirectAttributes, "保存采购合同成功");
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	/**
	 * 保存采购合同
	 */
	@RequiresPermissions(value={"workstockcontract:workStockContract:add","workstockcontract:workStockContract:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkStockContract workStockContract, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workStockContract)){
			return form(workStockContract, model);
		}
		User user = workStockContract.getCreateBy();
		String sta = workStockContract.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
		}
		//状态设置为审核中
		workStockContract.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workStockContractService.get(workStockContract.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workStockContract.setCompanyId(UserUtils.getSelectCompany().getId());
			workStockContract.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workStockContractService.save(workStockContract, variables,processInstanceId);
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "采购合同申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "采购合同申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "采购合同申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	/**
	 * 工单执行（完成任务）
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkStockContract workStockContract, Model model,
							RedirectAttributes redirectAttributes) {
		try{
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workStockContract.getAct().getTaskDefKey();
			List<User> users = null;
			if ("hzbzr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workStockContract.getProcessInstanceId(), 2);
				if (users==null){
					users = UserUtils.getByRoleActivityEnname("gzr",3,workStockContract.getOfficeId(),"13",workStockContract.getCreateBy());
				}
			}else if("gzr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workStockContract.getProcessInstanceId(), 2);
			}else if("sqr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workStockContract.getProcessInstanceId(), 1);
			}else if("modifyApply".equals(taskDefKey)){
				users = UserUtils.getByProssType(workStockContract.getProcessInstanceId(), 1);
			}
			if ("yes".equals(workStockContract.getAct().getFlag()) && (users==null || users.size()==0)){
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			}else {
				String str =workStockContractService.auditSave(workStockContract,users);
				addMessage(redirectAttributes, str);
			}
		}catch (Exception e){
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workStockContract.getHome()) && "home".equals(workStockContract.getHome())){
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		}else {
			return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
		}
	}
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkStockContract workStockContract,Model model) {
		model.addAttribute("processInstanceId", workStockContract.getProcessInstanceId());
		return "modules/workstockcontract/workTrack";
	}
	/**
	 * 删除采购合同
	 */
	@RequiresPermissions("workstockcontract:workStockContract:del")
	@RequestMapping(value = "delete")
	public String delete(WorkStockContract workStockContract, RedirectAttributes redirectAttributes) {
		workStockContractService.delete(workStockContract);
		addMessage(redirectAttributes, "删除采购合同成功");
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	
	/**
	 * 批量删除采购合同
	 */
	@RequiresPermissions("workstockcontract:workStockContract:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workStockContractService.delete(workStockContractService.get(id));
		}
		addMessage(redirectAttributes, "删除采购合同成功");
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workstockcontract:workStockContract:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkStockContract workStockContract, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "采购合同"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkStockContract> page = workStockContractService.findPage(new Page<WorkStockContract>(request, response, -1), workStockContract);
    		new ExportExcel("采购合同", WorkStockContract.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出采购合同记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workstockcontract:workStockContract: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<WorkStockContract> list = ei.getDataList(WorkStockContract.class);
			for (WorkStockContract workStockContract : list){
				try{
					workStockContractService.save(workStockContract);
					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()+"/workstockcontract/workStockContract/?repage";
    }
	
	/**
	 * 下载导入采购合同数据模板
	 */
	@RequiresPermissions("workstockcontract:workStockContract:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "采购合同数据导入模板.xlsx";
    		List<WorkStockContract> list = Lists.newArrayList(); 
    		new ExportExcel("采购合同数据", WorkStockContract.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
    }
	
	
	/**
	 * 选择供应商
	 */
	@RequestMapping(value = "selectsupplier")
	public String selectsupplier(WorkSupplier supplier, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		supplier.setRemoveSign("1");//正常
		Page<WorkSupplier> page = workSupplierService.findPage(new Page<WorkSupplier>(request, response), supplier);
		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", supplier);
		model.addAttribute("page", page);
		return "modules/sys/gridselectsupplier";
	}
	/**
	 * 强制撤销
	 */
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkStockContract workStockContract,RedirectAttributes redirectAttributes){
		workStockContractService.cancelInvalidate(workStockContract);
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	@RequiresPermissions("workstockcontract:workStockContract:edit")
	@RequestMapping(value = "complete")
	public String complete(WorkStockContract workStockContract, RedirectAttributes redirectAttributes) {
		workStockContractService.updateWorkReimbursementInfo(workStockContract);
		workStockContract.setCompleteStatus("2");
		workStockContractService.updateCompleteStatus(workStockContract);
		addMessage(redirectAttributes, "该采购合同已完成");
		return "redirect:"+Global.getAdminPath()+"/workstockcontract/workStockContract/?repage";
	}
	/**
	 * 获取联系人名称
	 * @return
	 */
	@RequestMapping(value = "getLinkName")
	@ResponseBody
	public String getLinkName() {
		HashMap<Object, Object> map = Maps.newHashMap();
		String obj = request.getParameter("obj");
		WorkSupplier  workSupplier = workSupplierService.get(obj);
		if(workSupplier!=null){
			map.put("linkName",workSupplier.getLinkName());
		}
		return JsonMapper.toJsonString(map);
	}
}