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

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.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.managementcenter.materialplan.entity.InventoryTable;
import com.jeeplus.modules.sg.managementcenter.materialplan.entity.MaterialPlan;
import com.jeeplus.modules.sg.managementcenter.materialplan.service.MaterialPlanService;
import com.jeeplus.modules.sg.managementcenter.materialplan.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.materialplan.util.MaterialPlanInfo;
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.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

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

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

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

	/**
	 * 保存表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:managementcenter:materialplan:add","sg:managementcenter:materialplan:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialPlan materialPlan, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialPlan);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		materialPlanService.save(materialPlan);//保存
		j.setSuccess(true);
		j.setMsg("保存成功");
		return j;
	}
	
	/**
	 * 删除表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:materialplan:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialPlan materialPlan) {
		AjaxJson j = new AjaxJson();
		materialPlanService.delete(materialPlan);
		j.setMsg("删除成功");
		return j;
	}
	
	/**
	 * 批量表单
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:materialplan:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			materialPlanService.deleteData(id);
		}
		j.setMsg("删除成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sg:managementcenter:materialplan:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaterialPlan materialPlan, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "需求基本信息表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MaterialPlan> page = materialPlanService.findPage(new Page<MaterialPlan>(request, response, -1), materialPlan);
    		new ExportExcel("需求基本信息表", MaterialPlan.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:materialplan:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		MaterialPlan material = new MaterialPlan();
		List<MaterialPlan> materialPlanList = materialPlanService.findAllList(material);
		if (null==materialPlanList&&materialPlanList.size()<=0){
			j.setSuccess(false);
			j.setMsg( "还没有导入基础数据表");
			return j;
		}
		try {
			Integer count = 0;
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportUtil importUtil = new ImportUtil(file,0,0);
			Integer integer = MaterialPlanInfo.getJudgeExcel(importUtil);//验证表
			if (integer==MaterialPlanInfo.MATER_THREE){
				j.setSuccess(false);
				j.setMsg("导入失败：表不符合规范，请重新导入");
				return j;
			}
			if (integer==MaterialPlanInfo.MATER_ONE){
				List<MaterialPlan> materialPlans = MaterialPlanInfo.getMaterPlanUtil(importUtil);
				try{
					materialPlanService.saveList(materialPlans);
					count = materialPlans.size();
				}catch (Exception e){
					e.printStackTrace();
				}
			}
			if (integer==MaterialPlanInfo.MATER_TWO){
				if (materialPlanList.size()<=0){
					j.setSuccess(false);
					j.setMsg("您还没有导入基本信息表");
					return j;
				}
				List<InventoryTable> inventoryTables = MaterialPlanInfo.getUpdateMaterPlan(importUtil);
				for (InventoryTable inventoryTable:inventoryTables){
					try{
						materialPlanService.updateInventory(inventoryTable);
						successNum++;
					}catch(ConstraintViolationException ex){
						failureNum++;
					}catch (Exception ex) {
						failureNum++;
					}
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条项记录。");
			}
			if (integer == MaterialPlanInfo.MATER_ONE){
				j.setMsg( "已成功导入 "+count+" 条基本表记录"+failureMsg);
			}
			if (integer == MaterialPlanInfo.MATER_TWO){
				j.setMsg( "已成功导入"+successNum+"库存表记录");
			}
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入失败！失败信息："+e.getMessage());
		}
		return j;
    }
	@ResponseBody
    @RequestMapping(value = "addtime")
    public AjaxJson addTime(MaterialPlan materialPlan){
		AjaxJson j = new AjaxJson();
		try {
			materialPlanService.updateTime(materialPlan);
			j.setSuccess(true);
			j.setMsg("更新成功");
			return j;
		}catch (Exception e){
			e.printStackTrace();
		}
		j.setSuccess(false);
		j.setMsg("时间不符合规范");
		return j;
	}

	/**
	 * 下载导入数据模板
	 */
	@ResponseBody
	@RequestMapping(value = "import/template")
	public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
			materialPlanService.exportHeard(response);
			j.setSuccess(true);
			j.setMsg("导出成功！");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
	}
}