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

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.jeeplus.modules.warehouse.materialtype.utils.InitMaterialType;
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.bind.annotation.PathVariable;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.warehouse.materialtype.entity.MaterialType;
import com.jeeplus.modules.warehouse.materialtype.service.MaterialTypeService;

/**
 * 物资类型Controller
 * @author zhnaglt
 * @version 2023-02-13
 */
@Controller
@RequestMapping(value = "${adminPath}/warehouse/materialtype/materialType")
public class MaterialTypeController extends BaseController {

	@Autowired
	private MaterialTypeService materialTypeService;
	
	@ModelAttribute
	public MaterialType get(@RequestParam(required=false) String id) {
		MaterialType entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = materialTypeService.get(id);
		}
		if (entity == null){
			entity = new MaterialType();
		}
		return entity;
	}
	
	/**
	 * 物资类型列表页面
	 */
	@RequiresPermissions("warehouse:materialtype:materialType:list")
	@RequestMapping(value = {"list", ""})
	public String list(MaterialType materialType, @ModelAttribute("parentIds") String parentIds, HttpServletRequest request, HttpServletResponse response, Model model) {
		
		if(StringUtils.isNotBlank(parentIds)){
			model.addAttribute("parentIds", parentIds);
		}
		model.addAttribute("materialType", materialType);
		return "modules/warehouse/materialtype/materialTypeList";
	}

	/**
	 * 查看，增加，编辑物资类型表单页面
	 * params:
	 * 	mode: add, edit, view,addChild 代表四种种模式的页面
	 */
	@RequiresPermissions(value={"warehouse:materialtype:materialType:view","warehouse:materialtype:materialType:add","warehouse:materialtype:materialType:edit"},logical=Logical.OR)
	@RequestMapping(value = "form/{mode}")
	public String form(@PathVariable String mode, MaterialType materialType, Model model) {
		if (materialType.getParent()!=null && StringUtils.isNotBlank(materialType.getParent().getId())){
			materialType.setParent(materialTypeService.get(materialType.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(materialType.getId())){
				MaterialType materialTypeChild = new MaterialType();
				materialTypeChild.setParent(new MaterialType(materialType.getParent().getId()));
				List<MaterialType> list = materialTypeService.findList(materialType); 
				if (list.size() > 0){
					materialType.setSort(list.get(list.size()-1).getSort());
					if (materialType.getSort() != null){
						materialType.setSort(materialType.getSort() + 30);
					}
				}
			}
		}
		if (materialType.getSort() == null){
			materialType.setSort(30);
		}
		model.addAttribute("mode", mode);
		model.addAttribute("materialType", materialType);
		return "modules/warehouse/materialtype/materialTypeForm";
	}

	/**
	 * 保存物资类型
	 */
	@ResponseBody
	@RequiresPermissions(value={"warehouse:materialtype:materialType:add","warehouse:materialtype:materialType:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(MaterialType materialType, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(materialType);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}

		//新增或编辑表单保存
		materialTypeService.save(materialType);//保存
		j.setSuccess(true);
		j.put("parentIds", materialType.getParentIds());
		j.setMsg("保存品名代码成功");
		return j;
	}
	
	@ResponseBody
	@RequestMapping(value = "getChildren")
	public List<MaterialType> getChildren(String parentId){
		if("-1".equals(parentId)){//如果是-1，没指定任何父节点，就从根节点开始查找
			parentId = "0";
		}
		return materialTypeService.getChildren(parentId);
	}
	
	/**
	 * 删除物资类型
	 */
	@ResponseBody
	@RequiresPermissions("warehouse:materialtype:materialType:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(MaterialType materialType) {
		AjaxJson j = new AjaxJson();
		materialTypeService.delete(materialType);
		j.setSuccess(true);
		j.setMsg("删除物资类型成功");
		return j;
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<MaterialType> list = materialTypeService.findList(new MaterialType());
		for (int i=0; i<list.size(); i++){
			MaterialType e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("text", e.getName() + "(" + e.getCode() + ")");
				map.put("code", e.getCode());
				map.put("amount", e.getAmount());
				map.put("unit", e.getUnit());
				if(StringUtils.isBlank(e.getParentId()) || "0".equals(e.getParentId())){
					map.put("parent", "#");
					Map<String, Object> state = Maps.newHashMap();
					state.put("opened", true);
					map.put("state", state);
				}else{
					map.put("parent", e.getParentId());
				}
				mapList.add(map);
			}
		}
		return mapList;
	}


	@ResponseBody
	@RequestMapping(value = "initType")
	public AjaxJson initType() throws Exception{
		String filePath = "D:\\yqd\\2023\\cangchuguanli\\warehouse\\doc\\PMDM.xlsx";

		Map<String, String> codeIdMap = new HashMap<>();
		List<MaterialType> materialTypeList = InitMaterialType.initType(filePath, "main", "0", "0,");
		for (MaterialType materialType : materialTypeList) {
			materialTypeService.insert(materialType);
			codeIdMap.put(materialType.getCode(), materialType.getId());
		}

		String id = codeIdMap.get("001");
		List<MaterialType> materialTypeList1 = InitMaterialType.initType(filePath, "07", id, "0," + id + ",");
		for (MaterialType materialType : materialTypeList1) {
			materialTypeService.save(materialType);
		}

		id = codeIdMap.get("002");
		List<MaterialType> materialTypeList2 = InitMaterialType.initType(filePath, "0206", id, "0," + id + ",");
		for (MaterialType materialType : materialTypeList2) {
			materialTypeService.save(materialType);
		}

		id = codeIdMap.get("003");
		List<MaterialType> materialTypeList3 = InitMaterialType.initType(filePath, "1821", id, "0," + id + ",");
		for (MaterialType materialType : materialTypeList3) {
			materialTypeService.save(materialType);
		}

		id = codeIdMap.get("004");
		List<MaterialType> materialTypeList4 = InitMaterialType.initType(filePath, "21", id, "0," + id + ",");
		for (MaterialType materialType : materialTypeList4) {
			materialTypeService.save(materialType);
		}

		id = codeIdMap.get("005");
		List<MaterialType> materialTypeList5 = InitMaterialType.initType(filePath, "qt", id, "0," + id + ",");
		for (MaterialType materialType : materialTypeList5) {
			materialTypeService.save(materialType);
		}

		AjaxJson j = new AjaxJson();
		j.setMsg("初始化成功");
		return j;
	}
}