/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.materialProvided.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.materialProvided.entity.MaterialProvided;
import com.jeeplus.modules.sg.managementcenter.materialProvided.entity.MaterialProvidedVersion;
import com.jeeplus.modules.sg.managementcenter.materialProvided.service.MaterialProvidedService;
import com.jeeplus.modules.sg.managementcenter.materialProvided.service.MaterialProvidedVersionService;
import com.jeeplus.modules.sg.managementcenter.materialProvided.util.ImportPro;
import com.jeeplus.modules.sg.managementcenter.materialProvided.util.ImportUtil;
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.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${adminPath}/sg/managementcenter/marterialProvided")
public class MaterialProvidedController extends BaseController {

	@Autowired
	private MaterialProvidedService materialProvidedService;
	@Autowired
	private MaterialProvidedVersionService materialProvidedVersionService;
	
	@ModelAttribute
	public MaterialProvided get(@RequestParam(required=false) String id) {
		MaterialProvided entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialProvidedService.get(id);
		}
		if (entity == null){
			entity = new MaterialProvided();
		}
		return entity;
	}
	
	/**
	 * 列表页面
	 */
	@RequiresPermissions("managementcenter:materialProvided:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialProvided materialProvided, Model model) {
		model.addAttribute("materialProvided", materialProvided);
		return "modules/sg/managementcenter/materialProvided/materialProvided";
	}

	/**
	 * 文件上传
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "importExcel")
	public String importExcel() {
		return "modules/sg/managementcenter/materialProvided/importExcel";
	}

		/**
	 * 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialProvided:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(MaterialProvided materialProvided, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<MaterialProvided> page = materialProvidedService.findPage(new Page<MaterialProvided>(request, response), materialProvided);
		return getBootstrapData(page);
	}

	/**
	 * 控件列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "searchData")
	public Map<String, Object> searchData(MaterialProvided materialProvided, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<MaterialProvided> page = materialProvidedService.findPage(new Page<MaterialProvided>(request, response), materialProvided);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"managementcenter:materialProvided:view","managementcenter:materialProvided:add","managementcenter:materialProvided:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(MaterialProvided materialProvided, Model model) {
		MaterialProvidedVersion materialProvidedVersion = new MaterialProvidedVersion();
		List<MaterialProvidedVersion> allVersion = materialProvidedVersionService.findList(materialProvidedVersion);
		model.addAttribute("allVersion",allVersion);
		model.addAttribute("materialProvided", materialProvided);
		return "modules/sg/managementcenter/materialProvided/materialProvidedForm";
	}

	/**
	 * 保存表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"managementcenter:materialProvided:add","managementcenter:materialProvided:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialProvided materialProvided,MaterialProvidedVersion materialProvidedVersion1, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialProvided);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//查询版本id
		MaterialProvidedVersion materialProvidedVersion = materialProvidedVersionService.findById(materialProvidedVersion1);
		if (null!=materialProvidedVersion.getId()&&!"".equals(materialProvidedVersion.getId())){
			materialProvided.setVersion(materialProvidedVersion.getId());
		}

		//新增或编辑表单保存
		materialProvidedService.save(materialProvided);//保存
		j.setSuccess(true);
		j.setMsg("保存甲供标准物资成功");
		return j;
	}
	
	/**
	 * 删除表单
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialProvided:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialProvided materialProvided) {
		AjaxJson j = new AjaxJson();
		materialProvidedService.delete(materialProvided);
		j.setMsg("删除甲供标准物资成功");
		return j;
	}
	
	/**
	 * 批量表单
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialProvided:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			materialProvidedService.delete(materialProvidedService.get(id));
		}
		j.setMsg("删除请假表单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialProvided:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaterialProvided materialProvided, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "甲供标准物资"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MaterialProvided> page = materialProvidedService.findPage(new Page<MaterialProvided>(request, response, -1), materialProvided);
    		new ExportExcel("甲供标准物资", MaterialProvided.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("managementcenter:materialProvided:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file,MaterialProvidedVersion materialProvidedVersion, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		MaterialProvidedVersion materialProvidedVersion1 = null;
		materialProvidedVersion1 = materialProvidedVersionService.findById(materialProvidedVersion);
		try {
			if (null!=materialProvidedVersion1){
				j.setSuccess(false);
				j.setMsg("导入失败：版本名称已经存在;请更换版本名称");
				return j;
			}
			StringBuilder failureMsg = new StringBuilder();
			ImportUtil importUtil = new ImportUtil(file,1,0);
			Boolean judgeProvided = ImportPro.getJudgeProvided(importUtil);
			if (judgeProvided){
				j.setSuccess(false);
				j.setMsg("导入失败:表格不符合规范!");
				return j;
			}
			List<MaterialProvided> materProUtil = ImportPro.getMaterProUtil(importUtil);
			materialProvidedService.saveList(materProUtil,materialProvidedVersion);
			j.setMsg( "已成功导入甲供标准物资记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入甲供标准物资失败！失败信息："+e.getMessage());
		}
		return j;
    }

}