package com.fourdage.dingding.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fourdage.base.common.JsonResult;
import com.fourdage.base.controller.BaseController;
import com.fourdage.dingding.entity.Department;
import com.fourdage.dingding.entity.DingDingSearchBean;
import com.fourdage.dingding.entity.ProcessCode;
import com.fourdage.dingding.entity.ProcessInstance;
import com.fourdage.dingding.service.IDepartmentService;
import com.fourdage.dingding.service.IProcessCodeService;
import com.fourdage.dingding.util.DingDingUtil;
import com.fourdage.dingding.util.FileUtil;
import com.fourdage.dingding.util.HtmlPdfUtil;
import com.fourdage.dingding.util.ZipUtil;
import com.fourdage.system.entity.DataDictionary;
import com.fourdage.system.entity.User;
import com.fourdage.system.service.IDataDictionaryService;

@Controller
@RequestMapping("/dingding/examination")
public class ExaminationController extends BaseController{
	
	@Value("${web.pdf.file.path}")
    private String path;
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IProcessCodeService processCodeService;
	@Autowired
	private HtmlPdfUtil htmlPdfUtil;
	@Autowired
	private DingDingUtil dingDingUtil;
	@Autowired
	private IDataDictionaryService dataDictionaryService;
	
    @RequestMapping("/index")
    public String index(ModelMap map) {
    	String region = dingDingUtil.getRegion();
    	
    	List<ProcessCode> processes = processCodeService.findByRegion(region);
    	List<DataDictionary> companys = dataDictionaryService.findByCode("company");
    	map.put("process", processes);
    	map.put("companys", companys);
		return "dingding/examination/index";
    }
    
	@RequestMapping(value = {"/list"}, method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> list(String datetime, String applyDate, String processCodeId, String businessNum, String companyId){
    	logger.info("run list");
		logger.info("input arg:  datetime：{}, applyDate:{}, processCodeId:{}, businessNum:{}, companyId:{}", datetime, applyDate, processCodeId, businessNum, companyId);
		
		Map<String, Object> result = new HashMap<>();
		try {
			String startTime = "";
			String endTime = "";
			
			if (datetime != null){
				startTime = datetime.split(" - ")[0];
				endTime = datetime.split(" - ")[1];
			}
			
			DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");    
			DateTime startDateTime = new DateTime(new DateTime().getYear(), new DateTime().getMonthOfYear(), 1, 0, 0, 0);
			//默认从钉钉上获取当月第一天，作为提交申请的开始时间；
			long startTimelong = startDateTime.getMillis();
			if (StringUtils.isNotEmpty(applyDate)){
				startTimelong = DateTime.parse(applyDate, format).toDate().getTime();
			}
			
			//用户选择审批时间段, 默认取今天
			long startTimeSearch = new DateTime().withMillisOfDay(0).getMillis();
			if (StringUtils.isNotEmpty(startTime)){
				startTimeSearch = DateTime.parse(startTime, format).toDate().getTime();
			}
			long endTimeSearch = new DateTime().millisOfDay().withMaximumValue().toDate().getTime();
			if (StringUtils.isNotEmpty(endTime)){
				endTimeSearch = DateTime.parse(endTime, format).toDate().getTime();
			}
			
			ProcessCode processCode = processCodeService.find(Integer.valueOf(processCodeId));
			List<ProcessInstance> processes = new ArrayList<ProcessInstance>();
			
			DingDingSearchBean vo = new DingDingSearchBean();
			vo.setProcessCode(processCode.getProcessCode());
			vo.setStartTime(startTimelong);
			vo.setStartTimeSearch(startTimeSearch);
			vo.setEndTimeSearch(endTimeSearch);
			vo.setBusinessNum(businessNum);
			if (StringUtils.isNotEmpty(companyId)){
				DataDictionary d = dataDictionaryService.find(Integer.valueOf(companyId));
				vo.setCompany(d.getDataValue());
			}
			
			dingDingUtil.getProcesses(processes, vo);

			result.put("code", 0);
			result.put("msg", "");
			result.put("count", processes.size());
			result.put("data", processes);
			return result;
		}
		catch (Exception e) {
			result.put("code", 1);
			result.put("msg", "报500错误啦，请联系管理员！");
			return result;
        }
	}

	/**
	 * 查看审批详情
	 * @param processInstanceId
	 * @param processCodeId
	 * @param title
	 * @param businessId
	 * @param map
	 * @return
	 */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult detail(String processInstanceId, String processCodeId, String title, String businessId, ModelMap map) {
    	
        try {
        	//首先查找文件是否已经存在
        	ProcessCode processCode = processCodeService.findById(Integer.valueOf(processCodeId));
            String fileName = dingDingUtil.getFileName(processCode.getProcessName(), title, businessId);
    		String filePathName = path + fileName + ".html";
    		//生成文件夹
    		File dirFile = new File(path + processCode.getProcessName());
    		if(!dirFile.exists()){
    			dirFile.mkdir();
    		}
    		File file = new File(filePathName);

			// 2023-09-19 覆盖旧文件
			file.createNewFile();
    		
    		htmlPdfUtil.generateHTMLFile_2(dingDingUtil.getAccessToken(), processInstanceId, fileName);
        	return JsonResult.success(fileName + ".html");
        } catch (Exception e) {
        	logger.error("系统异常：", e);
            return JsonResult.failure("系统异常："+e);
        }finally{
        }
    }

    /**
     * 下载单个pdf
     * @param processInstanceId
     * @param processCodeId
     * @param title
     * @param businessId
     * @param res
     */
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(String processInstanceId, String processCodeId, String title, String businessId, HttpServletResponse res){
    	logger.info("run download");
    	
        //首先查找文件是否已经存在
    	ProcessCode processCode = processCodeService.findById(Integer.valueOf(processCodeId));
        String fileName = dingDingUtil.getFileName(processCode.getProcessName(), title, businessId);
		File file = new File(path + fileName + ".html");
//		if (!file.exists()){
//			//不存在则生成html和pdf文件
//			htmlPdfUtil.generateHtmlAndPDF(dingDingUtil.getAccessToken(), processInstanceId, processCode.getProcessName());
//		}else{
//			//存在则生成pdf文件
//			htmlPdfUtil.generatePdfFile(path + fileName);
//		}

		// 2023-09-19 覆盖旧文件
		//不存在则生成html和pdf文件
			htmlPdfUtil.generateHtmlAndPDF(dingDingUtil.getAccessToken(), processInstanceId, processCode.getProcessName());
		// 存在则生成pdf文件
			htmlPdfUtil.generatePdfFile(path + fileName);
		
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			String name = title + businessId;
			String fileRealName = new String(name.getBytes(), "ISO-8859-1");
			res.setHeader("content-type", "application/octet-stream");
			res.setContentType("application/octet-stream");
			res.setHeader("Content-Disposition", "attachment;filename=" + fileRealName + ".pdf");
			byte[] buff = new byte[1024];
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(path + fileName + ".pdf")));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			logger.error("系统异常：", e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error("系统异常：", e);
				}
			}
			FileUtil.deleteFile(path + fileName + ".pdf");
		}
		logger.info("Download successfully");
    }

    /**
     * 下载打包的pdf文件 
     * @param filePath
     * @param fileName
     * @param res
     */
    @RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
    public void downloadFile(String filePath, String fileName, HttpServletResponse res){
    	
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			String fileRealName = new String(fileName.getBytes(), "ISO-8859-1");
			res.setHeader("content-type", "application/octet-stream");
			res.setContentType("application/octet-stream");
			res.setHeader("Content-Disposition", "attachment;filename=" + fileRealName);
			byte[] buff = new byte[1024];
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File(filePath)));
			int i = bis.read(buff);
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			logger.error("系统异常：", e);
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					logger.error("系统异常：", e);
				}
			}
			FileUtil.deleteFile(filePath);
		}
		logger.info("Download successfully");
    }
    
    /**
     * 生成打包文件
     * @param processInstanceIds
     * @param processCodeId
     * @param res
     * @return
     */
    @RequestMapping(value = "/downloadAll", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult downloadAll(String processInstanceIds, String processCodeId, HttpServletResponse res){
    	ProcessCode processCode = processCodeService.find(Integer.valueOf(processCodeId));
    	try{
    		//先删除该目录下所有文件
        	FileUtil.deleteFolder(path + processCode.getProcessName());
    		
    		//生成pdf
	        String[] processInstanceIdArr = processInstanceIds.split(",");
	        for (String processInstanceId : processInstanceIdArr){
	        	htmlPdfUtil.generateHtmlAndPDF(dingDingUtil.getAccessToken(), processInstanceId, processCode.getProcessName());
	        }
	        //将pdf打包成zip
	        String sourceFilePath = path + processCode.getProcessName() + "/";
	        String zipName = processCode.getProcessName() + new Date().getTime();
	        
	        FileOutputStream fos1 = new FileOutputStream(new File(path + zipName + ".zip"));
	        ZipUtil.toZip(sourceFilePath, fos1, false);
	        
	        JSONObject object = new JSONObject();
	        object.put("fileName", zipName + ".zip");
	        object.put("filePath", path + zipName + ".zip");
	        
	        
	        return JsonResult.success(object);
	    } catch (Exception e) {
	    	logger.error("系统异常：", e);
	        return JsonResult.failure("系统异常："+e);
	    }finally {
	    	//删除该目录下所有文件
        	FileUtil.deleteFolder(path + processCode.getProcessName());
	    }
    }
}

