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

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

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

import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workaftermath.dao.WorkAftermathDao;
import com.jeeplus.modules.workbidingproject.dao.WorkBidingProjectDao;
import com.jeeplus.modules.workbidingproject.service.WorkBidingProjectService;
import com.jeeplus.modules.workclientinfo.entity.WorkClientInfo;
import com.jeeplus.modules.workclientinfo.service.WorkClientInfoService;
import com.jeeplus.modules.workfullmanage.entity.WorkFullManage;
import com.jeeplus.modules.workfullmanage.entity.WorkFullRecord;
import com.jeeplus.modules.workfullmanage.service.WorkFullRecordService;
import com.jeeplus.modules.workproject.dao.WorkProjectDao;
import com.jeeplus.modules.workproject.entity.WorkProject;
import com.jeeplus.modules.workproject.service.WorkProjectService;
import com.jeeplus.modules.workprojectdeposit.dao.WorkProjectDepositDao;
import com.jeeplus.modules.workprojectdeposit.entity.WorkProjectDeposit;
import com.jeeplus.modules.workprojectdeposit.service.WorkProjectDepositService;
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.workbidingproject.entity.WorkBidingProject;
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.workaftermath.entity.WorkAftermath;
import com.jeeplus.modules.workaftermath.service.WorkAftermathService;

/**
 * 评标后工作管理Controller
 * @author liuw
 * @version 2017-12-26
 */
@Controller
@RequestMapping(value = "${adminPath}/workaftermath/workAftermath")
public class WorkAftermathController extends BaseController {

	@Autowired
	private WorkAftermathService workAftermathService;
	@Autowired
	private WorkBidingProjectService workBidingProjectService;
	@Autowired
	private WorkAftermathDao workAftermathDao;
	@Autowired
	private WorkProjectDepositDao workProjectDepositDao;
	@Autowired
	private WorkProjectNotifyService workProjectNotifyService;
	@Autowired
	private WorkBidingProjectDao workBidingProjectDao;
	@Autowired
	private WorkFullRecordService workFullRecordService;
	@Autowired
	private WorkProjectService workProjectService;
	@Autowired
	private WorkProjectDao workProjectDao;
	@Autowired
	private WorkClientInfoService workClientInfoService;


	@Autowired
	private WorkProjectDepositService workProjectDepositService;
	@ModelAttribute
	public WorkAftermath get(@RequestParam(required=false) String id) {
		WorkAftermath entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workAftermathService.get(id);
		}
		if (entity == null){
			entity = new WorkAftermath();
		}
		return entity;
	}
	
	/**
	 * 评标后工作管理列表页面
	 */
	//@RequiresPermissions("workaftermath:workAftermath:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkAftermath workAftermath, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkAftermath> page = workAftermathService.findPage(new Page<WorkAftermath>(request, response), workAftermath); 
		model.addAttribute("page", page);
		return "modules/workaftermath/workAftermathList";
	}

	/**
	 * 查看，增加，编辑评标后工作管理表单页面
	 */
	//@RequiresPermissions(value={"workaftermath:workAftermath:view","workaftermath:workAftermath:add","workaftermath:workAftermath:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkAftermath workAftermath, Model model,HttpServletRequest request) {
		String pid = request.getParameter("pid");
		if(StringUtils.isBlank(pid)){
			pid = request.getSession().getAttribute("pid").toString();
		}
		WorkAftermath workAftermath2 = workAftermathDao.getBypid(pid);
		if(workAftermath2!=null&&!workAftermath2.equals("")){
			workAftermath = workAftermath2;
		}
		WorkBidingProject workBidingProject = workBidingProjectService.get(pid);
		workAftermath.setWorkBidingProject(workBidingProject);
			StringBuffer sb = new StringBuffer();
			if(workBidingProject.getProjectMaster()!=null&&!workBidingProject.getProjectMaster().equals("")){
				String [] a = StringUtils.split(workBidingProject.getProjectMaster(), ",");
				if(a.length>1){
					for (String id : StringUtils.split(workBidingProject.getProjectMaster(), ",")){
						//this.masterList.add(new User(id));
						String name = UserUtils.get(id).getName();
						sb.append(name+",");
					}
				}else {
					for (String id : StringUtils.split(workBidingProject.getProjectMaster(), ",")) {
						//this.masterList.add(new User(id));
						String name = UserUtils.get(id).getName();
						sb.append(name);
					}
				}
				workAftermath.setProjectMaster(sb+"");
			}
		List<WorkProjectDeposit> list = workProjectDepositService.findByPid(workBidingProject.getId());
		if(StringUtils.isNotBlank(workBidingProject.getClient().getId())){
			WorkClientInfo workClientInfo = workClientInfoService.get(workBidingProject.getClient().getId());
			workAftermath.setWorkClientInfo(workClientInfo);
		};
		workAftermath.setList(list);
		model.addAttribute("workAftermath", workAftermath);
		request.getSession().getAttribute("pid");
		return "modules/workaftermath/workAftermathForm";
	}

	/**
	 * 保存评标后工作管理
	 */
	//@RequiresPermissions(value={"workaftermath:workAftermath:add","workaftermath:workAftermath:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkAftermath workAftermath, Model model, RedirectAttributes redirectAttributes,HttpServletRequest request) throws Exception{
		if (!beanValidator(model, workAftermath)){
			return form(workAftermath, model,request);
		}
		if(!workAftermath.getIsNewRecord()){//编辑表单保存
			WorkAftermath t = workAftermathService.get(workAftermath.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workAftermath, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workAftermathService.save(t);//保存
		}else{//新增表单保存
			workAftermath.setCompanyId(UserUtils.getSelectCompany().getId());
			workAftermath.setOfficeId(UserUtils.getSelectOffice().getId());
			WorkBidingProject workBidingProject = workBidingProjectService.get(workAftermath.getWorkBidingProject().getId());
				StringBuffer sb = new StringBuffer();
				if(workBidingProject.getProjectMaster()!=null&&!workBidingProject.getProjectMaster().equals("")){
					for (String id : StringUtils.split(workBidingProject.getProjectMaster(), ",")){
						String name = UserUtils.get(id).getName();
						sb.append(name+",");
					}
					workAftermath.setProjectMaster(sb+"");
				}
			workAftermathService.save(workAftermath);//保存
		}
		addMessage(redirectAttributes, "保存评标后工作管理成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingprojectmg/workBidingProjectmg/list";
	}
	
	/**
	 * 删除评标后工作管理
	 */
	//@RequiresPermissions("workaftermath:workAftermath:del")
	@RequestMapping(value = "delete")
	public String delete(WorkAftermath workAftermath, RedirectAttributes redirectAttributes) {
		workAftermathService.delete(workAftermath);
		addMessage(redirectAttributes, "删除评标后工作管理成功");
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/?repage";
	}
	
	/**
	 * 批量删除评标后工作管理
	 */
	//@RequiresPermissions("workaftermath:workAftermath:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workAftermathService.delete(workAftermathService.get(id));
		}
		addMessage(redirectAttributes, "删除评标后工作管理成功");
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	//@RequiresPermissions("workaftermath:workAftermath:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkAftermath workAftermath, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评标后工作管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkAftermath> page = workAftermathService.findPage(new Page<WorkAftermath>(request, response, -1), workAftermath);
    		new ExportExcel("评标后工作管理", WorkAftermath.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出评标后工作管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	//@RequiresPermissions("workaftermath:workAftermath: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<WorkAftermath> list = ei.getDataList(WorkAftermath.class);
			for (WorkAftermath workAftermath : list){
				try{
					workAftermathService.save(workAftermath);
					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()+"/workaftermath/workAftermath/?repage";
    }
	
	/**
	 * 下载导入评标后工作管理数据模板
	 */
	@RequiresPermissions("workaftermath:workAftermath:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评标后工作管理数据导入模板.xlsx";
    		List<WorkAftermath> list = Lists.newArrayList(); 
    		new ExportExcel("评标后工作管理数据", WorkAftermath.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/?repage";
    }
	
	
	/**
	 * 选择招标项目
	 */
	@RequestMapping(value = "selectworkBidingProject")
	public String selectworkBidingProject(WorkBidingProject workBidingProject, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<WorkBidingProject> page = workAftermathService.findPageByworkBidingProject(new Page<WorkBidingProject>(request, response),  workBidingProject);
		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", workBidingProject);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}

	/**
	 * 确认中标企业
	 */
	@RequestMapping(value = "updateBiding")
	public String updateBiding(WorkProjectDeposit workProjectDeposit,HttpServletRequest request) {
		workProjectDeposit.setBidingState("1");//1为已中标
		workProjectDepositDao.updateState(workProjectDeposit);
		WorkProjectDeposit workProjectDeposit2 = workProjectDepositService.get(workProjectDeposit.getId());
		request.getSession().setAttribute("pid",workProjectDeposit2.getBidingProject().getId());
		List<WorkProjectDeposit> list = workProjectDepositService.findByPid(workProjectDeposit2.getBidingProject().getId());
		list.remove(workProjectDeposit);
		for (WorkProjectDeposit w:
			 list) {
			w.setBidingState("2");//2为未中标
			workProjectDepositDao.updateState(w);
		}
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/form";
	}
	/**
	 * 退还保证金
	 */
	@RequestMapping(value = "updateStatus")
	public String updateStatus(WorkProjectDeposit workProjectDeposit,HttpServletRequest request) {
		workProjectDeposit.setDepositStatus("3");//3为已退还
		workProjectDepositDao.updateStatus(workProjectDeposit);
		WorkProjectDeposit workProjectDeposit2 = workProjectDepositService.get(workProjectDeposit.getId());
		request.getSession().setAttribute("pid",workProjectDeposit2.getBidingProject().getId());

		Role role = UserUtils.getSelectRole().get(0);
		StringBuffer buffer1 = DateUtils.getByEnnme(role.getEnname());
		buffer1.append("cw");
		//发起通知给财务
		WorkProjectNotify workProjectNotify = new WorkProjectNotify();
		workProjectNotify.setTitle("保证金退还通知");
		workProjectNotify.setNotifyId(workProjectDeposit.getId());
		workProjectNotify.setCompanyId(UserUtils.getSelectCompany().getId());
		workProjectNotify.setContent("保证金退还");
		workProjectNotify.setRemarks("待通知");
		workProjectNotify.setNotifyRole(buffer1.toString());
		workProjectNotify.setType("29");
		workProjectNotify.setStatus("0");
		workProjectNotifyService.save(workProjectNotify);
		//修改总项目归档状态
		if(workProjectDeposit2.getBidingProject()!=null){
			WorkBidingProject workBidingProject = workBidingProjectService.get(workProjectDeposit2.getBidingProject().getId());
			if(getBidState(workBidingProject)&&getMoneyState(workBidingProject)){
				WorkProject workProject = workProjectService.get(workBidingProject.getWorkProject().getId());
				workProject.setState("1");//1为能归档
				workProjectDao.updateStatus(workProject);
				//通知
				StringBuffer buffer = DateUtils.getByEnnme(role.getEnname());
				buffer.append("glygd");//归档管理员角色
				WorkProjectNotify workProjectNotifyy = new WorkProjectNotify();
				workProjectNotifyy.setTitle("招标项目相关业务完成，请归档");
				workProjectNotifyy.setNotifyId(workBidingProject.getId());
				workProjectNotifyy.setNotifyRole(buffer.toString());
				workProjectNotifyy.setCompanyId(workBidingProject.getCompanyId());
				workProjectNotifyy.setContent(workBidingProject.getProjectName()+"已符合归档条件,请归档!");
				workProjectNotifyy.setType("30");
				workProjectNotifyy.setStatus("0");
				workProjectNotifyy.setRemarks("待通知");
				workProjectNotifyService.save(workProjectNotifyy);
			}
		}
		return "redirect:"+Global.getAdminPath()+"/workaftermath/workAftermath/form";
	}
	/**
	 * 保存项目归档
	 */
	@RequestMapping(value = "startposs")
	public String startposs(WorkBidingProject workBidingProject, Model model, RedirectAttributes redirectAttributes) throws Exception{
		WorkFullRecord workFullRecord = new WorkFullRecord();
		WorkBidingProject workBidingProject1 = workBidingProjectService.get(workBidingProject.getId());
		workFullRecord.setWorkBidingProject(workBidingProject1);
		workFullRecord.setRecordNumber(workBidingProject1.getProjectNumber());
		workFullRecord.setRecordName(workBidingProject1.getProjectName());
		workFullRecord.setStartTime(workBidingProject.getProjectStartDate());
		workFullRecord.setEndTime(workBidingProject.getProjectEndDate());
		model.addAttribute("workFullRecord", workFullRecord);
		if (StringUtils.isNotBlank(workBidingProject.getName()) && workBidingProject.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/workaftermath/workRecordForm";
	}
	/**
	 * 项目归档
	 */
	@RequestMapping(value = "updateRd")
	public String updateRd(WorkFullRecord workFullRecord,HttpServletRequest request, RedirectAttributes redirectAttributes) {

		String bid=  workFullRecord.getWorkBidingProject().getId();
		WorkFullRecord workFullManageId = workFullRecordService.findUniqueByProperty("work_full_manage_id", workFullRecord.getWorkBidingProject().getId());
		if(workFullManageId != null){
			addMessage(redirectAttributes, "项目归档已申请，不能重新申请");
			return "redirect:"+Global.getAdminPath()+"/workbidingprojectrd/workBidingProjectrd/list";
		}
		WorkBidingProject workBidingProject = workBidingProjectService.get(bid);
		if(!getBidState(workBidingProject)){
			addMessage(redirectAttributes, "项目未定标");
			return "redirect:"+Global.getAdminPath()+"/workbidingprojectrd/workBidingProjectrd/list";
		}
		if(!getMoneyState(workBidingProject)){
			addMessage(redirectAttributes, "项目相关企业保证金未退还");
			return "redirect:"+Global.getAdminPath()+"/workbidingprojectrd/workBidingProjectrd/list";
		}
		//workFullManageId.preInsert();
		workFullRecord.setCompanyId(UserUtils.getSelectCompany().getId());
		WorkFullManage w = new WorkFullManage();
		w.setId(workBidingProject.getId());
		workFullRecord.setWorkFullManage(w);
		workFullRecord.setOfficeId(workBidingProject.getOffice()==null?"":workBidingProject.getOffice().getId());
		workFullRecord.setType("4");
		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());//保存

		workBidingProject.setStatus("3");
		workBidingProjectDao.updateStatus(workBidingProject);
		addMessage(redirectAttributes, "项目已归档");
		return "redirect:"+Global.getAdminPath()+"/workbidingprojectrd/workBidingProjectrd/list";
	}
	//确定有中标企业
	public boolean getBidState(WorkBidingProject workBidingProject){
		int num = 0;
		List<WorkProjectDeposit> list= workProjectDepositService.findByPid(workBidingProject.getId());
		for (WorkProjectDeposit workProjectDeposit:
				list) {
			if (workProjectDeposit.getBidingState().equals("1")){
				num++;
			}
		}
		if(num == 0){
			return false;
		}else{
			return true;
		}
	}
	//确定保证金已退还
	public boolean getMoneyState(WorkBidingProject workBidingProject){
		int num = 0;
		List<WorkProjectDeposit> list= workProjectDepositService.findByPid(workBidingProject.getId());
		for (WorkProjectDeposit workProjectDeposit:
				list) {
			if (!workProjectDeposit.getDepositStatus().equals("3")){
				num++;
			}
		}
		if(num == 0){
			return true;
		}else{
			return false;
		}
	}
}