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.entity.EarlyStage;
import com.jeeplus.modules.filing.approvalStage.service.EarlyStageService;
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.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
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/earlyStage")
public class EarlyStageController extends BaseController {

	@Autowired
	private EarlyStageService earlyStageService;

	@Autowired
	private FilingImagesService filingImagesService;

	@ModelAttribute
	public EarlyStage get(@RequestParam(required=false) String id) {
		EarlyStage entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = earlyStageService.get(id);
		}
		if (entity == null){
			entity = new EarlyStage();
		}
		return entity;
	}
	
	/**
	 * 项目前期阶段列表页面
	 */
	@RequiresPermissions("test:filing:earlyStage:list")
	@RequestMapping(value = {"list", ""})
	public String list(EarlyStage earlyStage, Model model) {
		model.addAttribute("earlyStage", earlyStage);
		return "modules/filing/earlyStage/earlyStageList";
	}
	
		/**
	 * 项目前期阶段列表数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(EarlyStage earlyStage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EarlyStage> page = earlyStageService.findPage(new Page<EarlyStage>(request, response,-1), earlyStage);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加,项目前期阶段表单页面
	 */
	@RequiresPermissions(value={"test:filing:earlyStage:view","test:filing:earlyStage:add","test:filing:earlyStage:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(EarlyStage earlyStage, Model model) {
		model.addAttribute("earlyStage", earlyStage);
		return "modules/filing/earlyStage/earlyStageForm";
	}


	/**
	 * 查看，增加,项目前期阶段表单页面-字类数据列表
	 */
	@RequiresPermissions(value={"test:filing:earlyStage:view","test:filing:earlyStage:add","test:filing:earlyStage:edit"},logical=Logical.OR)
	@RequestMapping(value = "childForm")
	public String childForm(EarlyStage earlyStage, Model model) {
		model.addAttribute("earlyStage", earlyStage);
		return "modules/filing/earlyStage/earlyStageChildForm";
	}
	
	/**
	 * 保存项目前期阶段
	 */
	@ResponseBody
	@RequiresPermissions(value={"test:filing:earlyStage:add","test:filing:earlyStage:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(EarlyStage earlyStage, Model model) throws Exception{
		AjaxJson j = new AjaxJson();
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(earlyStage);
		if (StringUtils.isNotBlank(errMsg)){
			j.setSuccess(false);
			j.setMsg(errMsg);
			return j;
		}
		//新增或编辑表单保存
		earlyStageService.save(earlyStage);//保存
		j.setSuccess(true);
		j.setMsg("保存项目前期阶段成功");
		return j;
	}

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


	/**
	 * 删除项目前期阶段
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(EarlyStage earlyStage) {
		AjaxJson j = new AjaxJson();
		earlyStageService.delete(earlyStage);
		j.setMsg("删除项目前期阶段成功");
		return j;
	}
	
	/**
	 * 批量删除项目前期阶段
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			earlyStageService.delete(earlyStageService.get(id));
		}
		j.setMsg("删除项目前期阶段成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage:export")
    @RequestMapping(value = "export")
    public AjaxJson exportFile(EarlyStage earlyStage, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "项目前期阶段"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			//查询所有父级的信息
			List<EarlyStage> list = earlyStageService.findList(earlyStage);
			List<EarlyStage> returnList = new ArrayList<>();
			//根据父级，查询所有子级的信息
			for (EarlyStage a :
					list) {
				List<EarlyStage> childList = earlyStageService.findChildList(a);
				returnList.add(a);
				for (EarlyStage b :
						childList) {
					returnList.add(b);
				}
			}
    		new ExportExcel("项目前期阶段", EarlyStage.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> earlyStage = filingImagesService.findByProjectId(id);
				for (FilingImages f :
						earlyStage) {
					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(File[] srcfile, 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(EarlyStage earlyStage, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EarlyStage> page = earlyStageService.findChildPage(new Page<EarlyStage>(request, response), earlyStage);
		return getBootstrapData(page);
	}
	

	/**
	 * 导入Excel数据
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage: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<EarlyStage> list = ei.getDataList(EarlyStage.class);
			for (EarlyStage earlyStage :
					list) {
				earlyStageService.save(earlyStage);
			}
			j.setMsg( "已成功导入条项目前期阶段记录");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导入项目前期阶段失败！失败信息："+e.getMessage());
		}
		return j;
    }
	
	/**
	 * 下载导入项目前期阶段数据模板
	 */
	@ResponseBody
	@RequiresPermissions("test:filing:earlyStage:import")
    @RequestMapping(value = "import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "项目前期阶段数据导入模板.xlsx";
    		List<EarlyStage> list = Lists.newArrayList(); 
    		new ExportExcel("项目前期阶段数据", EarlyStage.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg( "导入模板下载失败！失败信息："+e.getMessage());
		}
		return j;
    }
	

}