/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sg.raiseCapital.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.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.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 qy
 * @date 2021-07-06
 */
@Controller
@RequestMapping(value = "${adminPath}/raiseCapital")
public class RaiseCapitalController extends BaseController {

	@Autowired
	private RaiseCapitalService raiseCapitalService;

	@Autowired
	private PickIngService pickIngService;

	@Autowired
	private ShowListService showListService;
	
	@ModelAttribute
	public RaiseCapital get(@RequestParam(required=false) String id) {
		RaiseCapital entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = raiseCapitalService.get(id);
		}
		if (entity == null){
			entity = new RaiseCapital();
		}
		return entity;
	}
	
	/**
	 * 提资表单列表页面
	 */
	@RequiresPermissions("test:raiseCapital:list")
	@RequestMapping(value = {"list", ""})
	public String list(RaiseCapital raiseCapital, Model model) {
		List<PickList> pickListList = raiseCapitalService.newAllList();
		model.addAttribute("pickListList", pickListList);
		model.addAttribute("raiseCapital", raiseCapital);
		return "modules/sg/raiseCapital/raiseCapital";
	}
	
		/**
	 * 提资表单列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapital:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(RaiseCapital raiseCapital, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<RaiseCapital> page = raiseCapitalService.findPage(new Page<RaiseCapital>(request, response), raiseCapital); 
		return getBootstrapData(page);
	}

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

	/**
	 * 保存提资表单
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:raiseCapital:add","test:raiseCapital: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;
		}
		//新增或编辑表单保存
		raiseCapitalService.save(raiseCapital);//保存
		j.setSuccess(true);
		j.setMsg("保存提资表单成功");
		return j;
	}
	
	/**
	 * 删除提资表单
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapital:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(RaiseCapital raiseCapital) {
		AjaxJson j = new AjaxJson();
		raiseCapitalService.delete(raiseCapital);
		j.setMsg("删除提资表单成功");
		return j;
	}
	
	/**
	 * 批量删除提资表单
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapital:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			raiseCapitalService.delete(raiseCapitalService.get(id));
		}
		j.setMsg("删除提资表单成功");
		return j;
	}

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:raiseCapital: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{
					raiseCapitalService.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:raiseCapital: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 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,HttpServletRequest request, HttpServletResponse response){
		Result j = new Result();
		try {
			raiseCapitalService.getExport(projectName,request,response);
			j.setSuccess(true);
			j.setMsg("导出成功！");
		}catch (Exception e){
			j.setSuccess(false);
			j.setMsg("导出失败！失败信息："+e.getMessage());
		}
		return j;
	}
}