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

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.filing.approvalStage.entity.ApprovalStage;
import com.jeeplus.modules.filing.approvalStage.service.ApprovalStageService;
import com.jeeplus.modules.filing.constructionStage.entity.ConstructionStage;
import com.jeeplus.modules.filing.filingImages.entity.FilingImages;
import com.jeeplus.modules.filing.filingImages.service.FilingImagesService;
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 java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 核准阶段Controller
 * @author qy
 * @version 2021-03-24
 */
@Controller
@RequestMapping(value = "${adminPath}/filing/approvalStage")
public class ApprovalStageController extends BaseController {

	@Autowired
	private ApprovalStageService approvalStageService;

	@Autowired
	private FilingImagesService filingImagesService;

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

	/**
	 * 核准阶段列表页面
	 */
	@RequiresPermissions("test:filing:approvalStage:list")
	@RequestMapping(value = {"list", ""})
	public String list(ApprovalStage approvalStage, Model model) {
		model.addAttribute("approvalStage", approvalStage);
		return "modules/filing/approvalStage/approvalStageList";
	}

		/**
	 * 核准阶段列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:approvalStage:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ApprovalStage approvalStage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ApprovalStage> page = approvalStageService.findPage(new Page<ApprovalStage>(request, response,-1), approvalStage);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加,核准阶段表单页面
	 */
	@RequiresPermissions(value={"test:filing:approvalStage:view","test:filing:approvalStage:add","test:filing:approvalStage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ApprovalStage approvalStage, Model model) {
		model.addAttribute("approvalStage", approvalStage);
		return "modules/filing/approvalStage/approvalStageForm";
	}


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

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


	/**
	 * 删除核准阶段
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:approvalStage:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ApprovalStage approvalStage) {
		AjaxJson j = new AjaxJson();
		approvalStageService.delete(approvalStage);
		j.setMsg("删除核准阶段成功");
		return j;
	}

	/**
	 * 批量删除核准阶段
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:approvalStage:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			approvalStageService.delete(approvalStageService.get(id));
		}
		j.setMsg("删除核准阶段成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:approvalStage:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(ApprovalStage approvalStage, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "核准阶段"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			//查询所有父级的信息
			List<ApprovalStage> list = approvalStageService.findList(approvalStage);
			List<ApprovalStage> returnList = new ArrayList<>();
			//根据父级，查询所有子级的信息
			for (ApprovalStage a :
					list) {
				List<ApprovalStage> childList = approvalStageService.findChildList(a);
				returnList.add(a);
				for (ApprovalStage b :
						childList) {
					returnList.add(b);
				}
			}
    		new ExportExcel("核准阶段", ApprovalStage.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 = "exportFiles")
	public void exportFiles(String ids, HttpServletResponse servletResponse) {
		AjaxJson j = new AjaxJson();
		List<FilingImages> allList = new ArrayList<>();
		if (null != ids && !"".equals(ids)) {
			String idArray[] = ids.split(",");
			for (String id : idArray) {
				//获取选择项目的信息及附件信息
				List<FilingImages> approvalStage = filingImagesService.findByProjectId(id);
				for (FilingImages f :
						approvalStage) {
					if (f.getImgPath().contains("|")) {
						String[] split = f.getImgPath().split("\\|");
						for (int i = 0; i < split.length; i++) {
							String s = split[i];
							FilingImages filingImages = new FilingImages();
							filingImages.setImgPath(s);
							filingImages.setProjectCode(f.getProjectCode());
							filingImages.setPurpose(f.getPurpose());
							allList.add(filingImages);
						}
					} else {
						allList.add(f);
					}
				}
			}
		} else {
			//获取所有项目的信息及附件
			allList = filingImagesService.findAllList(new FilingImages());
		}

		File srcfile[] = new File[allList.size()];
		for (int i = 0; i < allList.size(); i++) { //这里是在模拟添加文件  修改为自己要压缩的文件
			String imgPath = allList.get(i).getImgPath();
			if (null != imgPath && !"".equals(imgPath)) {
				srcfile[i] = new File(imgPath);
			}
		}
		String zipname = "test" + ".zip";
		File zip = new File(zipname);// 压缩文件
		if (zip.exists()) {
			try {
				zip.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		ZipFiles(srcfile, zip);
		/*try {
			// 获取压缩文件流
			InputStream zipStream = new FileInputStream(new File("/附件下载.zip"));
			// 下载文件名中文处理
			String downZipFileName = URLEncoder.encode("附件下载.zip".substring("附件下载.zip".lastIndexOf("/") + 1), "UTF-8");
			// 下载到浏览器
			servletResponse.setHeader("Content-disposition", "attachment; filename*=UTF-8''" + downZipFileName);
			BufferedOutputStream bufferedOs = new BufferedOutputStream(servletResponse.getOutputStream());
			byte[] buffer = new byte[10240];
			int bytesRead = 0;
			while ((bytesRead = zipStream.read(buffer)) != -1) {
				bufferedOs.write(buffer, 0, bytesRead);
			}
			bufferedOs.flush();
			bufferedOs.close();
			zipStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}*/
	}


	/**
	  文件压缩
	 */
	private static void ZipFiles(java.io.File[] srcfile, java.io.File zipfile) {
		byte[] buf=new byte[1024];
		ZipOutputStream out=null;
		try {
			out=new ZipOutputStream(new FileOutputStream(
					zipfile));
			for (int i=0; i < srcfile.length; i++) {
				FileInputStream in=new FileInputStream(srcfile[i]);
				out.putNextEntry(new ZipEntry(srcfile[i].getName()));
				int len;
				while ((len=in.read(buf)) > 0) {
					out.write(buf, 0, len);
				}
				out.closeEntry();
				in.close();
			}
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


    @ResponseBody
    @RequestMapping(value = "detail")
	public Map<String, Object> detail(ApprovalStage approvalStage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ApprovalStage> page = approvalStageService.findChildPage(new Page<ApprovalStage>(request, response), approvalStage);
		return getBootstrapData(page);
	}


	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:approvalStage: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<ApprovalStage> list = ei.getDataList(ApprovalStage.class);
			for (ApprovalStage approvalStage :
					list) {
				approvalStageService.save(approvalStage);
			}
			j.setMsg( "已成功导入条核准阶段记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入核准阶段失败！失败信息："+e.getMessage());
		}
		return j;
    }

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

}