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

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import com.jeeplus.modules.sys.entity.User;

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.balancedlibrary.liKuResourcePool.entity.LiKuResourcePool;
import com.jeeplus.modules.sg.balancedlibrary.liKuResourcePool.service.LiKuResourcePoolService;
import com.jeeplus.modules.sg.balancedlibrary.replaceMaterial.entity.ReplaceMaterial;
import com.jeeplus.modules.sg.balancedlibrary.replaceMaterial.service.ReplaceMaterialService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
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.validation.ConstraintViolationException;
import java.util.List;
import java.util.Map;

/**
 * 物料替换Controller
 * @author enford
 * @version 1.0
 */
@Controller
@RequestMapping(value = "${adminPath}/replaceMaterial")
public class ReplaceMaterialController extends BaseController {

	@Autowired
	private ReplaceMaterialService service;
	
	@ModelAttribute
	public ReplaceMaterial get(@RequestParam(required=false) String id) {
		ReplaceMaterial entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = service.get(id);
		}
		if (entity == null){
			entity = new ReplaceMaterial();
		}
		return entity;
	}
	
	/**
	 * 物料替换列表页面
	 */
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:list")
	@RequestMapping(value = "list")
	public String list(ReplaceMaterial entity, Model model) {
		model.addAttribute("entity", entity);
		return "modules/sg/balancedlibrary/replaceMaterial/replaceMaterialList";
	}
	
		/**
	 * 物料替换列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ReplaceMaterial entity, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ReplaceMaterial> page = service.findPage(new Page<ReplaceMaterial>(request, response), entity);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑物料替换表单页面
	 */
	@RequiresPermissions(value={"sg:balancedlibrary:ReplaceMaterial:view","sg:balancedlibrary:ReplaceMaterial:add","sg:balancedlibrary:ReplaceMaterial:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ReplaceMaterial entity, Model model) {
		model.addAttribute("entity", entity);
		return "modules/sg/balancedlibrary/replaceMaterial/replaceMaterialForm";
	}

	/**
	 * 保存物料替换
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:balancedlibrary:ReplaceMaterial:add","sg:balancedlibrary:ReplaceMaterial:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ReplaceMaterial entity, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(entity);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		service.save(entity);
		j.setSuccess(true);
		j.setMsg("保存物料替换成功");
		return j;
	}
	
	/**
	 * 删除物料替换
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ReplaceMaterial entity) {
		AjaxJson j = new AjaxJson();
		service.delete(entity);
		j.setMsg("删除物料替换成功");
		return j;
	}
	
	/**
	 * 批量删除物料替换
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			service.delete(service.get(id));
		}
		j.setMsg("删除物料替换成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(ReplaceMaterial entity, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物料替换"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ReplaceMaterial> page = service.findPage(new Page<ReplaceMaterial>(request, response, -1), entity);
    		new ExportExcel("", ReplaceMaterial.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:balancedlibrary:ReplaceMaterial:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		List<ReplaceMaterial> insertList = new ArrayList<>();
		try {
			ImportExcel ei = new ImportExcel(file, 0, 0);
			int last = ei.getLastDataRowNum();
			for (int i = 1; i <= ei.getLastDataRowNum(); i++) {
				Row row = ei.getRow(i);
				ReplaceMaterial replaceMaterial = new ReplaceMaterial();
				Cell cell = row.getCell(0);
				if (null == cell) {
					continue;
				}
				String value = cell.toString();
				if ("".equals(value) || null == value || value.contains("注：")) {
					continue;
				}
				BigDecimal bigDecimal = new BigDecimal(value);
				String cellOne = bigDecimal.toPlainString();
				replaceMaterial.setMaterialCode(cellOne);
				replaceMaterial.setMaterialDescription(String.valueOf(row.getCell(1)));
				BigDecimal decTwo = new BigDecimal(row.getCell(2).toString());
				replaceMaterial.setExtendedCoding(decTwo.toPlainString());
				replaceMaterial.setExtendedDescription(String.valueOf(row.getCell(3)));
				BigDecimal decFive = new BigDecimal(row.getCell(5).toString());
				replaceMaterial.setMaterialCodeRep(decFive.toPlainString());
				replaceMaterial.setMaterialDescriptionRep(String.valueOf(row.getCell(6)));
				BigDecimal decSeven = new BigDecimal(row.getCell(7).toString());
				replaceMaterial.setExtendedCodingRep(decSeven.toPlainString());
				String cellEight = String.valueOf(row.getCell(8));
				if ("null".equals(cellEight)) {
					cellEight = "";
				}
				replaceMaterial.setExtendedDescriptionRep(cellEight);
				replaceMaterial.preInsert();
				insertList.add(replaceMaterial);
			}
			if (insertList.size() > 0) {
				service.insertList(insertList);
			}
			j.setMsg( "已成功导入 "+insertList.size()+" 条替换记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入物料替换失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入物料替换数据模板
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:ReplaceMaterial:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "物料替换数据导入模板.xlsx";
    		List<ReplaceMaterial> list = Lists.newArrayList(); 
    		new ExportExcel("", ReplaceMaterial.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }


	/**
	 * 当使用POI处理excel的时候，遇到了比较长的数字，
	 * 虽然excel里面设置该单元格是文本类型的，但是POI的cell的类型就会变成数字类型
	 * 而且无论数字是否小数，使用cell.getNumbericCellValue() 去获取值的时候，会得到一个double，
	 * 而且当长度大一点的时候会变成科学计数法形式
	 * 使用DecimalFormat对这个double进行了格式话，
	 * 随后使用format方法获得的String就是你想要的值了。
	 * @param hssfcell
	 * @return
	 */
	public static String getValue(HSSFCell hssfcell){
		String str;
		DecimalFormat df = new DecimalFormat("0");
		if(hssfcell.getCellType()==HSSFCell.CELL_TYPE_BOOLEAN){
			str = String.valueOf(hssfcell.getBooleanCellValue());
			return str;
		} else if(hssfcell.getCellType()==HSSFCell.CELL_TYPE_NUMERIC){
			str = df.format(hssfcell.getNumericCellValue());
			return str;
		} else{
			str = hssfcell.getStringCellValue();
			return str;
		}
	}

}