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


import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.common.utils.text.EncodeUtil;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.managementcenter.activiti.utils.MyActiviUtils;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.entity.ModuleBlockVersion;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.entity.ModuleBlock;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.entity.ModuleListing;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.entity.ModuleVersion;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.service.ModuleBlockService;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.service.ModuleBlockVersionService;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.service.ModuleListingService;
import com.jeeplus.modules.sg.managementcenter.moduleacquisition.util.ModuleUtil;
import com.jeeplus.modules.sg.picking.activiti.entity.PickIng;
import com.jeeplus.modules.sg.picking.activiti.service.PickIngService;
import com.jeeplus.modules.sys.entity.DictValue;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


@Controller
@RequestMapping(value = "${adminPath}/managementcenter/moduleacquisition")
public class ModuleBlockWeb extends BaseController {

	@Autowired
	private ModuleBlockService moduleBlockService;
	@Autowired
	private ModuleListingService moduleListingService;
	@Autowired
	private PickIngService pickIngService;
	@Autowired
	private ModuleBlockVersionService moduleBlockVersionService;
	
	@ModelAttribute
	public ModuleBlock get(@RequestParam(required=false) String id) {
		ModuleBlock entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = moduleBlockService.get(id);
		}
		if (entity == null){
			entity = new ModuleBlock();
		}
		return entity;
	}
	/**
	 * 文件上传
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "importExcel")
	public String importExcel() {
		return "modules/sg/managementcenter/moduleacquisition/importExcel";
	}

	/**
	 * 项目列表页面
	 */
	@RequiresPermissions("managementcenter:moduleacquisition:list")
	@RequestMapping(value = {"list", ""})
	public String list(ModuleBlock moduleBlock, Model model) {
		model.addAttribute("ModuleBlock", moduleBlock);
		return "modules/sg/managementcenter/moduleacquisition/moduleBlockList";
	}
	/**
	 * 列表数据
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:moduleacquisition:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ModuleBlock moduleBlock, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ModuleBlock> page = moduleBlockService.findPage(new Page<ModuleBlock>(request, response), moduleBlock);
		//当判定系统为linux的时候
		if (Global.SYS_TYPE.equals("2")) {
			List<ModuleBlock> list = page.getList();
			for (ModuleBlock upload :
					list) {
				if (null!=upload.getMdImg()&&!upload.getMdImg().equals("")){
					String mdImg = upload.getMdImg();
					String newMdImg = "";
					String[] split = mdImg.split("\\|");
					for (int i = 0; i < split.length; i++) {
						newMdImg += "http://" + request.getServerName() + split[i] + "|";
					}
					upload.setMdImg(newMdImg);
				}
			}
		}
		return getBootstrapData(page);
	}
	/**
	 * 生成新版本列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "newData")
	public Map<String, Object> newData(ModuleBlock moduleBlock, HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		String versionName = (String) session.getAttribute("versionName");
		moduleBlock.setMdVersionName(versionName);
		Page<ModuleBlock> page = moduleBlockService.findPage(new Page<ModuleBlock>(request, response), moduleBlock);
		//当判定系统为linux的时候
		if (Global.SYS_TYPE.equals("2")) {
			List<ModuleBlock> list = page.getList();
			for (ModuleBlock moduleBlock1: list) {
					String mdImg = moduleBlock1.getMdImg();
					if (mdImg!=null&&!"".equals(mdImg)) {
						moduleBlock1.setMdImg("http://" + request.getServerName()  +moduleBlock1.getMdImg());
					}
			}
		}
		return getBootstrapData(page);
	}

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

	/**
	 * 查看，增加，编辑表单页面
	 */
	@RequiresPermissions(value={"managementcenter:moduleacquisition:view","managementcenter:moduleacquisition:list","managementcenter:moduleacquisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(ModuleBlock moduleBlock, Model model) {
		model.addAttribute("moduleBlock", moduleBlock);
		return "modules/sg/managementcenter/moduleacquisition/moduleBlockForm";
	}

	/**
	 * 保存
	 */
	@ResponseBody
	@RequiresPermissions(value={"managementcenter:moduleacquisition:add","managementcenter:moduleacquisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ModuleBlock moduleBlock, Model model,HttpServletRequest request) throws Exception{
		if (moduleBlock.getIsNewRecord()){
			HttpSession session = request.getSession();
			String versionName = (String) session.getAttribute("versionName");
			ModuleBlockVersion moduleBlockVersion = new ModuleBlockVersion();
			moduleBlockVersion.setVersionName(versionName);
			ModuleBlockVersion versionServiceById = moduleBlockVersionService.findById(moduleBlockVersion);//查询版本信息
			moduleBlock.setMdVersion(versionServiceById.getId());
			moduleBlock.setMdVersionName(versionName);
		}
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(moduleBlock);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		moduleBlockService.save(moduleBlock);//保存
		j.setSuccess(true);
		j.setMsg("保存模块成功");
		return j;
	}

	/**
	 * 保存（旧版本）
	 */
	@ResponseBody
	@RequiresPermissions(value={"managementcenter:moduleacquisition:add","managementcenter:moduleacquisition:edit"},logical=Logical.OR)
	@RequestMapping(value = "saveOld")
	public AjaxJson saveOld(ModuleBlock moduleBlock, Model model,HttpServletRequest request) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(moduleBlock);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存

		moduleBlock.setMdVersion(moduleBlock.getMdVersion());
		moduleBlockService.save(moduleBlock);//保存
		j.setSuccess(true);
		j.setMsg("保存模块成功");
		return j;
	}

	/**
	 * 删除项目
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:moduleacquisition:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ModuleBlock moduleBlock) {
		AjaxJson j = new AjaxJson();
		moduleBlockService.delete(moduleBlock);
		j.setMsg("删除项目成功");
		return j;
	}
	
	/**
	 * 批量删除
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:moduleacquisition:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			moduleBlockService.delete(moduleBlockService.get(id));
		}
		j.setMsg("删除项目成功");
		return j;
	}

	/**
	 * 导入Excel数据

	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:moduleacquisition:import")
	@RequestMapping(value = "import")
	public AjaxJson importFile(@RequestParam("file")MultipartFile file, ModuleBlockVersion moduleBlockVersion, HttpServletResponse response, HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		try {
			ModuleBlockVersion moduleBlockVersion1 = null;
			moduleBlockVersion1 = moduleBlockVersionService.findById(moduleBlockVersion);
			if (null!=moduleBlockVersion1){
				j.setSuccess(false);
				j.setMsg("导入失败：版本名称已经存在，请更换版本名称再进行操作");
				return j;
			}
			ImportExcel importBlock = new ImportExcel(file, 0, "模块表");
			ImportExcel importListing = new ImportExcel(file, 0, "模块清单");
			List<ModuleBlock> moduleBlockUtil = ModuleUtil.getModuleBlockUtil(importBlock);
			List<ModuleListing> moduleListingUtil = ModuleUtil.getModuleListingUtil(importListing);
			moduleBlockService.savaList(moduleBlockUtil,moduleListingUtil,moduleBlockVersion);
			j.setMsg( "已成功导入 "+moduleBlockUtil.size()+" 条记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入表单失败！失败信息："+e.getMessage());
		}
		return j;
	}
	/*
		生成新版本
	 */
	@RequestMapping(value = "insertVersion")
	public String saveVersion(ModuleBlock moduleBlock,String versionId,ModuleBlockVersion moduleBlockVersion,Model model,HttpServletRequest request) {
		String versionName = moduleBlockVersion.getVersionName();
		String versionAlias = moduleBlockVersion.getVersionAlias();
		try {
			moduleBlockVersion.setVersionName(URLDecoder.decode(versionName, "UTF-8"));
			moduleBlockVersion.setVersionAlias(URLDecoder.decode(versionAlias,"UTF-8"));
		}catch (Exception e){
			e.printStackTrace();
		}
		ModuleBlockVersion moduleBlockVersion1 = null;
		moduleBlockVersion1 = moduleBlockVersionService.findById(moduleBlockVersion);
		if (null!=moduleBlockVersion1){
			String str = moduleBlockVersion.getVersionName();
			moduleBlockVersion.setVersionName(str+"新版");
		}
		HttpSession session = request.getSession();
		session.setAttribute("versionName",moduleBlockVersion.getVersionName());
		moduleBlock.setMdVersion(versionId);
		List<ModuleBlock> moduleBlocks = moduleBlockService.findList(moduleBlock);
		List<ModuleListing> moduleListings = moduleListingService.findByList(moduleBlocks);
		//生成新版本:保存数据
		moduleBlockService.savaList(moduleBlocks,moduleListings,moduleBlockVersion);
		model.addAttribute("ModuleBlock",moduleBlock);
		return "modules/sg/managementcenter/moduleacquisition/moduleBlockNewList";
	}

	@ResponseBody
	@RequestMapping(value = "dataVersion")
	public Map<String, Object> dataVersion(ModuleBlockVersion moduleBlockVersion, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ModuleBlockVersion> page = moduleBlockVersionService.findPage(new Page<ModuleBlockVersion>(request, response), moduleBlockVersion);
		return getBootstrapData(page);
	}

	/**
	 * 生成新版本页面
	 */
	@RequiresPermissions("managementcenter:moduleacquisition:insertVersion")
	@RequestMapping(value ="listVersion")
	public String listVersion(ModuleBlockVersion moduleBlockVersion, Model model,HttpServletRequest request) {
		model.addAttribute("moduleBlockVersion",moduleBlockVersion);
		return "modules/sg/managementcenter/moduleacquisition/moduleVersionList";
	}

	/**
	 * 选择流程发布版本
	 */
	@RequiresPermissions("managementcenter:moduleacquisition:selectVersion")
	@RequestMapping(value ="selectVersion")
	public String selectVersion(ModuleVersion moduleVersion, Model model,HttpServletRequest request) {
		model.addAttribute("ModuleVersion",moduleVersion);
		List<String> versions = pickIngService.allVersion();
		DictValue dic = MyActiviUtils.findDic();
		String dicValue = dic.getValue();
		model.addAttribute("dicValue", dicValue);
		model.addAttribute("versions", versions);
		return "modules/sg/managementcenter/moduleacquisition/selectVersion";
	}

	/**
	 * 选择流程发布版本修改
	 */
	@ResponseBody
	@RequiresPermissions("managementcenter:moduleacquisition:selectVersion")
	@RequestMapping(value = "selectVersionSave")
	public AjaxJson selectVersionEdit(String version, Model model,HttpServletRequest request){
		AjaxJson j = new AjaxJson();
		//新增或编辑表单保存
		try {
			version = URLDecoder.decode(version, "UTF-8");
		}catch (Exception e){
			e.printStackTrace();
		}
		pickIngService.updateSelectVersion(version);
		j.setSuccess(true);
		j.setMsg("保存版本成功");
		return j;
	}
}