/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.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.entity.Workattachment;
import com.jeeplus.modules.sys.service.JudgeService;
import com.jeeplus.modules.sys.service.WorkattachmentService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.workfullmanage.service.WorkFullManageService;
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.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 评委Controller
 * @author fgy
 * @version 2017-12-26
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/judge")
public class JudgeController extends BaseController {

	@Autowired
	private JudgeService judgeService;
	@Autowired
    private WorkattachmentService workattachmentService;
	@Autowired
	private WorkFullManageService workFullManageService;
	
	@ModelAttribute
	public Judge get(@RequestParam(required=false) String id) {
		Judge entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = judgeService.get(id);
		}
		if (entity == null){
			entity = new Judge();
		}
		return entity;
	}
	
	/**
	 * 评委列表页面
	 */
	@RequiresPermissions("sys:judge:list")
	@RequestMapping(value = {"list", ""})
	public String list(Judge judge, HttpServletRequest request, HttpServletResponse response, Model model) {
		Office office = UserUtils.getSelectOffice();
		Page<Judge> page = new Page<>();
		if(!office.getName().contains("招标")){
			page.setPageNo(1);
			page.setPageSize(10);
			model.addAttribute("page", page);
			model.addAttribute("addBtn","addBtn");
			return "modules/sys/judgeList";
		}
		//给公司管理员和招标部部门负责人删除权限
		String peopleMaster = judgeService.getPeopleMaster();

		page = judgeService.findPage(new Page<Judge>(request, response), judge);
		model.addAttribute("page", page);
		model.addAttribute("peopleMaster",peopleMaster);
		return "modules/sys/judgeList";
	}

	/**
	 * 查看，增加，编辑评委表单页面
	 */
	@RequiresPermissions(value={"sys:judge:view","sys:judge:add","sys:judge:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Judge judge, Model model,HttpServletRequest request) {
		String view = request.getParameter("view");
		model.addAttribute("judge", judge);
		model.addAttribute("judgeAttachmentList",judge.getJudgeAttachmentList());
		if("view".equals(view)){
			return "modules/sys/judgeView";
		}
		return "modules/sys/judgeForm";
	}

	/**
	 * 保存评委
	 */
	@RequiresPermissions(value={"sys:judge:add","sys:judge:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Judge judge, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if(judge.getQualificationCredentials()==null){
			judge.setQualificationCredentials("");
		}
		if (!beanValidator(model, judge)){
			return form(judge, model,null);
		}
		String attachmentId="";
		if(StringUtils.isBlank(judge.getId())){
			String currentTime = request.getParameter("currentTime");
			String time = String.valueOf(request.getSession().getAttribute("judge_attachment_currentTime"));
			if(StringUtils.isNotBlank(currentTime)&&currentTime.equals(time)){
				attachmentId = currentTime;
			}
		}
		if(!judge.getIsNewRecord()){//编辑表单保存
			Judge t = judgeService.get(judge.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(judge, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			judgeService.save(t,attachmentId);//保存
		}else{//新增表单保存
			judgeService.save(judge,attachmentId);//保存
		}
		addMessage(redirectAttributes, "保存评委成功");
		return "redirect:"+Global.getAdminPath()+"/sys/judge/?repage";
	}

	@RequestMapping("/uploadJudgeAttachment")
	@ResponseBody
    public AjaxJson uploadFile(MultipartHttpServletRequest multiRequest){
		judgeService.saveFile(multiRequest);
		String attachmentId=multiRequest.getParameter("attachmentId");
		String currentTime = multiRequest.getParameter("currentTime");
        String time = String.valueOf(multiRequest.getSession().getAttribute("judge_attachment_currentTime"));
        if(StringUtils.isBlank(attachmentId)&&StringUtils.isNotBlank(currentTime)&&StringUtils.isNotBlank(time)&&currentTime.equals(time)){
			attachmentId = currentTime;
		}
        List<Workattachment> attachmentList = workattachmentService.getListByAttachmentIdAndFlag(attachmentId,"65");
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("judgeAttachmentList",attachmentList);
	    return ajaxJson;
    }

    @RequestMapping("delFile")
	@ResponseBody
    public AjaxJson delFile(Judge judge,HttpServletRequest request,Model model){
    	String judgeId = request.getParameter("id");
		String attaId = request.getParameter("attaId");
		String attachmentUrl = request.getParameter("attachmentUrl");
        judgeService.delFile(attaId,attachmentUrl);
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.put("attachmentUrl",attachmentUrl);
		return ajaxJson;
    }

	/**
	 * 删除评委
	 */
	@RequiresPermissions("sys:judge:del")
	@RequestMapping(value = "delete")
	public String delete(Judge judge, RedirectAttributes redirectAttributes) {
		judgeService.delete(judge);
		addMessage(redirectAttributes, "删除评委成功");
		return "redirect:"+Global.getAdminPath()+"/sys/judge/?repage";
	}
	
	/**
	 * 批量删除评委
	 */
	@RequiresPermissions("sys:judge:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			judgeService.delete(judgeService.get(id));
		}
		addMessage(redirectAttributes, "删除评委成功");
		return "redirect:"+Global.getAdminPath()+"/sys/judge/?repage";
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("sys:judge:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(Judge judge, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评委"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Judge> page = judgeService.findPage(new Page<Judge>(request, response, -1), judge);
    		new ExportExcel("评委", Judge.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()+"/sys/judge/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("sys:judge: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<Judge> list = ei.getDataList(Judge.class);
			for (Judge judge : list){
				try{
					judgeService.save(judge);
					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()+"/sys/judge/?repage";
    }
	
	/**
	 * 下载导入评委数据模板
	 */
	@RequiresPermissions("sys:judge:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletRequest request,HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "评委数据导入模板.xlsx";
    		List<Judge> list = Lists.newArrayList(); 
    		new ExportExcel("评委数据", Judge.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()+"/sys/judge/?repage";
    }
	
	
	

}