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

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

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

import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.UserUtils;
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 com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
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 com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.warehouse.materialrequisition.entity.MaterialRequisition;
import com.jeeplus.modules.warehouse.materialrequisition.service.MaterialRequisitionService;

/**
 * 物资领用Controller
 * @author zhanglt
 * @version 2023-02-13
 */
@Controller
@RequestMapping(value = "${adminPath}/warehouse/materialrequisition/materialRequisition")
public class MaterialRequisitionController extends BaseController {

	@Autowired
	private MaterialRequisitionService materialRequisitionService;
	@Autowired
	private SystemService systemService;

	
	@ModelAttribute
	public MaterialRequisition get(@RequestParam(required=false) String id) {
		MaterialRequisition entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialRequisitionService.get(id);
		}
		if (entity == null){
			entity = new MaterialRequisition();
		}
		return entity;
	}
	
	/**
	 * 物资领用列表页面
	 */
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialRequisition materialRequisition, Model model) {
		model.addAttribute("materialRequisition", materialRequisition);
		return "modules/warehouse/materialrequisition/materialRequisitionList";
	}
	
		/**
	 * 物资领用列表数据
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MaterialRequisition materialRequisition, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<MaterialRequisition> page = materialRequisitionService.findPage(new Page<MaterialRequisition>(request, response), materialRequisition); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑物资领用表单页面
	 */
	@RequiresPermissions(value={"warehouse:materialrequisition:materialRequisition:view","warehouse:materialrequisition:materialRequisition:add","warehouse:materialrequisition:materialRequisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, MaterialRequisition materialRequisition, Model model) {
		if(materialRequisition.getNumber()==null|| Objects.equals(materialRequisition.getNumber(), "")){
			materialRequisition.setNumber(materialRequisitionService.createLYDH());
		}
		if(materialRequisition.getOperator() == null){
			materialRequisition.setOperator(UserUtils.getUser());
		}
		model.addAttribute("materialRequisition", materialRequisition);
		model.addAttribute("mode", mode);
		return "modules/warehouse/materialrequisition/materialRequisitionForm";
	}

	/**
	 * 保存物资领用
	 */
	@ResponseBody
	@RequiresPermissions(value={"warehouse:materialrequisition:materialRequisition:add","warehouse:materialrequisition:materialRequisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialRequisition materialRequisition, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialRequisition);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		if(!Objects.equals(materialRequisition.getStatus(), "2")){
			materialRequisitionService.save(materialRequisition);//保存
		}else {
			j.setSuccess(false);
			j.setMsg("该物资领用单已出库不可以修改");
			return j;
		}
//		materialRequisitionService.delivery(materialRequisition);

		j.setSuccess(true);
		j.setMsg("保存物资领用成功");
		return j;
	}
	
	/**
	 * 删除物资领用
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialRequisition materialRequisition) {
		AjaxJson j = new AjaxJson();
		materialRequisitionService.delete(materialRequisition);
		j.setMsg("删除物资领用成功");
		return j;
	}
	
	/**
	 * 批量删除物资领用
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			materialRequisitionService.delete(materialRequisitionService.get(id));
		}
		j.setMsg("删除物资领用成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaterialRequisition materialRequisition, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物资领用"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MaterialRequisition> page = materialRequisitionService.findPage(new Page<MaterialRequisition>(request, response, -1), materialRequisition);
    		new ExportExcel("物资领用", MaterialRequisition.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 = "detail")
	public MaterialRequisition detail(String id) {
		return materialRequisitionService.get(id);
	}
	

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<MaterialRequisition> list = ei.getDataList(MaterialRequisition.class);
			for (MaterialRequisition materialRequisition : list){
				try{
					materialRequisitionService.save(materialRequisition);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条物资领用记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条物资领用记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入物资领用失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入物资领用数据模板
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialrequisition:materialRequisition:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物资领用数据导入模板.xlsx";
    		List<MaterialRequisition> list = Lists.newArrayList(); 
    		new ExportExcel("物资领用数据", MaterialRequisition.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	/**
	 * 生成对应的 出库记录  领用后出库
	 */
	@ResponseBody
	@RequiresPermissions(value={"warehouse:materialrequisition:materialRequisition:add","warehouse:materialrequisition:materialRequisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "delivery")
	public AjaxJson delivery(MaterialRequisition materialRequisition, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialRequisition);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
//		materialRequisitionService.save(materialRequisition);//保存
		if(Objects.equals(materialRequisition.getStatus(), "2")){
			j.setSuccess(false);
			j.setMsg("该物资已领用出库，不可重复领用");
			return j;
		}
		materialRequisitionService.delivery(materialRequisition);
		j.setSuccess(true);
		j.setMsg("保存物资领用成功");
		return j;
	}


}