/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.materialinfo.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.entity.MaterialInfoBean;
import com.jeeplus.modules.sg.managementcenter.materialinfo.service.MaterialInfoService;
import com.jeeplus.modules.sg.managementcenter.materialplan.entity.MaterialPlan;
import com.jeeplus.modules.sg.managementcenter.materialproject.entity.MaterialProject;
import com.jeeplus.modules.sg.managementcenter.materialproject.service.MaterialProjectService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 年度物资上报明细
 */
@Controller
@RequestMapping(value = "${adminPath}/managementcenter/materialinfo")
public class MaterialInfoController extends BaseController {

	@Autowired
	private MaterialInfoService materialInfoService;
	@Autowired
	private MaterialProjectService materialProjectService;
	
	@ModelAttribute
	public MaterialInfo get(@RequestParam(required=false) String id) {
		MaterialInfo entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialInfoService.get(id);
		}
		if (entity == null){
			entity = new MaterialInfo();
		}
		return entity;
	}
	
	/**
	 * 年度物资上报明细 列表页面
	 */
	@RequiresPermissions("managementcenter:materialinfo:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialInfo materialInfo, Model model) {
		model.addAttribute("materialInfo", materialInfo);
		return "modules/sg/managementcenter/materialinfo/materialInfoList";
	}
	
	/**
	 * 年度物资上报明细 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialinfo:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MaterialInfo materialInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		MaterialInfo materialInfo1 = new MaterialInfo();//存入session数值
		materialInfo1.setProjectName(materialInfo.getProjectName());
		MaterialProject materialProject =  new MaterialProject();
		materialProject.setProjectStatus("");
		materialProject.setReserveCode(materialInfo.getReserveCode());
		MaterialProject materialProject1 = new MaterialProject();
		materialProjectService.getSearch(materialProject,materialProject1);
		List<MaterialProject> list = materialProjectService.findList(materialProject);
		String[] projectNames = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			if (null!=list.get(i).getReserveProjectName()&&!"".equals(list.get(i).getReserveProjectName())){
				projectNames[i] = list.get(i).getReserveProjectName();
			}
		}
		if (null!=list&&list.size()>0){
			materialInfo.setProjectNames(projectNames);
			materialInfo1.setProjectNames(projectNames);
		}else {
			if (!"".equals(materialInfo.getReserveCode())||!"".equals(materialInfo.getProjectCode())||
				!"".equals(materialInfo.getProjectDefine())){
				materialInfo.setProjectName("没有找到:请重新刷新...");
				materialInfo1.setProjectName("没有找到:请重新刷新...");
			}
		}
		HttpSession session = request.getSession();
		session.setAttribute("materialInfoSelect",materialInfo1);
		Page<MaterialInfo> page = materialInfoService.findPage(new Page<MaterialInfo>(request, response), materialInfo);
		return getBootstrapData(page);
	}




	
//	/**
//	 * 删除
//	 */
//	@ResponseBody
//	@RequiresPermissions("managementcenter:materialinfo:del")
//	@RequestMapping(value = "delete")
//	public AjaxJson delete(MaterialInfo materialInfo) {
//		AjaxJson j = new AjaxJson();
//		materialInfoService.delete(materialInfo);
//		j.setMsg("删除成功");
//		return j;
//	}
//
//	/**
//	 * 批量删除
//	 */
//	@ResponseBody
//	@RequiresPermissions("managementcenter:materialinfo:del")
//	@RequestMapping(value = "deleteAll")
//	public AjaxJson deleteAll(String ids) {
//		AjaxJson j = new AjaxJson();
//		String idArray[] =ids.split(",");
//		for(String id : idArray){
//			materialInfoService.delete(materialInfoService.get(id));
//		}
//		j.setMsg("删除成功");
//		return j;
//	}


//	/**
//	 * 导入Excel数据
//	 */
//	@ResponseBody
//	@RequiresPermissions("managementcenter:materialinfo:import")
//    @RequestMapping(value = "import")
//   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
//		String batch = request.getParameter("batch");   //物料批次
//		String itemBatch = request.getParameter("itemBatch");  //项目批次
//		AjaxJson j = new AjaxJson();
//		try {
//			materialInfoService.saveData(file,batch,itemBatch);
//			j.setMsg("导入成功");
//		} catch (Exception e) {
//			j.setSuccess(false);
//			j.setMsg("导入失败！失败信息："+e.getMessage());
//		}
//		return j;
//    }


    /**
     * 年度物资上报明细 多文件导入
     */
    @ResponseBody
    @RequiresPermissions("managementcenter:materialinfo:import")
    @RequestMapping(value = "imports")
    public AjaxJson importFile(@RequestParam("file")MultipartFile[] file, HttpServletResponse response, HttpServletRequest request) {
        String batch = request.getParameter("batch");   //物料批次
        String itemBatch = request.getParameter("itemBatch");   //项目批次
        AjaxJson j = new AjaxJson();
        try {
            for(int i=0;i<file.length;i++) {
                materialInfoService.saveData(file[i], batch,itemBatch);
            }
            j.setMsg("导入成功");
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }


//    /**
//	 * 导入文件页面
//	 * @return
//	 */
//	@RequestMapping(value = "importExcel")
//	public String importExcel(Model model) {
//		List<MaterialProject> list = materialProjectService.findBatch();
//		model.addAttribute("batch",list);
//		return "modules/sg/managementcenter/materialinfo/importexcel";
//	}


	/**
	 * 年度物资上报明细 多文件导入页面
	 */
	@RequestMapping(value = "/importMore/Form")
	public String importMoreForm(Model model){
		List<MaterialProject> list = materialProjectService.findBatch();
		model.addAttribute("batch",list);
		return "modules/sg/managementcenter/materialinfo/importmore";
	}


	@RequestMapping(value = "/importMore/Process")
	public String importProcess(Model model){
		List<MaterialProject> list = materialProjectService.findBatch();
		model.addAttribute("batch",list);
		return "modules/sg/managementcenter/materialinfo/importProcess";
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequestMapping(value = "export")
	public AjaxJson exportFile(MaterialInfo materialInfo, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		HttpSession session = request.getSession();
		MaterialInfo materialInfo1 = (MaterialInfo)session.getAttribute("materialInfoSelect");
		try {
			String fileName = "物料信息表"+ DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<MaterialInfo> page = materialInfoService.findPage(new Page<MaterialInfo>(request, response, -1), materialInfo1);
			new ExportExcel("物料信息表", MaterialInfoBean.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;
	}



//	/**
//	 * 项目验证
//	 */
//
//	@ResponseBody
//	@RequestMapping(value = "importValidation")
//	public AjaxJson importValidation(@RequestParam("file")MultipartFile file,String batch,String itemBatch){
//		AjaxJson j = new AjaxJson();
//		try {
//		ImportExcel mo = new ImportExcel(file,1,"模块表");
//		Row row = mo.getRow(0);
//		String projectName1 = (String) mo.getCellValue(row, 1);
//		String projectName = projectName1.trim();
//		MaterialProject materialProject = new MaterialProject();
//		materialProject.setReserveProjectName(projectName);
//		List<MaterialProject> list = materialProjectService.findList(materialProject);
//		if(list != null && list.size()>0){
//			j.setSuccess(true);
//		}else {
//			materialInfoService.saveData(file,batch,itemBatch);
//			j.setSuccess(true);
//			j.setErrorCode("0");
//			j.setMsg("导入成功");
//		}
//		} catch (Exception e) {
//			j.setSuccess(false);
//			j.setMsg("导入失败！失败信息："+e.getMessage());
//		}
//		return j;
//	}


    /**
     * 年度物资上报明细 多文件导入验证
	 * 若年度上报统计中已经存在某些项目，则返回消息由操作者选择是否进行覆盖，否则直接导入物资明细及项目信息
     */
    @ResponseBody
    @RequestMapping(value = "importValidations")
    public AjaxJson importValidations(@RequestParam("file")MultipartFile[] file,String batch,String itemBatch) {
        AjaxJson j = new AjaxJson();
        List<MaterialProject> list = new ArrayList<>();
        try {
        	//获取项目名称列表
            for(int i = 0;i<file.length;i++) {
				ImportExcel module = new ImportExcel(file[i], 1, "模块表");
				Row row = module.getRow(0);
				Object obj = module.getCellValue(row, 1);
				if(obj==null){
					throw new RuntimeException("找不到项目名称！");
				}
				String projectName = ((String) obj).trim();
                MaterialProject project = new MaterialProject();
				project.setReserveProjectName(projectName);
				list.add(project);
            }
            List<MaterialProject> projects = materialProjectService.findByList(list);
            //判断是否有已存在项目
            if(projects != null && projects.size()>0){
            	StringBuilder stringBuilder = new StringBuilder();
            	for(MaterialProject materialProject : list){
            		stringBuilder.append(materialProject.getReserveProjectName()+",");
				}
            	j.setMsg(stringBuilder.toString());
                j.setSuccess(true);
            }else {
                for(int k=0;k<file.length;k++) {
                    materialInfoService.saveData(file[k], batch,itemBatch);
                }
                j.setSuccess(true);
                j.setErrorCode("0");
                j.setMsg("导入成功");
            }
        } catch (Exception e) {
            j.setSuccess(true);
            j.setMsg("导入失败！失败信息："+e.getMessage());
        }
        return j;
    }






}