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

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.persistence.Page;
import com.jeeplus.common.utils.DateUtils;
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.modules.sys.entity.Judge;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.service.JudgeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workbidingevaluation.entity.WorkBidingEvaluation;
import com.jeeplus.modules.workbidingevaluation.service.WorkBidingEvaluationService;
import com.jeeplus.modules.workbidingproject.entity.WorkBidingProject;
import com.jeeplus.modules.workevaluationroom.entity.WorkEvaluationRoom;
import com.jeeplus.modules.workevaluationroom.service.WorkEvaluationRoomService;
import com.jeeplus.modules.workprojectdeposit.entity.WorkProjectDeposit;
import com.jeeplus.modules.workprojectdeposit.service.WorkProjectDepositService;
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.*;
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.List;

/**
 * 评标管理Controller
 * @author fgy
 * @version 2017-12-28
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "${adminPath}/workbidingevaluation/workBidingEvaluation")
public class WorkBidingEvaluationController extends BaseController {

	@Autowired
	private WorkBidingEvaluationService workBidingEvaluationService;
	@Autowired
	private WorkProjectDepositService workProjectDepositService;
	@Autowired
	private JudgeService judgeService;
	@Autowired
	private WorkEvaluationRoomService workEvaluationRoomService;

	@ModelAttribute
	public WorkBidingEvaluation get(@RequestParam(required=false) String id) {
		WorkBidingEvaluation entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = workBidingEvaluationService.get(id);
		}
		if (entity == null){
			entity = new WorkBidingEvaluation();
		}
		return entity;
	}
	
	/**
	 * 评标管理列表页面
	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation:list")
	@RequestMapping(value = {"list", ""})
	public String list(WorkBidingEvaluation workBidingEvaluation, HttpServletRequest request, HttpServletResponse response, Model model) {
		Office office = UserUtils.getSelectOffice();
		Page<WorkBidingEvaluation> page = new Page<>();
		if(!office.getName().contains("招标")){
			page.setPageNo(1);
			page.setPageSize(10);
			model.addAttribute("page", page);
			model.addAttribute("addBtn","addBtn");
			return "modules/workbidingevaluation/workBidingEvaluationList";
		}
		if(!UserUtils.getSelectRoleInfo()){
			String id = UserUtils.getUser().getId();
			workBidingEvaluation.setQueryCon(id);
		}

		page = workBidingEvaluationService.findPage(new Page<WorkBidingEvaluation>(request, response), workBidingEvaluation);
		model.addAttribute("page", page);
		return "modules/workbidingevaluation/workBidingEvaluationList";
	}

	/**
	 * 查看，增加，编辑评标管理表单页面
	 */
	@RequiresPermissions(value={"workbidingevaluation:workBidingEvaluation:view","workbidingevaluation:workBidingEvaluation:add","workbidingevaluation:workBidingEvaluation:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(WorkBidingEvaluation workBidingEvaluation, Model model ,HttpServletRequest request) {
		String workBidingProjectId = request.getParameter("workBidingProjectId");

		WorkEvaluationRoom workEvaluationRoom = workBidingEvaluation.getWorkEvaluationRoom();
		if(workEvaluationRoom!=null){
			if(StringUtils.isNotBlank(workEvaluationRoom.getFloor())){
				workEvaluationRoom.setFloor("，"+workEvaluationRoom.getFloor()+"楼，");
			}
			if(StringUtils.isNotBlank(workEvaluationRoom.getHouseNumber())){
				workEvaluationRoom.setHouseNumber(workEvaluationRoom.getHouseNumber()+"室");
			}
		}
		model.addAttribute("workBidingProjectId",workBidingProjectId);
		model.addAttribute("workBidingEvaluation", workBidingEvaluation);
		model.addAttribute("judgeMembersList",workBidingEvaluation.getJudgeMembersList());
		model.addAttribute("judgeMembersBakList",workBidingEvaluation.getJudgeMembersBakList());
		if(request.getParameter("view").equals("view")){
			return "modules/workbidingevaluation/workBidingEvaluationView";
		}
		return "modules/workbidingevaluation/workBidingEvaluationForm";
	}

	/**
	 * 保存评标管理
	 */
	@RequiresPermissions(value={"workbidingevaluation:workBidingEvaluation:add","workbidingevaluation:workBidingEvaluation:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(WorkBidingEvaluation workBidingEvaluation, Model model,HttpServletRequest request, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, workBidingEvaluation)){
			return form(workBidingEvaluation, model,null);
		}
		String workBidingProjectId = request.getParameter("workBidingProjectId");
		if(!workBidingEvaluation.getIsNewRecord()){//编辑表单保存
			WorkBidingEvaluation t = workBidingEvaluationService.get(workBidingEvaluation.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workBidingEvaluation, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workBidingEvaluationService.save(t);//保存
		}else{//新增表单保存
			String pageTime = request.getParameter("currentTime");
			List judgeSession = (List)request.getSession().getAttribute("judgeList_" + pageTime);
			List judgeBakSession = (List)request.getSession().getAttribute("judgeBakList_" + pageTime);
			String judgeMembers = workBidingEvaluationService.getUserIdsFromList(judgeSession);
			String judgeMembersBak = workBidingEvaluationService.getUserIdsFromList(judgeBakSession);
			workBidingEvaluation.setJudgeMembers(judgeMembers);
			workBidingEvaluation.setJudgeMembersBak(judgeMembersBak);
			String judgeLeader = (String)request.getSession().getAttribute("judgeLeader_" + pageTime);
			workBidingEvaluation.setJudgeLeader(StringUtils.isNotBlank(judgeLeader)?judgeLeader:"");
			workBidingEvaluation.setWorkBidingProjectId(workBidingProjectId);
			workBidingEvaluation.setWorkBidingProject(new WorkBidingProject(workBidingProjectId));
			workBidingEvaluationService.save(workBidingEvaluation);//保存
		}
		addMessage(redirectAttributes, "保存评标管理成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingevaluation/workBidingEvaluation/?repage";
	}
	
	/**
	 * 删除评标管理
	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation:del")
	@RequestMapping(value = "delete")
	public String delete(WorkBidingEvaluation workBidingEvaluation, RedirectAttributes redirectAttributes) {
		workBidingEvaluationService.delete(workBidingEvaluation);
		addMessage(redirectAttributes, "删除评标管理成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingevaluation/workBidingEvaluation/?repage";
	}

	@RequestMapping("confirmDeposit")
	@ResponseBody
	public AjaxJson confirmDeposit(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String num = request.getParameter("num");
		String statusValue = request.getParameter("statusValue");
		String workProjectDepositId = request.getParameter("workProjectDepositId");
		workBidingEvaluationService.confirmDeposit(num,statusValue,workProjectDepositId);
		return ajaxJson;
	}

	@RequestMapping("/selectJudgeMembers")
	@ResponseBody
	public AjaxJson selectJudgeMembers(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String judge = request.getParameter("judge");
		String consultType = request.getParameter("consultType");
		String judgeCount = request.getParameter("judgeCount");
		String workBidingEvaluationId = request.getParameter("workBidingEvaluationId");
		String pageTime = request.getParameter("currentTime");
		request.getSession().setAttribute("select_judge_members_"+pageTime,pageTime);

		List<Judge> judgeList = new ArrayList<>();
		if(judge.equals("judge")){
			judgeList = workBidingEvaluationService.selectJudgeList(judge,consultType,judgeCount);
			request.getSession().setAttribute("judgeList_"+pageTime,judgeList);
			if(StringUtils.isNotBlank(workBidingEvaluationId)){
				workBidingEvaluationService.saveJudgeMembers(workBidingEvaluationId,judgeList);
			}

			ajaxJson.put("judgeListSize",judgeList.size());
			ajaxJson.put("judgeList",judgeList);
		}
		List<Judge> judgeBakList = new ArrayList<>();
		if(judge.equals("judgeBak")){
			List membersList = (List)request.getSession().getAttribute("judgeList_" + pageTime);
			judgeBakList = workBidingEvaluationService.selectjudgeBakList(judge,consultType,judgeCount,membersList, workBidingEvaluationId);
			request.getSession().setAttribute("judgeBakList_"+pageTime,judgeBakList);
			if(StringUtils.isNotBlank(workBidingEvaluationId)){
				workBidingEvaluationService.saveJudgeMembersBak(workBidingEvaluationId,judgeBakList);
			}
            ajaxJson.put("judgeBakListSize",judgeBakList.size());
			ajaxJson.put("judgeList",judgeBakList);
		}
		return ajaxJson;
	}
	@RequestMapping("saveJudgeLeader")
	@ResponseBody
	public AjaxJson saveJudgeLeader(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String judgeId = request.getParameter("judgeId");
		String workBidingEvaluationId = request.getParameter("workBidingEvaluationId");
		if(StringUtils.isNotBlank(workBidingEvaluationId)){
			workBidingEvaluationService.saveJudgeLeader(workBidingEvaluationId,judgeId);
		}else{
			String pageTime = request.getParameter("currentTime");
			request.getSession().setAttribute("judgeLeader_"+pageTime,judgeId);
		}

		return ajaxJson;
	}
	@RequestMapping("deleteJudgeMember")
	@ResponseBody
	public AjaxJson deleteJudgeMember(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();

		String workBidingEvaluationId = request.getParameter("workBidingEvaluationId");
		String judgeId = request.getParameter("judgeId");
		String judgeType = request.getParameter("judgeType");
		String pageTime = request.getParameter("currentTime");
		if(StringUtils.isNotBlank(workBidingEvaluationId)){
			workBidingEvaluationService.deleteJudgeMember(workBidingEvaluationId,judgeId,judgeType);
		}else {
			if(StringUtils.isNotBlank(judgeType) && judgeType.equals("0")){
				List judgeList = (List)request.getSession().getAttribute("judgeList_"+pageTime);
				judgeList = workBidingEvaluationService.modifyJudgeList(judgeList,judgeId);
				request.getSession().setAttribute("judgeList_"+pageTime,judgeList);
			}
		}

		return ajaxJson;
	}

	@RequestMapping("joinInJudgeMembers")
	@ResponseBody
	public AjaxJson joinInJudgeMembers(HttpServletRequest request){
		AjaxJson ajaxJson = new AjaxJson();
		String workBidingEvaluationId = request.getParameter("workBidingEvaluationId");
		String judgeId = request.getParameter("judgeId");
		String pageTime = request.getParameter("currentTime");
		if(StringUtils.isNotBlank(workBidingEvaluationId)){
			WorkBidingEvaluation w = workBidingEvaluationService.joinInJudgeMembers(workBidingEvaluationId, judgeId);
			ajaxJson.put("judgeList",w.getJudgeMembersList());
		}else {
			List judgeList = (List)request.getSession().getAttribute("judgeList_"+pageTime);
			judgeList.add(judgeService.get(judgeId));
			ajaxJson.put("judgeList",judgeList);
		}
		return ajaxJson;
	}

	/**
	 * 批量删除评标管理
	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			workBidingEvaluationService.delete(workBidingEvaluationService.get(id));
		}
		addMessage(redirectAttributes, "删除评标管理成功");
		return "redirect:"+Global.getAdminPath()+"/workbidingevaluation/workBidingEvaluation/?repage";
	}

	@RequestMapping(value = "editDeposit")
	public String editDeposit(Model model, HttpServletRequest request) {
		String workProjectDepositId = request.getParameter("workProjectDepositId");
		WorkProjectDeposit workProjectDeposit = workProjectDepositService.getById(workProjectDepositId);
		if(workProjectDeposit!=null){
			model.addAttribute("workProjectDeposit", workProjectDeposit);
			model.addAttribute("workBidingProjectId",workProjectDeposit.getBidingProject().getId());
		}
		model.addAttribute("workProjectDepositId",workProjectDepositId);
		return "modules/workbidingevaluation/workProjectDepositForm";
	}
	@RequestMapping(value = "deleteDeposit")
	@ResponseBody
	public AjaxJson deleteDeposit(HttpServletRequest request) {
		AjaxJson ajaxJson = new AjaxJson();
		String workProjectDepositId = request.getParameter("workProjectDepositId");
		WorkProjectDeposit workProjectDeposit = workProjectDepositService.getById(workProjectDepositId);
		workProjectDepositService.delete(workProjectDeposit);
		return ajaxJson;
	}
	@RequestMapping(value = "formDeposit")
	public String formDeposit(WorkProjectDeposit workProjectDeposit, Model model,HttpServletRequest request) {
		model.addAttribute("workProjectDeposit", workProjectDeposit);
		model.addAttribute("workBidingProjectId",request.getParameter("workBidingProjectId"));
		return "modules/workbidingevaluation/workProjectDepositForm";
	}
	@RequestMapping(value = "saveDeposit")
	@ResponseBody
	public AjaxJson saveDeposit(WorkProjectDeposit workProjectDeposit ,Model model, HttpServletRequest request) throws Exception{
		AjaxJson ajaxJson = new AjaxJson();
		String workProjectDepositId = request.getParameter("workProjectDepositId");

		if(workProjectDeposit!=null && !workProjectDeposit.getIsNewRecord()){//编辑表单保存
			WorkProjectDeposit t = workProjectDepositService.getById(workProjectDepositId);//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(workProjectDeposit, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			workProjectDepositService.save(t);//保存
		}else{//新增表单保存
			workProjectDeposit.setDepositStatus("1");
			workProjectDeposit.setBidingDocumentStatus("1");
			workProjectDeposit.setCompanyId(UserUtils.getSelectCompany().getId());
			workProjectDeposit.setOfficeId(UserUtils.getSelectOffice().getId());
			workProjectDepositService.save(workProjectDeposit);//保存
		}
		if(StringUtils.isBlank(workProjectDepositId)){
		}
        ajaxJson.put("workProjectDeposit",workProjectDeposit);
        return ajaxJson;
	}

	/**
	 * 选择评标室
	 */
	@RequestMapping(value = "selectRoom")
	public String selectRoom(WorkEvaluationRoom room, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey,String floorLabel,String floorKey,String housenumberLabel,String housenumberKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		room.setCompanyId(UserUtils.getSelectCompany().getId());
		Page<WorkEvaluationRoom> page = workEvaluationRoomService.findPage(new Page<WorkEvaluationRoom>(request, response),  room);
		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("floorLabel", floorLabel);
		model.addAttribute("floorKey", floorKey);
		model.addAttribute("housenumberLabel", housenumberLabel);
		model.addAttribute("housenumberKey", housenumberKey);
		model.addAttribute("obj", room);
		model.addAttribute("page", page);
		return "modules/sys/selectWorkEvaluationRoom";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(WorkBidingEvaluation workBidingEvaluation, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评标管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<WorkBidingEvaluation> page = workBidingEvaluationService.findPage(new Page<WorkBidingEvaluation>(request, response, -1), workBidingEvaluation);
    		new ExportExcel("评标管理", WorkBidingEvaluation.class).setDataList(page.getList()).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出评标管理记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidingevaluation/workBidingEvaluation/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation: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<WorkBidingEvaluation> list = ei.getDataList(WorkBidingEvaluation.class);
			for (WorkBidingEvaluation workBidingEvaluation : list){
				try{
					workBidingEvaluationService.save(workBidingEvaluation);
					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()+"/workbidingevaluation/workBidingEvaluation/?repage";
    }
	
	/**
	 * 下载导入评标管理数据模板
	 */
	@RequiresPermissions("workbidingevaluation:workBidingEvaluation:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评标管理数据导入模板.xlsx";
    		List<WorkBidingEvaluation> list = Lists.newArrayList(); 
    		new ExportExcel("评标管理数据", WorkBidingEvaluation.class, 1).setDataList(list).write(response, fileName,request.getHeader("USER-AGENT")).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/workbidingevaluation/workBidingEvaluation/?repage";
    }
	
	
	

}