/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.balancedlibrary.liKuResourcePool.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.modules.sg.balancedlibrary.liKuResourcePool.utils.ImportUtil;
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.liKuResourcePool.utils.LiKuUtils;
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.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 利库资源池Controller
 * @author lgf
 * @version 2018-06-12
 */
@Controller
@RequestMapping(value = "${adminPath}/liKuResourcePool")
public class LiKuResourcePoolController extends BaseController {

	@Autowired
	private LiKuResourcePoolService service;



	@ModelAttribute
	public LiKuResourcePool get(@RequestParam(required=false) String id) {
		LiKuResourcePool entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = service.get(id);
		}
		if (entity == null){
			entity = new LiKuResourcePool();
		}
		return entity;
	}
	
	/**
	 * 利库资源池列表页面
	 */
	@RequiresPermissions("sg:balancedlibrary:liKuResourcePool:list")
	@RequestMapping(value = "list")
	public String list(LiKuResourcePool entity, Model model) {
		model.addAttribute("entity", entity);
		return "modules/sg/balancedlibrary/liKuResourcePool/liKuResourcePoolList";
	}
	
		/**
	 * 利库资源池列表数据
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:liKuResourcePool:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(LiKuResourcePool entity, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LiKuResourcePool> page = service.findPage(new Page<LiKuResourcePool>(request, response), entity);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑利库资源池表单页面
	 */
	@RequiresPermissions(value={"sg:balancedlibrary:liKuResourcePool:view","sg:balancedlibrary:liKuResourcePool:add","sg:balancedlibrary:liKuResourcePool:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LiKuResourcePool entity, Model model) {
		model.addAttribute("entity", entity);
		return "modules/test/one/dialog/liKuResourcePoolForm";
	}

	/**
	 * 保存利库资源池
	 */
	@ResponseBody
	@RequiresPermissions(value={"sg:balancedlibrary:liKuResourcePool:add","sg:balancedlibrary:liKuResourcePool:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(LiKuResourcePool 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:liKuResourcePool:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(LiKuResourcePool entity) {
		AjaxJson j = new AjaxJson();
		service.delete(entity);
		j.setMsg("删除利库资源池成功");
		return j;
	}
	
	/**
	 * 批量删除利库资源池
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:liKuResourcePool: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:liKuResourcePool:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(LiKuResourcePool entity, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "资源池利库情况表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LiKuResourcePool> page = service.findPage(new Page<LiKuResourcePool>(request, response, -1), entity);
    		new ExportExcel("", LiKuResourcePool.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:liKuResourcePool:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String unit = "";
		String area = "";
		try {
			ImportUtil ei = new ImportUtil(file,0,0);
			List<LiKuResourcePool> list = ei.getDataList(LiKuResourcePool.class);
			for(LiKuResourcePool pool:list){
				pool.setIsSectionLength(LiKuUtils.isTheUnitMeter(pool.getUnitOfMeasurement()));
				//获取库存地描述，标记数据所属区域
				pool.setWhereFrom(LiKuUtils.judgmentArea(pool.getInvLocation()));
				pool.setRemaining(pool.getInventoryAmount());
				pool.setNumberOfNiches(0.0);
			}
//			List<LiKuResourcePool> list = new ArrayList<>();
//			int lastDataRowNum = ei.getLastDataRowNum();
//			for (int i = 1; i <= lastDataRowNum; i++) {
//				LiKuResourcePool pool = new LiKuResourcePool();
//				Row row = ei.getRow(i);
//				pool.setSerialNumber(String.valueOf(row.getCell(0)));
//				pool.setFactory(String.valueOf(row.getCell(1)));
//				pool.setBatch(String.valueOf(row.getCell(2)));
//				pool.setMaterialCode(row.getCell(3).getStringCellValue());
//				pool.setMaterialDescription(String.valueOf(row.getCell(4)));
//				pool.setUnitOfMeasurement(String.valueOf(row.getCell(5)));
//				pool.setInventoryAmount(Double.valueOf(String.valueOf(row.getCell(6))));
//				pool.setInventoryLocation(String.valueOf(row.getCell(7)));
//				pool.setInvLocation(String.valueOf(row.getCell(8)));
//				pool.setInvLocationDes(String.valueOf(row.getCell(9)));
//				pool.setSupplierName(String.valueOf(row.getCell(10)));
//				pool.setSpecialStock(String.valueOf(row.getCell(11)));
//				pool.setExtendedCoding(String.valueOf(row.getCell(12)));
//				pool.setExtendedDescription(String.valueOf(row.getCell(13)));
//				pool.setMeterNumber(String.valueOf(row.getCell(14)));
//				pool.setRingCage(String.valueOf(row.getCell(15)));
//				pool.setTerminalWarranty(String.valueOf(row.getCell(16)));
//				pool.setSpecialParameters(String.valueOf(row.getCell(17)));
//				pool.setRemarks(String.valueOf(row.getCell(18)));
//				pool.setDaysStorage(Double.valueOf(String.valueOf(row.getCell(19))).intValue());
//				pool.setMonthStorage(Double.valueOf(String.valueOf(row.getCell(20))).intValue());
//				pool.setIsExpansion(String.valueOf(row.getCell(21)));
//				//获取计量单位，判断是否是段长数据
//				unit = pool.getUnitOfMeasurement();
//				pool.setIsSectionLength(LiKuUtils.isTheUnitMeter(unit));
//				//获取库存地描述，标记数据所属区域
//				pool.setWhereFrom(LiKuUtils.judgmentArea(pool.getInvLocation()));
//				pool.setRemaining(pool.getInventoryAmount());
//				pool.setNumberOfNiches(0.0);
//				list.add(pool);
//			}
			if (list.size() > 0) {
				List<LiKuResourcePool> insertList = new ArrayList<>();
				for (LiKuResourcePool pool :list) {
					Integer isSectionLength = pool.getIsSectionLength();
					if (isSectionLength.compareTo(LiKuUtils.YES) == 0) {
						String lengthOfCable = pool.getMeterNumber();
						if (null != lengthOfCable && !"".equals(lengthOfCable)) {
							String[] split = lengthOfCable.split(";");
							for (int i = 0; i < split.length; i++) {
								LiKuResourcePool liKu = new LiKuResourcePool();
								liKu.setSerialNumber(pool.getSerialNumber());
								liKu.setFactory(pool.getFactory());
								liKu.setBatch(pool.getBatch());
								liKu.setMaterialCode(pool.getMaterialCode());
								liKu.setMaterialDescription(pool.getMaterialDescription());
								liKu.setUnitOfMeasurement(pool.getUnitOfMeasurement());
								liKu.setInventoryAmount(pool.getInventoryAmount());
								liKu.setInventoryLocation(pool.getInventoryLocation());
								liKu.setInvLocation(pool.getInvLocation());
								liKu.setInvLocationDes(pool.getInvLocationDes());
								liKu.setSupplierName(pool.getSupplierName());
								liKu.setSpecialStock(pool.getSpecialStock());
								liKu.setExtendedCoding(pool.getExtendedCoding());
								liKu.setExtendedDescription(pool.getExtendedDescription());
								liKu.setLengthOfCable(Double.valueOf(split[i]));
								liKu.setRingCage(pool.getRingCage());
								liKu.setTerminalWarranty(pool.getTerminalWarranty());
								liKu.setSpecialParameters(pool.getSpecialParameters());
								liKu.setRemarks(pool.getRemarks());
								liKu.setDaysStorage(pool.getDaysStorage());
								liKu.setMonthStorage(pool.getMonthStorage());
								liKu.setIsExpansion(pool.getIsExpansion());
								liKu.setNumberOfNiches(pool.getNumberOfNiches());
								liKu.setRemaining(Double.valueOf(split[i]));
								liKu.setIsSectionLength(pool.getIsSectionLength());
								liKu.setWhereFrom(pool.getWhereFrom());
								liKu.setSegBelongs(i + 1);
								insertList.add(liKu);
							}
						} else {
							pool.setSegBelongs(1);
							pool.setLengthOfCable(pool.getInventoryAmount());
							insertList.add(pool);
						}
					}else {
						insertList.add(pool);
					}
				}
				//利库资源池每次重新导入数据，将原有数据清空
				service.clearLiKuResource();
				service.insertList(insertList);
				j.setMsg("已成功导入 " + insertList.size() + " 条利库资源池记录");
			}
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入利库资源池失败！失败信息："+e.getMessage());
		}
		return j;
    }



	/**
	 * 下载导入利库资源池数据模板
	 */
	@ResponseBody
	@RequiresPermissions("sg:balancedlibrary:liKuResourcePool:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "利库资源池数据导入模板.xlsx";
    		List<LiKuResourcePool> list = Lists.newArrayList(); 
    		new ExportExcel("", LiKuResourcePool.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }

}