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

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.managementcenter.materialinfo.entity.MaterialInfo;
import com.jeeplus.modules.sg.managementcenter.materialinfo.service.MaterialInfoService;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.materialproject.service.MaterialProjectService;
import com.jeeplus.modules.sg.managementcenter.materialproject.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.materialproject.util.MaterialProUtil;
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.http.HttpRequest;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "${adminPath}/managementcenter/materialproject")
public class MaterialProjectController extends BaseController {

	@Autowired
	private MaterialProjectService materialProjectService;
	@Autowired
	private MaterialInfoService materialInfoService;
	
	@ModelAttribute
	public MaterialProject get(@RequestParam(required=false) String id) {
		MaterialProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialProjectService.get(id);
		}
		if (entity == null){
			entity = new MaterialProject();
		}
		return entity;
	}
	
	/**
	 * 项目列表页面
	 */
	@RequiresPermissions("managementcenter:materialproject:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialProject materialProject, Model model) {
		model.addAttribute("materialProject", materialProject);
		return "modules/sg/managementcenter/materialproject/materialProjectList";
	}
	
		/**
	 * 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MaterialProject materialProject, HttpServletRequest request, HttpServletResponse response, Model model) {
		materialProject.setProjectStatus("");
		MaterialProject materialProject1 = new MaterialProject();
		materialProjectService.getSearch(materialProject,materialProject1);
		HttpSession session = request.getSession();
		session.setAttribute("materialPro",materialProject1);
		Page<MaterialProject> page = materialProjectService.findPage(new Page<MaterialProject>(request, response), materialProject);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"managementcenter:materialproject:view","managementcenter:materialproject:add","managementcenter:materialproject:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(MaterialProject materialProject, Model model) {
		List<MaterialProject> list = materialProjectService.findBatch();
		model.addAttribute("batch",list);
		model.addAttribute("materialProject", materialProject);
		return "modules/sg/managementcenter/materialproject/materialProjectForm";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@RequiresPermissions(value={"managementcenter:materialproject:add","managementcenter:materialproject:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialProject materialProject, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialProject);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		materialProjectService.save(materialProject);//保存
		j.setSuccess(true);
		j.setMsg("保存项目成功");
		return j;
	}
	
	/**
	 * 删除项目
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialProject materialProject) {
		AjaxJson j = new AjaxJson();
		materialProjectService.delete(materialProject);
		j.setMsg("删除项目成功");
		return j;
	}
	
	/**
	 * 批量删除
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			materialProjectService.delete(materialProjectService.get(id));
		}
		j.setMsg("删除项目成功");
		return j;
	}
	
	/**
	 * 物料列表导出
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaterialProject materialProject, HttpServletRequest request, HttpServletResponse response){
		AjaxJson j = new AjaxJson();
		HttpSession session = request.getSession();
		MaterialProject materialProject1 = (MaterialProject)session.getAttribute("materialPro");
		try {
            String fileName = "物料"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			List<MaterialProject> list = new ArrayList<MaterialProject>();
			if (!materialProject1.getReserveProjectName().equals("")||!materialProject1.getProjectName().equals("")||!materialProject1.getProjectCode().equals("")||
					!materialProject1.getReserveCode().equals("")||!materialProject1.getProjectAttribute().equals("")||!materialProject1.getProjectDefine().equals("")
			||null!=materialProject1.getReserveCodes()||null!=materialProject1.getProjectCodes()){
				list = materialProjectService.findList(materialProject1);
			}else {
				list = materialProjectService.findList(materialProject);
			}
            List<MaterialInfo> materialInfos = materialInfoService.findByBatch(list);
    		new ExportExcel(null, MaterialInfo.class).setDataList(materialInfos).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 项目列表导出
	 * @param materialProject
	 * @param request
	 * @param response
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:export")
	@RequestMapping(value = "exportpro")
	public AjaxJson exportPro(MaterialProject materialProject, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			HttpSession session = request.getSession();
			MaterialProject materialProject1 = (MaterialProject)session.getAttribute("materialPro");
			String fileName = "项目表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
//			Page<MaterialProject> page = materialProjectService.findPage(new Page<MaterialProject>(request, response, -1), materialProject);
			List<MaterialProject> list = null;
			if (!materialProject1.getReserveProjectName().equals("")||!materialProject1.getProjectName().equals("")||!materialProject1.getProjectCode().equals("")||
			!materialProject1.getReserveCode().equals("")||!materialProject1.getProjectAttribute().equals("")||!materialProject1.getProjectDefine().equals("")
			||null!=materialProject1.getReserveCodes()||null!=materialProject1.getProjectCodes()){
				list = materialProjectService.findList(materialProject1);
			}else {
				list = materialProjectService.findList(materialProject);
			}
			new ExportExcel(null, MaterialProject.class).setDataList(list).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("managementcenter:materialproject: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 materialProjectFlag = MaterialProUtil.getMaterialProjectFlag(importUtil);
			if (materialProjectFlag){
				j.setSuccess(false);
				j.setMsg("表不符合规范");
				return j;
			}
			List<MaterialProject> materialProjects = MaterialProUtil.getProjectUtil(importUtil);
			materialProjectService.replaceList(materialProjects);
			j.setMsg( "已成功导入 "+materialProjects.size()+" 条项目表单记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入项目表单失败！失败信息："+e.getMessage());
		}
		return j;
	}
}