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

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.mapper.JsonMapper;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.web.BaseController;
import com.jeeplus.common.websocket.utils.Constant;
import com.jeeplus.modules.act.entity.Act;
import com.jeeplus.modules.act.service.ActTaskService;
import com.jeeplus.modules.projectrecord.service.ProjectRecordsService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workactivity.service.ActivityService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
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.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.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 投标项目Controller
 * @author mengxy
 * @version 2017-05-27
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workbidproject/workBidProject")
public class  WorkBidProjectController extends BaseController {

	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private WorkProjectService workProjectService;

	@Autowired
	protected RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private ActTaskService actTaskService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private WorkClientInfoService workClientInfoService;
	@Autowired
	private ActivityService activityService;
	@Autowired
	private ProjectRecordsService projectRecordsService;
	@Autowired
	private OfficeService officeService;

	@ModelAttribute
	public WorkBidProject get(@RequestParam(required=false) String id) {
		WorkBidProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workBidProjectService.get(id);
		}
		if (entity == null){
			entity = new WorkBidProject();
		}
		return entity;
	}

	/**
	 * 投标项目列表页面
	 */
	@RequiresPermissions("workbidproject:workBidProject:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBidProject workBidProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkBidProject> page = workBidProjectService.findPage(new Page<WorkBidProject>(request, response), workBidProject);
		model.addAttribute("page", page);
		return "modules/workbidproject/workBidProjectList";
	}

	/**
	 * 查看tabId=1，增加，编辑投标项目表单页面
	 */
	//@RequiresPermissions(value={"workbidproject:workBidProject:view","workbidproject:workBidProject:add","workbidproject:workBidProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBidProject workBidProject, Model model) {
		String view = "workBidProjectForm";
		Office office = UserUtils.getSelectOffice();
		String tabId = request.getParameter("tabId");
		Act actBid = null;
		if(workBidProject!=null && StringUtils.isNotBlank(workBidProject.getProcessInstanceId())){
			actBid = getByAct(workBidProject.getProcessInstanceId());
			if(actBid!=null&&"tbzy".equals(actBid.getTaskDefKey())){
				workBidProject.setSign("tbzy");
			}
		}
		if("1".equals(tabId)){
			view = "workBidProjectView";
		}else if("3".equals(tabId)&&actBid!=null&&!"tbzy".equals(actBid.getTaskDefKey())){
			ProcessInstance processInstance = actTaskService.getProcIns(workBidProject.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);
				workBidProject.setAct(act);
				view = "workBidProjectModify";
			}
		}
		// 环节编号
		String taskDefKey = workBidProject.getAct().getTaskDefKey();
		if (StringUtils.isNotBlank(taskDefKey) && !taskDefKey.equals("modifyApply")){
			if("zjl".equals(workBidProject.getAct().getTaskDefKey())){
				return "modules/workbidproject/workBidProjectzjlAudit";
			}else if("tbzy".equals(workBidProject.getAct().getTaskDefKey())){
				return "modules/workbidproject/workBidProjectbzAudit";
			}else if ("gzr".equals(workBidProject.getAct().getTaskDefKey())){
				return "modules/workbidproject/workBidProjectgzAudit";
			}else if("sqr".equals(workBidProject.getAct().getTaskDefKey())){
				return "modules/workbidproject/workBidProjectkbAudit";
			}else if("scyfglbzrss".equals(workBidProject.getAct().getTaskDefKey())){
				return "modules/workbidproject/workBidProjectwhAudit";
			}else {
				return "modules/workbidproject/workBidProjectAudit";
			}
		}

		if(StringUtils.isBlank(workBidProject.getId())){
			workBidProject.setOfficeName(UserUtils.getSelectOffice().getName());
			workBidProject.setTrialType("0");//标前
		}
		model.addAttribute("workBidProject", workBidProject);
		return "modules/workbidproject/"+view;
	}
	public Act getByAct(String processInstanceId){
		Act act = new Act();
		HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
		ProcessInstance processInstance = actTaskService.getProcIns(processInstanceId);
        if (processInstance != null) {
            List<Task> taskList = actTaskService.getCurrentTaskList(processInstance);
            if (taskList != null && taskList.size() > 1) {
                for (Task taskInfok : taskList) {
                    if (taskInfok.getAssignee().equals(UserUtils.getUser().getId())) {
                        act.setTaskId(taskInfok.getId());
                        act.setTaskName(taskInfok.getName());
                        act.setTaskDefKey(taskInfok.getTaskDefinitionKey());
                        act.setProcDefId(taskInfok.getProcessDefinitionId());
                        act.setProcInsId(taskInfok.getProcessInstanceId());
                        act.setTask(taskInfok);
                    }
                }
            }else {
				Task task = actTaskService.getCurrentTaskInfo(processInstance);
				act.setTaskId(task.getId());
				act.setTaskName(task.getName());
				act.setTaskDefKey(task.getTaskDefinitionKey());
				act.setProcDefId(task.getProcessDefinitionId());
				act.setProcInsId(task.getProcessInstanceId());
				act.setTask(task);
			}
		}
		return  act;
	}
	@RequestMapping(value = "store")
    public String store(WorkBidProject workBidProject,
                        Model model,
                        RedirectAttributes redirectAttributes) throws Exception {
		if (!beanValidator(model, workBidProject)){
			return form(workBidProject, model);
		}

		User user = workBidProject.getCreateBy();
		String submitter = "";
		if(user != null){
			submitter = user.getId();
		}
		String sta = workBidProject.getStatus();
		if(!UserUtils.getUser().getId().equals(submitter) && !Strings.isNullOrEmpty(submitter) && sta != null){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
		}
		workBidProject.setStatus("1"); //暂存状态
		workBidProject.setCompanyId(UserUtils.getSelectCompany().getId());
		workBidProject.setOfficeId(UserUtils.getSelectOffice().getId());
		if (StringUtils.isNotBlank(workBidProject.getProcessInstanceId()) && workBidProject.getProcessInstanceId().equals("NULL")){
			workBidProject.setProcessInstanceId("");
		}
		if(!workBidProject.getIsNewRecord()){//编辑表单保存
			WorkBidProject t =workBidProjectService.get(workBidProject.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workBidProjectService.save(t);//保存
		}else{//新增表单保存
			workBidProjectService.save(workBidProject);//保存
		}
		addMessage(redirectAttributes, "保存投标申请单成功");
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
	}
	/**
	 * 保存投标项目
	 */
	@RequestMapping(value = "save")
	public String save(WorkBidProject workBidProject,
					   Model model,
					   RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBidProject)){
			return form(workBidProject, model);
		}
		User user = workBidProject.getCreateBy();
		String sta = workBidProject.getStatus();
		if(user!=null && !UserUtils.getUser().getId().equals(user.getId()) && StringUtils.isNotBlank(user.getId())){
			addMessage(redirectAttributes, "您不是申请人，无法修改");
			return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
		}
		//状态设置为审核中
//		workBidProject.setStatus("2");
		String processInstanceId ="";
		if (user!=null && StringUtils.isNotBlank(user.getId()) && StringUtils.isNotBlank(sta) && "3".equals(sta)){
			processInstanceId = workBidProjectService.get(workBidProject.getId()).getProcessInstanceId();
		}
		try {
			Map<String, Object> variables = Maps.newHashMap();
			workBidProject.setCompanyId(UserUtils.getSelectCompany().getId());
			workBidProject.setOfficeId(UserUtils.getSelectOffice().getId());
			String str = workBidProjectService.save(workBidProject, variables,processInstanceId,"2");
			if (StringUtils.isNotBlank(str)){
				addMessage(redirectAttributes, "投标申请提交失败:"+str);
			}else {
				addMessage(redirectAttributes, "投标申请已经提交");
			}

		} catch (Exception e) {
			addMessage(redirectAttributes, "投标申请提交失败!");
			addMessage(redirectAttributes, "系统内部错误");
		}
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
	}

	/**
	 * 工单执行（完成任务）
	 * @param workBidProject
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "saveAudit")
	public String saveAudit(WorkBidProject workBidProject,
							Model model,
							RedirectAttributes redirectAttributes) {
		try {
			// 对不同环节的业务逻辑进行操作
			String taskDefKey = workBidProject.getAct().getTaskDefKey();
			String flag = workBidProject.getAct().getFlag();
			List<User> users = null;
			//分管领导
			if ("fgld".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 2);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("scyfglbzr", 3, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			//市场部分管领导负责人
			} else if ("scyfglbzr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 3);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("zjl", 1, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			//总经理
			} else if ("zjl".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 4);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("tbzy", 3, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			//投标专员
			} else if ("tbzy".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 5);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("scyfglbzr", 3, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			} else if ("scyfglbzrs".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 6);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("gzr", 1, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			} else if ("gzr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 6);
			} else if ("sqr".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 8);
				if (users == null)
					users = UserUtils.getByRoleActivityEnname("scyfglbzr", 3, workBidProject.getOfficeId(), "16", workBidProject.getCreateBy());
			} else if ("scyfglbzrss".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 8);
			} else if ("modifyApply".equals(taskDefKey)) {
				users = UserUtils.getByProssType(workBidProject.getProcessInstanceId(), 1);
			}
			if ("yes".equals(flag) && (users == null || users.size() == 0)) {
				addMessage(redirectAttributes, "审批失败,审批人为空,请联系管理员！");
			} else {
				String str = workBidProjectService.auditSave(workBidProject, users);
				addMessage(redirectAttributes, str);
			}
		} catch (Exception e) {
			addMessage(redirectAttributes, "审批失败");
		}
		if (StringUtils.isNotBlank(workBidProject.getHome()) && "home".equals(workBidProject.getHome())) {
			return "redirect:" + Global.getAdminPath() + "/home/?repage";
		} else {
			return "redirect:" + Global.getAdminPath() + "/workbidproject/workBidProject/?repage";
		}
	}

	/**
	 * 删除投标项目
	 */
	@RequiresPermissions("workbidproject:workBidProject:del")
	@RequestMapping(value = "delete")
	public String delete(WorkBidProject workBidProject, RedirectAttributes redirectAttributes) {
		workBidProjectService.delete(workBidProject);
		addMessage(redirectAttributes, "删除投标申请单成功");
		return "redirect:" + Global.getAdminPath() + "/workbidproject/workBidProject/?repage";
	}

	/**
	 * 批量删除投标项目
	 */
	@RequiresPermissions("workbidproject:workBidProject:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workBidProjectService.delete(workBidProjectService.get(id));
		}
		addMessage(redirectAttributes, "删除投标项目成功");
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
	}

	/**
	 * 导出excel文件
	 */
	//@RequiresPermissions("workbidproject:workBidProject:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkBidProject workBidProject, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "投标项目"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkBidProject> page = workBidProjectService.findPage(new Page<WorkBidProject>(request, response, -1), workBidProject);
			System.out.println("===========================\n"+ JSON.toJSONString(page.getList().toString()));
    		new ExportExcel("投标项目", WorkBidProject.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出投标项目记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workbidproject:workBidProject: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<WorkBidProject> list = ei.getDataList(WorkBidProject.class);
			for (WorkBidProject workBidProject : list){
				try{
					workBidProjectService.save(workBidProject);
					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()+"/workbidproject/workBidProject/?repage";
    }

	/**
	 * 下载导入投标项目数据模板
	 */
	@RequiresPermissions("workbidproject:workBidProject:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "投标项目数据导入模板.xlsx";
    		List<WorkBidProject> list = Lists.newArrayList();
    		new ExportExcel("投标项目数据", WorkBidProject.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
    }
	/**
	 * 读取单个实体流程
	 * @return
	 */
	@RequestMapping(value = "getProcessOne")
	public String getProcessOne(WorkBidProject workBidProject,Model model) {
		model.addAttribute("processInstanceId", workBidProject.getProcessInstanceId());
		return "modules/workbidproject/workBidProjectTrack";
	}
	@RequestMapping("cancelInvalidate")
	public String cancelInvalidate(WorkBidProject workBidProject,RedirectAttributes redirectAttributes){
		workBidProjectService.cancelInvalidate(workBidProject);
		return "redirect:"+Global.getAdminPath()+"/workbidproject/workBidProject/?repage";
	}


	/**
	 * 选择招标单位
	 */
	@RequestMapping(value = "selectbidCompany")
	public String selectbidCompany(WorkClientInfo bidCompany, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkClientInfo> page = workClientInfoService.findPage(new Page<WorkClientInfo>(request, response), bidCompany);
		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", bidCompany);
		model.addAttribute("page", page);
		//return "modules/sys/gridselect";
		return "modules/sys/gridselectAhref";
	}
	/**
	 * 选择实施部门
	 */
	@RequestMapping(value = "selectimplementingDept")
	public String selectimplementingDept(Office implementingDept, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Office> page = workBidProjectService.findPageByimplementingDept(new Page<Office>(request, response),  implementingDept);
		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", implementingDept);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	/**
	 * 选择负责人
	 */
	@RequestMapping(value = "selectprojectMaster")
	public String selectprojectMaster(User projectMaster, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<User> page = workBidProjectService.findPageByprojectMaster(new Page<User>(request, response),  projectMaster);
		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", projectMaster);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}


}