/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.managementcenter.materialInventory.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.oa.service.OaNotifyMaterialService;
import com.jeeplus.modules.oa.service.OaNotifyService;
import com.jeeplus.modules.sg.managementcenter.materialInventory.entity.MaterialInventory;
import com.jeeplus.modules.sg.managementcenter.materialInventory.entity.MaterialRequisition;
import com.jeeplus.modules.sg.managementcenter.materialInventory.service.MaterialInventoryService;
import com.jeeplus.modules.sg.managementcenter.materialInventory.util.ImportPro;
import com.jeeplus.modules.sg.managementcenter.materialInventory.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.project.entity.PickingRequisition;
import com.jeeplus.modules.sg.managementcenter.project.service.PickingRequisitionService;
import com.jeeplus.modules.sg.managementcenter.project.service.ProjectService;
import com.jeeplus.modules.sg.managementcenter.project.util.PickingInfo;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 库存物料管理
 */
@Controller
@RequestMapping(value = "${adminPath}/sg/managementcenter/materialInventory")
public class MaterialInventoryController extends BaseController {
	@Autowired
	private MaterialInventoryService materialInventoryService;
	@Autowired
	private PickingRequisitionService pickingRequisitionService;
//	@Autowired
//	private OaNotifyMaterialService oaNotifyMaterialService;
//	@Autowired
//	private ProjectService projectService;
//	@Autowired
//	private OaNotifyService oaNotifyService;
	
	@ModelAttribute
	public MaterialInventory get(@RequestParam(required=false) String id) {
		MaterialInventory entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialInventoryService.get(id);
		}
		if (entity == null){
			entity = new MaterialInventory();
		}
		return entity;
	}
	
	/**
	 * 库存物料管理页面
	 */
	@RequiresPermissions("managementcenter:materialInventory:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialInventory materialInventory, Model model) {
		model.addAttribute("materialInventory", materialInventory);
		return "modules/sg/managementcenter/materialInventory/materialInventory";
	}

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

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

	/**
	 * 保存表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"managementcenter:materialInventory:add","managementcenter:materialInventory:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialInventory materialInventory, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialInventory);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		materialInventoryService.save(materialInventory);//保存
		j.setSuccess(true);
		j.setMsg("保存库存成功");
		return j;
	}
	
	/**
	 * 删除表单
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialInventory:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialInventory materialInventory) {
		AjaxJson j = new AjaxJson();
		materialInventoryService.delete(materialInventory);
		j.setMsg("删除库存成功");
		return j;
	}
	
	/**
	 * 批量表单
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialInventory:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			materialInventoryService.delete(materialInventoryService.get(id));
		}
		j.setMsg("删除请假表单成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialInventory:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(MaterialInventory materialInventory, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "库存"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<MaterialInventory> page = materialInventoryService.findPage(new Page<MaterialInventory>(request, response, -1), materialInventory);
    		new ExportExcel("库存", MaterialInventory.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;
    }

	/**
	 * 导入库存物料数据（即附件4）
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialInventory:import")
    @RequestMapping(value = "importInventory")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
			StringBuilder failureMsg = new StringBuilder();
			ImportUtil importUtil = new ImportUtil(file,1,0);
			boolean judgeInventory = ImportPro.getJudgeInventory(importUtil);
			if (judgeInventory){
				j.setSuccess(false);
				j.setMsg("导入失败：表格不符合规范!");
				return j;
			}
			List<MaterialInventory> inventoryData = ImportPro.getInventoryData(importUtil);
			List<MaterialInventory> list = ImportPro.getInventorySet(inventoryData);//相同物料编码数据汇总
			materialInventoryService.saveList(list);
			j.setMsg( "已成功导入"+list.size()+"条,"+"库存记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入库存失败！失败信息："+e.getMessage());
		}
		return j;
    }
    /**
     * 导入领料单数据（即附件5）
     */
    @ResponseBody
    @RequiresPermissions("managementcenter:materialInventory:import")
    @RequestMapping(value = "importRequisition")
    public AjaxJson importFile1(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request){
        AjaxJson j = new AjaxJson();
		String str = "";//提示
        try {
            StringBuilder failureMsg = new StringBuilder();
            ImportUtil importUtil = new ImportUtil(file,1,0);
			boolean judgeRequisition = ImportPro.getJudgeRequisition(importUtil);
			if (judgeRequisition){
				j.setSuccess(false);
				j.setMsg("导入失败：表格不符合规范!");
				return j;
			}
			List<MaterialRequisition> requisitionData = ImportPro.getRequisitionData(importUtil);//得到领料单原始数据
			Map<String,MaterialRequisition> map = ImportPro.getRequisitionMap(requisitionData);//领料单数据汇总map,key为物料编码
			List<MaterialInventory> inventoryList = materialInventoryService.findByList(new ArrayList<>(map.values()));//得到数据库中匹配的物料编码
			if (null==inventoryList||inventoryList.size()<=0){
				j.setSuccess(false);
				j.setMsg("导入领料单失败！失败信息：无基础数据");
				return j;
			}
			List<MaterialInventory> materialInventories = ImportPro.getMaterial(inventoryList, map);//得到可使用库存数量
			materialInventoryService.saveList(materialInventories);

			//发送通知-------------
			//读取表格list
			List<PickingRequisition> listPickRequisition = PickingInfo.getListPickRequisition(importUtil);
			/*
				如下3个list是导入操作（得到最终保存数据库的集合）。对领料单进行数据库保存。
			 */
			List<PickingRequisition> duplicateRemoval = PickingInfo.getDuplicateRemoval(listPickRequisition);//去重集合
			if (null==duplicateRemoval || duplicateRemoval.size()<=0){
				j.setSuccess(false);
				j.setMsg("导入失败：导入表格无数据");
				return j;
			}
			List<PickingRequisition> repeatRequisition = PickingInfo.getRepeatRequisition(duplicateRemoval);//去掉重复的领料单号
			List<PickingRequisition> pickingRequisitions = pickingRequisitionService.pickingRequisitions(repeatRequisition);//得到数据库中数据
			List<PickingRequisition> sureSavePicking = PickingInfo.getSureSavePicking(pickingRequisitions, repeatRequisition);//参数1：得到数据库集合 参数2：读取表格list
			if (null!=sureSavePicking&&sureSavePicking.size()>0){
				pickingRequisitionService.saveList(sureSavePicking);
			}
			//判断该项目已完成首次领料
			List<PickingRequisition> judgePicking = PickingInfo.getJudgePicking(listPickRequisition);//获取领料状态
			/**
			 * 一致的,修改领料状态
			 */
			//获取需求数量和已出库数量都一致领料单集合
			List<PickingRequisition> changePicking = PickingInfo.getChangePicking(judgePicking);
/*			if (null!=changePicking&&changePicking.size()>0){
				List<Project> listProject1Picking1 = projectService.findListProjectPicking(changePicking);
				for (Project project1 : listProject1Picking1){
					projectService.getUpdateAcquisitionStatus("2", project1.getId());
				}
			}*/
			/*
				发送通知方法集合
			 */
			//获得该项目是否允许领料是否允许领料状态的项目:返回不一致集合
			List<PickingRequisition> notifyPickingRequisitions = PickingInfo.getUnifiedPicking(judgePicking);
			//去重
			List<PickingRequisition> duplicate = PickingInfo.getDuplicateRemoval(notifyPickingRequisitions);
			//根据项目定义号去项目表中查找项目信息
//			List<Project> listProject1Picking = projectService.findListProjectPicking(duplicate);
			/*if (null!= listProject1Picking && listProject1Picking.size()>0){
				//根据项目的id去数据库中查找项目领导审核时间
				List<Acquisition> findListDate = pickingRequisitionService.getFindListDate(listProject1Picking);
				if (null!=findListDate&&findListDate.size()>0){
					List<Acquisition> sureFindListDate = PickingInfo.getSureFindListDate(findListDate);
					//得到整合后的list集合（存在项目信息）
					List<ProjectAcquisition> listProjectAcquisition = PickingInfo.getListProjectAcquisition(listProject1Picking, sureFindListDate);

					//得到和项目表匹配的pickAcquisition的集合同时判断给超过三天的领料做标识
					List<PickingRequisition> listSameSetOf = PickingInfo.getListSameSetOf(listProjectAcquisition, listPickRequisition);
					if (null!=listSameSetOf&&listSameSetOf.size()>0){
						//根据物料编码进行去重
						List<PickingRequisition> duplicateRemovalMaterCode = PickingInfo.getDuplicateRemovalMaterCode(listSameSetOf);
						//得到库存对应的集合
						List<MaterialInventory> byListPicking = materialInventoryService.findByListPicking(duplicateRemovalMaterCode);

						//所有缺货未缺货信息的登记
						List<PickingRequisition> whetherStock = PickingInfo.getWhetherStock(listSameSetOf, byListPicking);

						//得到非缺货信息1的通知
						List<OaNotifyMaterial> noStockList = PickingInfo.getNoStock(whetherStock);
						//得到缺货信息3的通知（缺货项目信息）
						List<OaNotifyMaterial> yesStock2List = PickingInfo.getYesStock2(whetherStock);
						//得到缺货信息2的通知
						List<OaNotifyMaterial> yesStock1List = PickingInfo.getYesStock1(whetherStock);
						//发送通知方法
						//非缺货信息1
						if (null!=noStockList && noStockList.size()>0){
							int count = 0;
							List<String> listUserId = PickingInfo.getListUserId(PickingInfo.ALL_USER_ID);
							List<String> userId = pickingRequisitionService.findUserId(listUserId);
//							String stringJoiningTogether = PickingInfo.getStringJoiningTogether(userId);//获取通知人
							OaNotify oaNotify = new OaNotify();
							oaNotify.setType("5");
							oaNotify.setTitle("非缺货信息");//非缺货信息
//							oaNotify.setContent(noStock);
							oaNotify.setContent("请在详情中查看...");
							oaNotify.setStatus("1");
							oaNotify.setOaNotifyRecordIds(stringJoiningTogether);
							oaNotifyService.saveList(oaNotify,noStockList);
							List<OaNotifyRecord> list = oaNotify.getOaNotifyRecordList();
							for(OaNotifyRecord o : list){
								count++;
								//发送通知到客户端
								ServletContext context = SpringContextHolder
										.getBean(ServletContext.class);
								new SystemInfoSocketHandler().sendMessageToUser(UserUtils.get(o.getUser().getId()).getLoginName(), "收到一条新通知，请到我的通知查看！");
							}
							str="已经发送非缺货信息通知;";
						}
						//非缺货信息2
						if (null!=yesStock1List&&yesStock1List.size()>0){
							int count = 0;
							List<String> listUserId = PickingInfo.getListUserId(PickingInfo.QH_USER_ID);
							List<String> userId = pickingRequisitionService.findUserId(listUserId);
							String stringJoiningTogether = PickingInfo.getStringJoiningTogether(userId);//获取通知人
							OaNotify oaNotify = new OaNotify();
							oaNotify.setType("6");
							oaNotify.setTitle("缺货信息");
							oaNotify.setContent("请在详情中查看...");
							oaNotify.setStatus("1");
							oaNotify.setOaNotifyRecordIds(stringJoiningTogether);
							oaNotifyService.saveList(oaNotify,yesStock1List);
							List<OaNotifyRecord> list = oaNotify.getOaNotifyRecordList();
							for(OaNotifyRecord o : list){
								count++;
								//发送通知到客户端
								ServletContext context = SpringContextHolder
										.getBean(ServletContext.class);
								new SystemInfoSocketHandler().sendMessageToUser(UserUtils.get(o.getUser().getId()).getLoginName(), "收到一条新通知，请到我的通知查看！");
							}
							str+="已经发送缺货信息通知;";
						}
						//非缺货信息2
						if (null!=yesStock2List&&yesStock2List.size()>0){
							int count = 0;
							List<String> listUserId = PickingInfo.getListUserId(PickingInfo.QH_USER_ID);
							List<String> userId = pickingRequisitionService.findUserId(listUserId);
							String stringJoiningTogether = PickingInfo.getStringJoiningTogether(userId);//获取通知人
							OaNotify oaNotify = new OaNotify();
							oaNotify.setType("7");
							oaNotify.setTitle("缺货项目信息");
							oaNotify.setContent("请在详情中查看...");
							oaNotify.setStatus("1");
							oaNotify.setOaNotifyRecordIds(stringJoiningTogether);
							oaNotifyService.saveList(oaNotify,yesStock2List);
							List<OaNotifyRecord> list = oaNotify.getOaNotifyRecordList();
							for(OaNotifyRecord o : list){
								count++;
								//发送通知到客户端
								ServletContext context = SpringContextHolder
										.getBean(ServletContext.class);
								new SystemInfoSocketHandler().sendMessageToUser(UserUtils.get(o.getUser().getId()).getLoginName(), "收到一条新通知，请到我的通知查看！");
							}
							str+="已经发送缺货项目信息通知;";
						}
					}

				}
			}*/
			if (str.length()<=0){
				str+="暂无通知！";
			}
			j.setMsg( "已成功导入"+materialInventories.size()+"条,"+"领料单记录"+failureMsg+";"+str);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("导入领料单失败！失败信息："+e.getMessage());
        }
        return j;
    }
}