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

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.managementcenter.constructionProject.entity.ConstructionProject;
import com.jeeplus.modules.sg.managementcenter.constructionProject.service.ConstructionProjectService;
import com.jeeplus.modules.sg.managementcenter.constructionProject.util.ImportProUtil;
import com.jeeplus.modules.sg.managementcenter.constructionProject.util.ImportUtil;
import com.jeeplus.modules.sg.managementcenter.constructionProject.util.Result;
import com.jeeplus.modules.sg.managementcenter.constructionProject.util.TreeTableUtil;
import com.jeeplus.modules.test.tree.dialog.entity.TestTree1;
import com.jeeplus.modules.test.treetable.dialog.entity.CarKind1;
import com.jeeplus.modules.test.treetable.dialog.service.CarKind1Service;
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.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "${adminPath}/sg/managementCenter/constructionProject")
public class ConstructionProjectController extends BaseController {

	@Autowired
	private ConstructionProjectService constructionProjectService;
	@Autowired
	private CarKind1Service carKind1Service;
	
	@ModelAttribute
	public ConstructionProject get(@RequestParam(required=false) String id) {
		ConstructionProject entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = constructionProjectService.get(id);
		}
		if (entity == null){
			entity = new ConstructionProject();
		}
		return entity;
	}
	
	/**
	 * 项目列表页面
	 */
//	@RequiresPermissions("managementcenter:materialproject:list")
	@RequestMapping(value = {"list", ""})
	public String list(ConstructionProject constructionProject, Model model) {
		model.addAttribute("constructionProject", constructionProject);
		return "modules/sg/managementcenter/constructionProject/constructionList";
	}
	//树形列表页面
	@ResponseBody
	@RequestMapping(value = "bootstrapTreeTable")
	public List<Map<String,Object>> getBootstrapTreeTable(ConstructionProject constructionProject){
		List<Map<String,Object>> objects = Lists.newArrayList();
		constructionProject.setProjectStatus("0");
		List<ConstructionProject> constructionProjects = constructionProjectService.findList(constructionProject);
		List<Map<String, Object>> bootstrapTreeTables = TreeTableUtil.getBootstrapTreeTable(objects, constructionProjects);
		return bootstrapTreeTables;
	}
	//右侧列表
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(ConstructionProject constructionProject) {
		constructionProject.setProjectStatus("1");
		List<Map<String, Object>> parentConstructionMap = getMapListRight(constructionProject);
		return parentConstructionMap;
	}

	@ResponseBody
	@RequestMapping(value = "treeDataAjax")
	public Result treeDataAjax(ConstructionProject constructionProject) {
		Result result = new Result();
		List<Map<String,Object>> mapList = Lists.newArrayList();
		constructionProject.setProjectStatus("1");
		List<Map<String, Object>> parentConstructionMap = getMapListRight(constructionProject);
		result.setMapList(parentConstructionMap);
		result.setSuccess(true);
		result.setMessage("成功");
		return result;
	}

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

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

	/**
	 * 保存
	 */
	@ResponseBody
//	@RequiresPermissions(value={"managementcenter:materialproject:add","managementcenter:materialproject:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ConstructionProject constructionProject, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(constructionProject);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		constructionProjectService.save(constructionProject);//保存
		j.setSuccess(true);
		j.setMsg("保存项目成功");
		return j;
	}
	
	/**
	 * 删除项目
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ConstructionProject constructionProject) {
		AjaxJson j = new AjaxJson();
		constructionProjectService.delete(constructionProject);
		j.setMsg("删除项目成功");
		return j;
	}
	
	/**
	 * 批量删除
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:materialproject:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			constructionProjectService.delete(constructionProjectService.get(id));
		}
		j.setMsg("删除项目成功");
		return j;
	}
	


	/**
	 * 导入Excel数据

	 */
	@ResponseBody
//	@RequiresPermissions("managementcenter:materialproject:import")
	@RequestMapping(value = "import")
	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
			ImportUtil importUtil = new ImportUtil(file, 0, 0);
			List<ConstructionProject> constructionProjects = ImportProUtil.getProjectUtil(importUtil);
			constructionProjectService.savaList(constructionProjects);
			j.setMsg( "已成功导入 "+constructionProjects.size()+" 条项目表单记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入项目失败！失败信息："+e.getMessage());
		}
		return j;
	}

	/**
	 * 安排计划
	 * @return ajax
	 */
	@ResponseBody
	@RequestMapping(value = "unplanned")
	public Result getUnplanned(String ids, ConstructionProject constructionProject,String time){
		Result result = new Result();
		try{
			String idArray[] =ids.split(",");
			String str ="";
			SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM");
			Date date = formatter.parse(time);
			constructionProject.setArrangeTime(date);
			for(String id : idArray){
				str = id.substring(id.length()-4);
				if (!str.equals("line")){
					constructionProject.setId(id);
					constructionProject.setProjectStatus("1");
					constructionProjectService.updateStatus(constructionProject);
				}
			}
			constructionProject.setProjectStatus("1");
			constructionProject.setId("");
			List<Map<String, Object>> parentConstructionMap = getMapListRight(constructionProject);
			result.setSuccess(true);
			result.setMapList(parentConstructionMap);
			result.setMessage("安排计划成功");
		}catch (Exception e){
			result.setSuccess(false);
			result.setMessage("安排计划失败");
		}
		return result;
	}
	/**
	 * 安排计划
	 * @return ajax
	 */
	@ResponseBody
	@RequestMapping(value = "unplannedMinus")
	public Result getUnplannedMinus(String ids,ConstructionProject constructionProject,String time){
		Result result = new Result();
		try {
			String idArray[] =ids.split(",");
			String str ="";
			for(String id : idArray){
				str = id.substring(id.length()-4);
				if (!str.equals("line")){
					constructionProject.setId(id);
					constructionProject.setProjectStatus("0");
					constructionProjectService.updateStatus(constructionProject);
				}
			}
			constructionProject.setProjectStatus("1");
			constructionProject.setId("");
			SimpleDateFormat formatter = new SimpleDateFormat( "yyyy-MM");
			Date date = formatter.parse(time);
			constructionProject.setArrangeTime(date);
			List<Map<String, Object>> parentConstructionMap = getMapListRight(constructionProject);
			result.setSuccess(true);
			result.setMapList(parentConstructionMap);
			result.setMessage("取消计划成功");
		}catch (Exception e){
			result.setSuccess(false);
			result.setMessage("取消计划失败");
		}
		return result;
	}

	//	@RequiresPermissions(value={"managementcenter:materialproject:view","managementcenter:materialproject:add","managementcenter:materialproject:edit"},logical=Logical.OR)
	@RequestMapping(value = "formPlan")
	public String formPlan(ConstructionProject constructionProject, Model model) {
		String originalId = constructionProject.getId();
		constructionProject.setProjectStatus("2");
		String constructionId = TreeTableUtil.getConstructionId(constructionProject);
		if ("".equals(constructionId)){
			model.addAttribute("constructionId","0");//项目
		}
		if ("line".equals(constructionId)){
			model.addAttribute("constructionId","1");
		}
		constructionProject = get(constructionProject.getId());
		constructionProject.setId(originalId);
		model.addAttribute("constructionProject", constructionProject);
		return "modules/sg/managementcenter/constructionProject/constructionPlanForm";
	}

	/**
	 * 计划安排时间修改
	 * @param constructionProject
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "unplannedPlan")
	public AjaxJson getUnplannedPlan(ConstructionProject constructionProject,Date historyTime){
		AjaxJson j = new AjaxJson();
		constructionProject.setProjectStatus("1");
		constructionProjectService.updateSpecificTime(constructionProject,historyTime);
		j.setMsg("设置时间成功");
		return j;
	}

	public List<Map<String,Object>> getMapListRight(ConstructionProject constructionProject){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String time = "";
		if (null!=constructionProject.getArrangeTime()){
			time = sdf.format(constructionProject.getArrangeTime());
			constructionProject.setArrangeTime(null);
		}else {
			time = sdf.format(new Date());
		}
		List<Map<String,Object>> mapList = Lists.newArrayList();
		List<ConstructionProject> constructionProjects = constructionProjectService.findList(constructionProject);
		List<ConstructionProject> constructionProjectList = TreeTableUtil.getMonths(constructionProjects, time);
		return TreeTableUtil.getBootstrapTreeTable(mapList, constructionProjectList);
	}
}