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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

import com.jeeplus.modules.sg.managementcenter.project.entity.Project;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.project.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.project.util.ProExcelInfo;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;

import static com.jeeplus.modules.sg.managementcenter.project.util.ProExcelInfo.getProjectUtilFlag;

/**
 * 表单Controller
 * @author lgf
 * @version 2018-06-12
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementcenter/project")
public class ProjectController extends BaseController {

	@Autowired
	private ProjectService projectService;
	
	@ModelAttribute
	public Project get(@RequestParam(required=false) String id) {
		Project entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectService.get(id);
		}
		if (entity == null){
			entity = new Project();
		}
		return entity;
	}
	
	/**
	 * 工程管理表单列表页面
	 */
	@RequiresPermissions("sg:managementcenter:project:list")
	@RequestMapping(value = {"list", ""})
	public String list(Project project, Model model) {
		model.addAttribute("leave1", project);
		return "modules/sg/managementcenter/project/projectList";
	}
	
		/**
	 * 表单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
		return getBootstrapData(page);
	}

	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:list")
	@RequestMapping(value = "dataSys")
	public Map<String, Object> dataSys(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		project.setStatus("0");
		project.setWhetherCloseStatus("0");
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
		return getBootstrapData(page);
	}

	/**
	 * 领料模块项目选择框
	 * */
	@ResponseBody
	@RequestMapping(value = "dataPicking")
	public Map<String, Object> dataPicking(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		project.setStatus("2");
		project.setWhetherCloseStatus("0");
		project.setEarlyMaterial(1);
		project.setConstructionUnitRole(UserUtils.getUser().getLoginName());
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
		return getBootstrapData(page);
	}

	/**
	 * 领料申请项目选择框
	 * */
	@ResponseBody
	@RequestMapping(value = "pickingApplication")
	public Map<String, Object> pickingApplication(Project project, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Project> page = projectService.findPage(new Page<Project>(request, response), project);
		return getBootstrapData(page);
	}



	/**
	 * 查看，增加，编辑表单表单页面
	 */
	@RequiresPermissions(value={"sg:managementcenter:project:view","sg:managementcenter:project:add","sg:managementcenter:project:edit"},logical= Logical.OR)
	@RequestMapping(value = "form")
	public String form(Project project, Model model) {
		model.addAttribute("leave1", project);
		return "modules/sg/managementcenter/project/projectForm";
	}

	/**
	 * 保存表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:managementcenter:project:add","sg:managementcenter:project:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Project project, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(project);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		List<Project> projects = new ArrayList<Project>();
		projects.add(project);
		String loginName = UserUtils.getUser().getLoginName();
		String judgeValue = ProExcelInfo.getJudgeValue(projects);
		if (project.getIsNewRecord()){
			if (!"".equals(judgeValue)||!project.getProjectManageRole().equals(loginName)){
				j.setSuccess(false);
				j.setMsg("新建失败:"+judgeValue+"数据不符合规范");
				return j;
			}
			project.preInsert();
			projectService.saveList(projects);
			j.setSuccess(true);
			j.setMsg("保存需求基本信息成功");
		}else{
			if (!"".equals(judgeValue)||!project.getProjectManageRole().equals(loginName)){
				j.setSuccess(false);
				j.setMsg("修改失败："+judgeValue+"数据不符合规范");
				return j;
			}
			project.preUpdate();
			projectService.save(project);
			j.setSuccess(true);
			j.setMsg("修改需求基本信息成功");
		}
		return j;
	}
	
	/**
	 * 删除表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Project project) {
		AjaxJson j = new AjaxJson();
		String requireName="";
		boolean flag = false;
		List<Project> listProject = projectService.findList(project);
		for (Project project1:listProject){
			flag = false;
			requireName = project1.getRequireName();
			if (!project1.getStatus().equals("0")||!project1.getConstructionStatus().equals("0")
					||!project1.getWhetherCloseStatus().equals("0")||!project1.getAcquisitionStatus().equals("0")){
				flag = true;
			}
		}
		if (flag){
			j.setSuccess(false);
			j.setMsg(requireName+":该项目在流程中运行,禁止删除");
			return  j;
		}
		projectService.delete(project);
		j.setMsg("删除需求基本信息成功");
		return j;
	}
	
	/**
	 * 批量表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		Project project = new Project();
		String idArray[] =ids.split(",");
		List<Project> listById = projectService.findListById(idArray);
		boolean flag=false;
		String requireName="";
		for (Project project1:listById){
			if (!project1.getStatus().equals("0")||!project1.getConstructionStatus().equals("0")
					||!project1.getWhetherCloseStatus().equals("0")||!project1.getAcquisitionStatus().equals("0")){
				flag = true;
				requireName += project1.getRequireName()+"、";
			}
		}
		if (flag){
			j.setSuccess(false);
			j.setMsg(requireName+"项目已经在流程中运行,禁止删除");
			return  j;
		}
		for(String id : idArray){
			projectService.delete(projectService.get(id));
		}
		j.setMsg("删除需求基本信息成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Project project, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "需求基本信息"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Project> page = projectService.findPage(new Page<Project>(request, response, -1), project);
    		new ExportExcel("需求基本信息", Project.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出需求基本信息记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:project:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
			ImportUtil importUtil = new ImportUtil(file, 0, 0);
			Boolean projectUtilFlag = ProExcelInfo.getProjectUtilFlag(importUtil);
			if (projectUtilFlag){
				j.setSuccess(false);
				j.setMsg("表不符合规范");
				return j;
			}
			List<Project> projects =ProExcelInfo.getSureProjects(ProExcelInfo.getProjectUtil(importUtil));
			String judgeValue = ProExcelInfo.getJudgeValue(projects);
			if (!"".equals(judgeValue)){
				j.setSuccess(false);
				j.setMsg("导入失败："+judgeValue+"数据不符合规范！");
				return j;
			}
			projectService.saveList(projects);
			j.setMsg( "已成功导入 "+projects.size()+" 条项目表单记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入需求基本信息表单失败！失败信息："+e.getMessage());
		}
		return j;
    }
}