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

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

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

import com.google.common.base.Strings;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workbidingproject.entity.WorkBidingProject;
import com.jeeplus.modules.workbidingproject.service.WorkBidingProjectService;
import com.jeeplus.modules.workbidproject.entity.WorkBidProject;
import com.jeeplus.modules.workbidproject.service.WorkBidProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientAttachment;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.entity.WorkClientLinkman;
import com.jeeplus.modules.workengineeringproject.entity.WorkEngineeringProject;
import com.jeeplus.modules.workengineeringproject.service.WorkEngineeringProjectService;
import com.jeeplus.modules.workfullmanage.dao.WorkFullManageDao;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
import com.jeeplus.modules.workfullmanage.service.WorkFullRecordService;
import com.jeeplus.modules.workproject.dao.WorkProjectDao;
import com.jeeplus.modules.workprojectnotify.entity.WorkProjectNotify;
import com.jeeplus.modules.workprojectnotify.service.WorkProjectNotifyService;
import com.jeeplus.modules.workreimbursement.utils.VarStr;
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 com.jeeplus.modules.workcontractinfo.entity.WorkContractInfo;
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.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;

/**
 * 总项目管理Controller
 * @author liuw
 * @version 2017-11-29
 */
@Controller
@RequestMapping(value = "${adminPath}/workproject/workProject")
public class WorkProjectController extends BaseController {

	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private WorkFullRecordService workFullRecordService;
	@Autowired
	private WorkProjectDao workProjectDao;
	@Autowired
	private WorkBidProjectService workBidProjectService;
	@Autowired
	private WorkBidingProjectService workBidingProjectService;
	@Autowired
	private WorkEngineeringProjectService workEngineeringProjectService;
	@Autowired
	private WorkFullManageDao workFullManageDao;
	@Autowired
	private WorkFullManageService workFullManageService;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;

	@ModelAttribute
	public WorkProject get(@RequestParam(required=false) String id) {
		WorkProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workProjectService.get(id);
		}
		if (entity == null){
			entity = new WorkProject();
		}
		return entity;
	}
	
	/**
	 * 项目管理列表页面
	 */
	@RequiresPermissions("workproject:workProject:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkProject workProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkProject> page = workProjectService.findPage(new Page<WorkProject>(request, response), workProject);
		List<WorkProject> list =  page.getList();
		List<WorkProject> list2 = new ArrayList<WorkProject>();
		if(list!=null){
			for (int i =0;i<list.size();i++) {
				WorkProject w = list.get(i);
				if(!("投标项目").equals(w.getSort())){
					list2.add(w);
				}
			}
			page.setList(list2);
		}
		model.addAttribute("page", page);
		return "modules/workproject/workProjectList";
	}

	/**
	 * 查看，增加，编辑项目管理表单页面
	 */
	@RequiresPermissions(value={"workbidproject:workBidProject:view","workbidingproject:workBidingProject:view","workengineeringproject:workEngineeringProject:view","workfullmanage:workFullManage:view","workproject:workProject:view","workproject:workProject:add","workproject:workProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkProject workProject, Model model,HttpServletRequest request) {
		String view = request.getParameter("view");
		//投标项目
		if(StringUtils.isNotBlank(view)&&view.equals("1")){
			WorkBidProject workBidProject = workBidProjectService.findUniqueByProperty("work_project_id", workProject.getId());
			model.addAttribute("workBidProject", workBidProject);
			return "modules/workbidproject/workBidProjectView";
		}
		//招标代理
		if(StringUtils.isNotBlank(view)&&view.equals("2")){
			WorkBidingProject workBidingProject = workBidingProjectService.findUniqueByProperty("work_project_id", workProject.getId());
			String id = null;
			if(workBidingProject!=null){
				id = workBidingProject.getId();
			}
			/*model.addAttribute("workBidingProject", workBidingProject);
			return "modules/workbidingproject/workBidingProjectView";*/
			return "redirect:"+Global.getAdminPath()+"/workbidingproject/workBidingProject/form?name=view&id="+id;
		}
		//工程咨询
		if(StringUtils.isNotBlank(view)&&view.equals("3")){
			WorkEngineeringProject workEngineeringProject = workEngineeringProjectService.findUniqueByProperty("project_id", workProject.getId());
			model.addAttribute("workEngineeringProject", workEngineeringProject);
			return "modules/workengineeringproject/workEngineeringProjectView";
		}
		//全过程管理
		if(StringUtils.isNotBlank(view)&&view.equals("4")){
			WorkFullManage workFullManage = workFullManageDao.getByPId(workProject);
			if(workFullManage==null){
				return null;
			}
			String id = workFullManage.getId();
			return "redirect:"+Global.getAdminPath()+"/workfullmanage/workFullManage/form?tabId=0&id="+id;
		}
		model.addAttribute("workProject", workProject);
		return "modules/workproject/workProjectForm";
	}

	/**
	 * 保存项目管理
	 */
	@RequiresPermissions(value={"workproject:workProject:add","workproject:workProject:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkProject workProject, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workProject)){
			return form(workProject, model,request);
		}
		if(!workProject.getIsNewRecord()){//编辑表单保存
			WorkProject t = workProjectService.get(workProject.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workProject, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workProjectService.save(t);//保存
		}else{//新增表单保存
			workProjectService.save(workProject);//保存
		}
		addMessage(redirectAttributes, "保存项目管理成功");
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/?repage";
	}
	
	/**
	 * 删除项目管理
	 */
	@RequiresPermissions("workproject:workProject:del")
	@RequestMapping(value = "delete")
	public String delete(WorkProject workProject, RedirectAttributes redirectAttributes) {
		workProjectService.delete(workProject);
		addMessage(redirectAttributes, "删除项目管理成功");
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/?repage";
	}
	
	/**
	 * 批量删除项目管理
	 */
	@RequiresPermissions("workproject:workProject:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workProjectService.delete(workProjectService.get(id));
		}
		addMessage(redirectAttributes, "删除项目管理成功");
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workproject:workProject:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkProject workProject, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkProject> page = workProjectService.findPage(new Page<WorkProject>(request, response, -1), workProject);
    		new ExportExcel("项目管理", WorkProject.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workproject:workProject: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<WorkProject> list = ei.getDataList(WorkProject.class);
			for (WorkProject workProject : list){
				try{
					workProjectService.save(workProject);
					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()+"/workproject/workProject/?repage";
    }
	
	/**
	 * 下载导入项目管理数据模板
	 */
	@RequiresPermissions("workproject:workProject:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "项目管理数据导入模板.xlsx";
    		List<WorkProject> list = Lists.newArrayList(); 
    		new ExportExcel("项目管理数据", WorkProject.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/?repage";
    }
	
	
	/**
	 * 选择合同外键
	 */
	@RequestMapping(value = "selectcontractId")
	public String selectcontractId(WorkContractInfo contractId, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkContractInfo> page = workProjectService.findPageBycontractId(new Page<WorkContractInfo>(request, response),  contractId);
		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", contractId);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}
	/**
	 * 保存项目归档
	 */
	@RequestMapping(value = "startProcess")
	public String startProcess(WorkProject workProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		WorkFullRecord workFullRecord = new WorkFullRecord();
		if(StringUtils.isNotBlank(workProject.getState())&&workProject.getState().equals("3")){
			WorkFullRecord workFullRecord1 = workFullRecordService.findUniqueByProperty("work_full_manage_id", workProject.getId());
			if(workFullRecord1!=null){
				//workFullRecord = workFullRecord1;
				workFullRecord = workFullRecordService.gett(workFullRecord1.getId());
				model.addAttribute("workFullRecord", workFullRecord);
				return "modules/workproject/workRecordView";
			}
		}
		WorkProject workProject1 = workProjectService.get(workProject.getId());
		workFullRecord.setWorkProject(workProject1);
		workFullRecord.setRecordNumber(workProject1.getNumber());
		workFullRecord.setRecordName(workProject1.getName());
		model.addAttribute("workFullRecord", workFullRecord);
		/*if (StringUtils.isNotBlank(workProject.getName()) && workProject.getName().equals("view")){
			WorkFullRecord workFullRecord1 = workFullRecordService.findUniqueByProperty("work_full_manage_id", workBidingProject.getId());
			workFullRecord1.setWorkBidingProject(workBidingProject1);
			workFullRecord1.setRecordNumber(workBidingProject1.getProjectNumber());
			workFullRecord1.setRecordName(workBidingProject1.getProjectName());
			model.addAttribute("workFullRecord", workFullRecord1);
			return "modules/workaftermath/workRecordView";
		}*/
		return "modules/workproject/workRecordForm";
	}
	/**
	 * 项目归档
	 */
	@RequestMapping(value = "updateRd")
	public String updateRd(WorkFullRecord workFullRecord,HttpServletRequest request, RedirectAttributes redirectAttributes) {

		String bid=  workFullRecord.getWorkProject().getId();
		WorkProject workProject = workProjectService.get(bid);
		WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", bid);
		if(workFullManageId != null){
			addMessage(redirectAttributes, "项目归档已申请，不能重新申请");
			return "redirect:"+Global.getAdminPath()+"/workproject/workProject/list";
		}
		//workFullManageId.preInsert();
		workFullRecord.setCompanyId(UserUtils.getSelectCompany().getId());
		WorkFullManage w = new WorkFullManage();
		w.setId(bid);
		workFullRecord.setWorkFullManage(w);
		workFullRecord.setOfficeId(workProject.getOfficeId()==null?"":workProject.getOfficeId());
		workFullRecord.setType("5");
		workFullRecord.setBackRecordStatus(VarStr.BACKRECORD_STATUS[1]);
		workFullRecordService.save(workFullRecord);


		//Role r = new Role();
		//r.setEnname(gly.toString());
		//Role rolegd =  roleDao.getByEnname(r);
		//List<User> userList = systemService.findUser(new User(new Role(rolegd.getId())));
		//workFullManageId.setManageUser(userList==null||userList.size()==0?"":userList.get(0).getId());
		//workFullRecordService.startposs(workFullManageId,variables,false,"4",buffer.toString());//保存

		workProject.setState("3");//此时项目由归档中变为已归档
		workProjectDao.updateStatus(workProject);

		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setRemarks("待通知");
		workProjectNotify.setUser(workProject.getCreateBy());
		workProjectNotify.setTitle("由您创建的项目："+workProject.getName()+"已完成归档!");
		workProjectNotify.setNotifyId(workFullRecord.getId());
		workProjectNotify.setCompanyId(workFullRecord.getCompanyId());
		workProjectNotify.setContent("项目已归档");
		workProjectNotify.setType("31");
		workProjectNotify.setStatus("0");
		workProjectNotifyService.save(workProjectNotify);
		addMessage(redirectAttributes, "归档完成");
		return "redirect:"+Global.getAdminPath()+"/workproject/workProject/list";
	}

}