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

import com.alibaba.fastjson.JSON;
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.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sg.financial.erpcredit.util.Result;
import com.jeeplus.modules.sg.financial.erpcredit.util.SerializeUtil;
import com.jeeplus.modules.sg.picking.activiti.entity.PickIng;
import com.jeeplus.modules.sg.picking.activiti.entity.PickList;
import com.jeeplus.modules.sg.picking.activiti.entity.ShowList;
import com.jeeplus.modules.sg.picking.activiti.service.PickIngService;
import com.jeeplus.modules.sg.picking.activiti.service.ShowListService;
import com.jeeplus.modules.sg.raiseCapital.entity.RaiseCapital;
import com.jeeplus.modules.sg.raiseCapital.service.RaiseCapitalService;
import com.jeeplus.modules.sg.raiseCapitalDesign.entity.*;
import com.jeeplus.modules.sg.raiseCapitalDesign.service.RaiseCapitalDesignService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.J2Cache;
import net.oschina.j2cache.redis.RedisCacheProvider;
import net.oschina.j2cache.redis.RedisClient;
import net.oschina.j2cache.redis.RedisUtils;
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 redis.clients.jedis.BinaryJedisCommands;
import redis.clients.jedis.Jedis;

import javax.json.Json;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 设计单位提资模块Controller
 * @author 徐滕
 * @date 2021-08-10
 */
@Controller
@RequestMapping(value = "${adminPath}/raiseCapitalDesign")
public class RaiseCapitalDesignController extends BaseController {

	@Autowired
	private RaiseCapitalDesignService raiseCapitalDesignService;


	@ModelAttribute
	public RaiseCapital get(@RequestParam(required=false) String id) {
		RaiseCapital entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = raiseCapitalDesignService.get(id);
		}
		if (entity == null){
			entity = new RaiseCapital();
		}
		return entity;
	}

	/**
	 * 提资表单列表页面
	 */
	@RequiresPermissions("test:raiseCapitalDesign:list")
	@RequestMapping(value = {"list", ""})
	public String list(RaiseCapital raiseCapital, Model model) {
		//创建一个临时UUID信息
		UUID uuid = UUID.randomUUID();
		List<PickList> pickListList = raiseCapitalDesignService.newAllList();
		model.addAttribute("pickUuid", uuid);
		model.addAttribute("pickListList", pickListList);
		model.addAttribute("raiseCapital", raiseCapital);
		return "modules/sg/raiseCapitalDesign/raiseCapitalDesign";
	}

	@RequestMapping(value = "disposeFormDataOnList")
	@ResponseBody
	public Map disposeFormDataOnList(String uuid) {
		Map<String,Object> map = new HashMap<>();
		//将新增页数据保存到redis中（item）
		List<DisposeData> voltageDisposeDataList = raiseCapitalDesignService.getDisposeFormData(uuid);
		map.put("data",voltageDisposeDataList);
		map.put("success",true);
		return map;
	}
	@RequestMapping(value = "disposeFormCableDataList")
	@ResponseBody
	public Map disposeFormCableDataList(String uuid) {
		Map<String,Object> map = new HashMap<>();
		//将新增页数据保存到redis中（item）
		List<DisposeCableData> voltageDisposeDataList = raiseCapitalDesignService.disposeFormCableDataList(uuid);
		map.put("data",voltageDisposeDataList);
		map.put("success",true);
		return map;
	}

		/**
	 * 提资表单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapitalDesign:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(RaiseCapital raiseCapital, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RaiseCapital> page = raiseCapitalDesignService.findPage(new Page<RaiseCapital>(request, response), raiseCapital);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑提资表单表单页面
	 */
	@RequiresPermissions(value={"test:raiseCapitalDesign:view","test:raiseCapitalDesign:add","test:raiseCapitalDesign:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(RaiseCapital raiseCapital, Model model) {
		model.addAttribute("raiseCapital", raiseCapital);
		return "modules/test/one/dialog/leave1Form";
	}

	/**
	 * 跳转架空导线处理页面
	 */
	//@RequiresPermissions(value={"test:raiseCapitalDesign:view","test:raiseCapitalDesign:add","test:raiseCapitalDesign:edit"},logical=Logical.OR)
	@RequestMapping(value = "aerialConductorForm")
	public String aerialConductorForm(String uuid,String item, Model model) {
		//将新增页数据保存到redis中（item）
		//raiseCapitalDesignService.disposeFormData(uuid,item);
		//查询10KV计算系数
		String highSingleVoltageCoefficient = DictUtils.getDictLabel("highSingleVoltageCoefficient", "designCalculateCoefficient", "");
		String highDoubleVoltageCoefficient = DictUtils.getDictLabel("highDoubleVoltageCoefficient", "designCalculateCoefficient", "");
		//查询0.4KV计算系数
		String lowSingleVoltageCoefficient = DictUtils.getDictLabel("lowSingleVoltageCoefficient", "designCalculateCoefficient", "");
		String lowDoubleVoltageCoefficient = DictUtils.getDictLabel("lowDoubleVoltageCoefficient", "designCalculateCoefficient", "");
		//查询10KV数据
		List<VoltageInfo> highVoltageList = raiseCapitalDesignService.getAerialConductor(uuid + "highVoltage","highVoltage");
		//查询0.4KV数据
		List<VoltageInfo> lowVoltageList = raiseCapitalDesignService.getAerialConductor(uuid + "lowVoltage","lowVoltage");
		model.addAttribute("highSingleVoltageCoefficient", highSingleVoltageCoefficient);
		model.addAttribute("highDoubleVoltageCoefficient", highDoubleVoltageCoefficient);
		model.addAttribute("lowSingleVoltageCoefficient", lowSingleVoltageCoefficient);
		model.addAttribute("lowDoubleVoltageCoefficient", lowDoubleVoltageCoefficient);
		model.addAttribute("highVoltageList", highVoltageList);
		model.addAttribute("lowVoltageList", lowVoltageList);
		model.addAttribute("uuid", uuid);
		return "modules/sg/raiseCapitalDesign/aerialConductorForm";
	}
	/**
	 * 电缆分段
	 * 查看，增加，编辑提资表单表单页面
	 */
	@RequestMapping(value = "cableSectionForm")
	public String cableSectionForm(String uuid, Model model) {
		List<CableSectionData> cableSectionData = raiseCapitalDesignService.getCableSectionData();
		List<CableSectionInfo> cableFourHundredList = raiseCapitalDesignService.getCableSection(uuid + "cableFourHundred","cableFourHundred");
		List<CableSectionInfo> cableHundredAndTwentyList = raiseCapitalDesignService.getCableSection(uuid + "cableHundredAndTwenty","cableHundredAndTwenty");
		List<CableSectionInfo> cableThreeHundredList = raiseCapitalDesignService.getCableSection(uuid + "cableThreeHundred","cableThreeHundred");
		List<CableSectionInfo> cableTwoHundredFortyList = raiseCapitalDesignService.getCableSection(uuid + "cableTwoHundredForty","cableTwoHundredForty");
		List<CableSectionInfo> cableSeventyList = raiseCapitalDesignService.getCableSection(uuid + "cableSeventy","cableSeventy");
		//获取电缆分段的系数
		String cableFactor = DictUtils.getDictLabel("cableFactor", "designCalculateCoefficient", "");
		model.addAttribute("cableFactor", cableFactor);
		model.addAttribute("cableSectionData", cableSectionData);
		model.addAttribute("cableFourHundredList", cableFourHundredList);
		model.addAttribute("cableHundredAndTwentyList", cableHundredAndTwentyList);
		model.addAttribute("cableThreeHundredList", cableThreeHundredList);
		model.addAttribute("cableTwoHundredFortyList", cableTwoHundredFortyList);
		model.addAttribute("cableSeventyList", cableSeventyList);
		model.addAttribute("uuid", uuid);
		return "modules/sg/raiseCapitalDesign/cableSectionForm";
	}
	/**
	 * 拆旧材料清册
	 * 查看，增加，编辑提资表单表单页面
	 */
	@RequestMapping(value = "inventoryForm")
	public String inventoryForm(String uuid, Model model) {
		List<InventoryInfo> inventoryList = raiseCapitalDesignService.getInventory(uuid + "inventory");
		model.addAttribute("inventoryList", inventoryList);
		model.addAttribute("uuid", uuid);
		return "modules/sg/raiseCapitalDesign/inventoryForm";
	}

	/**
	 * 架空导线计算处理
	 */
	@ResponseBody
	//@RequiresPermissions(value={"test:raiseCapitalDesign:add","test:raiseCapitalDesign:edit"},logical=Logical.OR)
	@RequestMapping(value = "saveVlatage")
	public AjaxJson saveVlatage(VoltageData voltageData, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(voltageData);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		raiseCapitalDesignService.saveVlatage(voltageData);//处理
		j.setSuccess(true);
		j.setMsg("处理完成");
		return j;
	}
	/**
	 * 电缆分段计算处理
	 */
	@ResponseBody
	@RequestMapping(value = "saveCable")
	public AjaxJson saveCable(CableSectionData cableSectionData, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(cableSectionData);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		raiseCapitalDesignService.saveCable(cableSectionData);//处理
		j.setSuccess(true);
		j.setMsg("处理完成");
		return j;
	}
	/**
	 * 电缆分段计算处理
	 */
	@ResponseBody
	@RequestMapping(value = "saveInventory")
	public AjaxJson saveInventory(InventoryData inventoryData, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(inventoryData);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		raiseCapitalDesignService.saveInventory(inventoryData);//处理
		j.setSuccess(true);
		j.setMsg("处理完成");
		return j;
	}

	/**
	 * 保存提资表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:raiseCapitalDesign:add","test:raiseCapitalDesign:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(RaiseCapital raiseCapital, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(raiseCapital);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		raiseCapitalDesignService.save(raiseCapital);//保存
		j.setSuccess(true);
		j.setMsg("保存提资表单成功");
		return j;
	}

	/**
	 * 删除提资表单
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapitalDesign:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(RaiseCapital raiseCapital) {
		AjaxJson j = new AjaxJson();
		raiseCapitalDesignService.delete(raiseCapital);
		j.setMsg("删除提资表单成功");
		return j;
	}

	/**
	 * 批量删除提资表单
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapitalDesign:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			raiseCapitalDesignService.delete(raiseCapitalDesignService.get(id));
		}
		j.setMsg("删除提资表单成功");
		return j;
	}

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapitalDesign:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<RaiseCapital> list = ei.getDataList(RaiseCapital.class);
			for (RaiseCapital raiseCapital : list){
				try{
					raiseCapitalDesignService.save(raiseCapital);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条提资表单记录。");
			}
			j.setMsg( "已成功导入 "+successNum+" 条提资表单记录"+failureMsg);
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入提资表单失败！失败信息："+e.getMessage());
		}
		return j;
    }

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

    /**
	 * 获取item和基础数据，存入hashmap，存入redis
	 * */
	@ResponseBody
	@RequestMapping(value = "exportCache")
	public AjaxJson exportCache(RaiseCapital raiseCapital,String uuid,String item, HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxJson j = new AjaxJson();
		ArrayList<String> objects = new ArrayList<>();
		ArrayList<String> findList = new ArrayList<>();
		List<ShowList> myList = new ArrayList<>();
		//领料清单list
		List<ShowList> billMaterials = new ArrayList<>();
		ShowList showList = new ShowList();
		if (item != null&&!"".equals(item)) {
			String[] split = item.split(";");
			for (int i = 0; i < split.length; i++) {
				objects.add(split[i]);
			}
			for (String s : objects) {
				String[] split1 = s.split(":");
				ShowList myShow = new ShowList();
				myShow.setId(split1[0]);
				String s1 = split1[1];
				myShow.setNumber(Double.parseDouble(s1));
				findList.add(split1[0]);
				myList.add(myShow);
			}
		}
		HashMap<String, Object> saveMap = new HashMap<>();
		saveMap.put("raiseCapital", raiseCapital);
		saveMap.put("myList", myList);
		String id = UserUtils.getUser().getId();
		CacheChannel channel = J2Cache.getChannel();
		RedisClient client = ((RedisCacheProvider)channel.getL2Provider()).getRedisClient();
		try {
			client.get().setex(id.getBytes(),120, SerializeUtil.serizlize(saveMap));
		} finally {
			client.release();
		}
		j.setSuccess(true);
		return j;
	}

	@ResponseBody
	@RequestMapping(value = "export")
	public Result exportFile(String projectName,String uuid,HttpServletRequest request, HttpServletResponse response){
		Result j = new Result();
		try {
			raiseCapitalDesignService.getExport(projectName,uuid,request,response);
			j.setSuccess(true);
			j.setMsg("导出成功！");

			CacheChannel channel = J2Cache.getChannel();
			RedisClient client = ((RedisCacheProvider)channel.getL2Provider()).getRedisClient();
			//导出成功后删除reids中的对应uuid的数据(没有模糊删除，只能一条条删除)
			BinaryJedisCommands binaryJedisCommands = client.get();
			binaryJedisCommands.del((uuid + "voltageDisposeData").getBytes());
			binaryJedisCommands.del((uuid + "highVoltage").getBytes());
			binaryJedisCommands.del((uuid + "lowVoltage").getBytes());

			binaryJedisCommands.del((uuid + "cableDisposeData").getBytes());
			binaryJedisCommands.del((uuid + "cableFourHundred").getBytes());
			binaryJedisCommands.del((uuid + "cableHundredAndTwenty").getBytes());
			binaryJedisCommands.del((uuid + "cableThreeHundred").getBytes());
			binaryJedisCommands.del((uuid + "cableTwoHundredForty").getBytes());
			binaryJedisCommands.del((uuid + "cableSeventy").getBytes());

			binaryJedisCommands.del((uuid + "inventory").getBytes());
		}catch (Exception e){
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
		return j;
	}
}
