package com.jeeplus.modules.filing.summary.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
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.filing.basicInformation.service.BasicInformationService;
import com.jeeplus.modules.filing.filingImages.entity.FilingImages;
import com.jeeplus.modules.filing.summary.entity.Summary;
import com.jeeplus.modules.filing.summary.service.SummaryService;
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 org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 汇总管理Controller
 * @author qy
 * @date 2021-04-13
 */
@Controller
@RequestMapping(value = "${adminPath}/filing/summary")
public class SummaryController extends BaseController {

	@Autowired
	private SummaryService summaryService;

	@Autowired
	private BasicInformationService basicInformationService;
	
	@ModelAttribute
	public Summary get(@RequestParam(required=false) String id) {
		Summary entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = summaryService.get(id);
		}
		if (entity == null){
			entity = new Summary();
		}
		return entity;
	}
	
	/**
	 * 汇总列表页面
	 */
	@RequiresPermissions("test:filing:summary:list")
	@RequestMapping(value = {"list", ""})
	public String list(Summary summary, Model model) {
		model.addAttribute("summary", summary);
		return "modules/filing/summary/summaryList";
	}
	
		/**
	 * 汇总列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Summary summary, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Summary> page = summaryService.findPage(new Page<Summary>(request, response,-1), summary);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加,汇总表单页面
	 */
	@RequiresPermissions(value={"test:filing:summary:view","test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Summary summary, Model model) {
		model.addAttribute("summary", summary);
		return "modules/filing/summary/summaryForm";
	}

	/**
	 * 修改,汇总表单页面
	 */
	@RequiresPermissions(value={"test:filing:summary:view","test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "updateForm")
	public String updateForm(Summary summary, Model model) {
		model.addAttribute("summary", summary);
		return "modules/filing/summary/updateForm";
	}

	/**
	 * 字类查看，增加，编辑汇总表单页面
	 */
	@RequiresPermissions(value={"test:filing:summary:view","test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "childForm")
	public String childForm(Summary summary, Model model) {
		model.addAttribute("summary", summary);
		return "modules/filing/summary/childForm";
	}

	/**
	 * 保存汇总
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Summary summary, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(summary);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//判断，项目前期阶段是否存在



		//新增或编辑表单保存
		Boolean aBoolean = summaryService.saveAll(summary);//保存
		if (false == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码已存在");
		} else {
			j.setSuccess(true);
			j.setMsg("保存汇总成功");
		}
		return j;
	}

	/**
	 * 保存汇总
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "updateSave")
	public AjaxJson updateSave(Summary summary, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(summary);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		Boolean aBoolean = summaryService.updateAll(summary);//保存
		if (true == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码重复");
		} else {
			j.setSuccess(true);
			j.setMsg("保存汇总成功");
		}
		return j;
	}

	/**
	 * 保存汇总
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:summary:add","test:filing:summary:edit"},logical=Logical.OR)
	@RequestMapping(value = "childSave")
	public AjaxJson childSave(Summary summary, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(summary);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		Boolean aBoolean = summaryService.updateChild(summary);//保存
		if (true == aBoolean) {
			j.setSuccess(false);
			j.setMsg("项目编码重复");
		} else {
			j.setSuccess(true);
			j.setMsg("保存汇总成功");
		}
		return j;
	}
	
	/**
	 * 删除汇总
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Summary summary) {
		AjaxJson j = new AjaxJson();
		summaryService.delete(summary);
		j.setMsg("删除汇总成功");
		return j;
	}
	
	/**
	 * 批量删除汇总
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			summaryService.delete(summaryService.get(id));
		}
		j.setMsg("删除汇总成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(Summary summary, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "汇总"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			//查询所有父级的信息
			List<Summary> list = summaryService.findList(summary);
			List<Summary> returnList = new ArrayList<>();
			//根据父级，查询所有子级的信息
			for (Summary a :
					list) {
				List<Summary> childList = summaryService.findAllChildList(a);
				returnList.add(a);
				for (Summary b :
						childList) {
					returnList.add(b);
				}
			}
			new ExportExcel("汇总", Summary.class).setDataList(returnList).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出汇总记录失败！失败信息："+e.getMessage());
		}
			return j;
    }


	@ResponseBody
    @RequestMapping(value = "detail")
	public Map<String, Object> detail(Summary summary, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Summary> page = summaryService.findOnePage(new Page<Summary>(request, response), summary);
		return getBootstrapData(page);
	}
	

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:import")
    @RequestMapping(value = "import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		try {
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Summary> list = ei.getDataList(Summary.class);
			for (Summary s :
					list) {
				summaryService.save(s);
			}
			j.setMsg( "已成功导入汇总记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入汇总失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入汇总数据模板
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:summary:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "汇总数据导入模板.xlsx";
    		List<Summary> list = Lists.newArrayList(); 
    		new ExportExcel("汇总数据", Summary.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	

}