package com.engine.custom.hg.service;


import com.engine.custom.hg.entity.HGBean;
import com.engine.custom.hg.util.HgUtils;
import com.engine.custom.hg.util.ZipUtil;

import org.apache.tools.zip.ZipOutputStream;
import weaver.conn.RecordSet;
import weaver.file.ImageFileManager;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class TextDocFileService   {
    private static ZipUtil zipUtil= new ZipUtil();
    BaseBean bean = new BaseBean();
    private final String filePath = bean.getPropValue("fjwz","filePath");
    // private static final String filePath = "E:\\test";
    //出巡时间内推送失败或未推送的数据
    public static final String getrqBydatesql = "select * from uf_tohgLog where ddsj > ? and ddsj < ? and( zt = 0   or zt = 2)";
    public static final String updatesql = "update uf_tohgLog set  esbml = ? where id = ?";
    public static final String updatetxtsql = "update uf_tohgLog set  zt = 1 , esbtxtml = ? where id in (";


    public  void genDocTxt(String day, String tranCode) {
        String dirDate = zipUtil.mkTemper(filePath);
        RecordSet recordSet = new RecordSet();
        bean.writeLog("dirDate====="+dirDate);
        Date date = getDate(day);
        // 获取当前时间的第一秒
        SimpleDateFormat yyyyMMddHHmmss = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String firstSecond = yyyyMMddHHmmss.format(getFirstSecondOfDate(date));

        // 获取当前时间的最后一秒
        String lastSecond =yyyyMMddHHmmss.format(getLastSecondOfDate(date));
        File file = null;
        List<HGBean> HGBeans = getData(firstSecond, lastSecond);
        String dateDir  = "tohg_" + new SimpleDateFormat("yyyyMMdd000000").format(date);
        if ("HG".equals(tranCode)) {
            file = zipUtil.crFile(dirDate + "/tohg_" + new SimpleDateFormat("yyyyMMdd000000").format(date));
            bean.writeLog("推送合规系统"+file.getPath()+file.getName());
        } else {
            // log.info("无此系统" + tranCode + ",拒绝推送");
        }
        ArrayList<String> ids = new ArrayList<>();

        if (HGBeans.size() == 0) {
            // zipUtil.writeToTxt(file.getPath(), file.getName(), "", false);
        }else{
            for (HGBean hgBean : HGBeans) {
                //生成TXT
                // String s1 = new String(hgBean.getContent().getBytes(StandardCharsets.UTF_8));
                zipUtil.writeToTxt(file.getPath(), file.getName(), hgBean.getContent() , true);
                // zipUtil.writeToTxt(file.getPath(), file.getName(), s1 , true);

                //生成附件
                Map<String,String> fjIdName = new HashMap<String,String>();
                Map<String,String> fjIdPath = new HashMap<String,String>();
                Map<String,String> zwIdName = new HashMap<String,String>();
                Map<String,String> zwIdPath = new HashMap<String,String>();
                Map<String,String> fjIdimg = new HashMap<String,String>();
                Map<String,String> zwIdimg = new HashMap<String,String>();
                Map<String,String> reqESBpathMap = new HashMap<String,String>();
                getIdPathName(hgBean.getFjid(),fjIdPath,fjIdName);
                getIdPathName(hgBean.getZwid(),zwIdPath,zwIdName);
                // bean.writeLog(fjIdName.toString());
                // bean.writeLog(fjIdPath.toString());
                // bean.writeLog(zwIdName.toString());
                // bean.writeLog(zwIdPath.toString());
                getIdIMIDName(hgBean.getFjid(),fjIdimg);
                getIdIMIDName(hgBean.getZwid(),zwIdimg);
                //压缩 =正文附件文件
                bean.writeLog("压缩文件开始====="+file.getPath() + File.separator + hgBean.getRequestId()+".zip");
                File filezip = new File(file.getPath() + File.separator + hgBean.getRequestId()+".zip");
                ZipOutputStream zos =null;
                try {
                    zos = new ZipOutputStream( new FileOutputStream(filezip));
                    // zos.setEncoding("gbk");
                    addFile2zip(file, hgBean, fjIdimg,1,zos);
                    addFile2zip(file, hgBean, zwIdimg,2,zos);

                // } catch (UnsupportedEncodingException e) {
                //     bean.writeLog("压缩文件异常====="+file.getPath() + File.separator + hgBean.getRequestId()+".zip");
                //     bean.writeLog("压缩文件异常信息====="+e.getMessage());
                //     e.printStackTrace();
                } catch ( FileNotFoundException e) {
                    bean.writeLog("压缩文件异常====="+file.getPath() + File.separator + hgBean.getRequestId()+".zip");
                    bean.writeLog("压缩文件异常信息====="+e.getMessage());
                    e.printStackTrace();
                } finally {
                    try {
                        zos.close();
                        bean.writeLog("压缩文件结束====="+file.getPath() + File.separator + hgBean.getRequestId()+".zip");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                try {
                    bean.writeLog("filezip.getAbsolutePath()==="+filezip.getAbsolutePath());
                    bean.writeLog("hgBean.getRequestId()+\".zip\"==="+hgBean.getRequestId()+".zip");
                    //推送附件
                    // String s = HgUtils.putFile(filezip.getAbsolutePath(), dateDir+File.separator+hgBean.getRequestId() + ".zip");
                    String s = HgUtils.putFile(filezip.getAbsolutePath(), hgBean.getRequestId() + ".zip");
                    if (s.length()>0){
                        ids.add(hgBean.getId()+"");
                        recordSet.executeUpdate(updatesql,s,hgBean.getId());
                    }
                    bean.writeLog("ESB返回==="+s);
                } catch (com.dcfs.fts.common.error.FtpException e) {
                    bean.writeLog("FTP异常==="+e.getMessage());
                } catch (IOException e) {
                    bean.writeLog("FTP异常==="+e.getMessage());
                    e.printStackTrace();
                }

            }
            //    压缩txt推送
            File writename = new File(file.getPath() + File.separator+"tohg_" + new SimpleDateFormat("yyyyMMdd000000").format(date)+".txt");
            File txtzip = new File(file.getPath() + File.separator + "tohg_" + new SimpleDateFormat("yyyyMMdd000000").format(date)+".zip");
            bean.writeLog("writename ==== "+writename.getAbsolutePath()  +"===="+ writename.getName());
            bean.writeLog("txtzip ==== "+txtzip.getAbsolutePath() +"===="+ txtzip.getName());
            try {
                OutputStream outputStream = new FileOutputStream(txtzip);
                ZipUtil.filesToZip(writename , outputStream ,"tohg_" + new SimpleDateFormat("yyyyMMdd000000").format(date)+File.separator+writename.getName());
                // String s = HgUtils.putFile(txtzip.getAbsolutePath(), dateDir+File.separator+dateDir + ".zip");
                String s = HgUtils.putFile(txtzip.getAbsolutePath(), dateDir + ".zip");
                bean.writeLog("ESB返回==="+s);
                if (s.length()>0){
                    String idstr =  String.join(",",ids);
                    recordSet.executeUpdate(updatetxtsql+idstr+" )",s);
                }
            } catch (Exception e) {
                bean.writeLog("FTP异常==="+e.getMessage());
                e.printStackTrace();
            }

        }
    }

    private void addFile2zip(File file, HGBean hgBean, Map<String, String> Idimg, int type, ZipOutputStream zos) {
        String fileType =  "";

        if (type == 1){
        fileType = hgBean.getRequestId()+File.separator+"附件"+File.separator;
        }else if(type == 2){
            fileType = hgBean.getRequestId()+File.separator+"正文"+File.separator;
        }
        // String path = new String(fileType.getBytes(StandardCharsets.UTF_8));
        // File filepath = zipUtil.crFile(file.getPath() + File.separator + hgBean.getRequestId());


        String finalFileType = fileType;
        ArrayList<String> fileNameList = new ArrayList<>();

        Idimg.forEach((key, value)  ->{
            FileOutputStream fos = null;
            try {
                // fos = new FileOutputStream(filezip);
                // org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(fos);
                //
                // zos.setEncoding("utf-8");

                ImageFileManager ifm = new ImageFileManager();
                ifm.getImageFileInfoById(Integer.parseInt(value));
                //writeLogs("2622 downloadFlag=" + downloadFlag);
                InputStream imagefile = ifm.getInputStream();
                String filename = finalFileType +ifm.getImageFileName();
                if (fileNameList.contains(filename)){
                    String tepName= filename.contains(".")? filename.substring(0, filename.indexOf(".")) : "";
                    if(tepName!=null&&!"".equals(tepName)){
                        String extNameTemp = filename.contains(".")? filename.substring(filename.lastIndexOf(".") + 1) : "";
                        filename = tepName + "_"+value+"."+extNameTemp;

                    }
                }else {
                    fileNameList.add(filename);
                }
                bean.writeLog("filename===="+filename);
                String filename2 =  new String(filename.getBytes(StandardCharsets.UTF_8));
                bean.writeLog("filename2===="+filename2);
                ZipUtil.addInputStreamToZip(imagefile,zos,filename);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    // 1 附件  2 正文
    private void addFile2Temp(Path tempFile, Map<String, String> IdPath, Map<String, String> IdName, int type) throws UnsupportedEncodingException {
        String fileType =  "";;
        if (type == 1){
          fileType = File.separator+"附件";
        }else if(type == 2){
          fileType = File.separator+"正文";
        }
        String finalFileType = new String(fileType.getBytes(StandardCharsets.UTF_8));
        IdPath.forEach((key , value) ->{
            // ZipUtil.zipToFolder(value,tempFile.toString()+ finalFileType,IdName.get(key) , );
        });
    }


    private Date getDate(String day) {
        Date date = new Date();
        if (day != null) {
            try {
                date = new SimpleDateFormat("yyyyMMdd").parse(day);
            } catch (ParseException e) {
                // writeLog("时间格式错误，重新发送指定日期失败");
                e.printStackTrace();
            }
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        //把日期往后增加一天.整数往后推,负数往前移动(1:表示明天、-1：表示昨天，0：表示今天)
        calendar.add(Calendar.DATE, -1);
        date = calendar.getTime();
        return date;
    }



    private List<HGBean> getData(String startTime, String endTime){
        bean.writeLog("获取推送合规系统数据start");
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(getrqBydatesql , startTime ,endTime);
        bean.writeLog("getrqBydatesql=="+getrqBydatesql + startTime + endTime);
        ArrayList<HGBean> hgBeans = new ArrayList<>();
        while (recordSet.next()){
            HGBean hgBean = new HGBean();
            hgBean.setId(Util.getIntValue(recordSet.getString("id")));
            hgBean.setRequestId(Util.getIntValue(recordSet.getString("request")));
            hgBean.setContent(Util.null2String(recordSet.getString("content")));
            hgBean.setZt(Util.getIntValue(recordSet.getString("zt")));
            hgBean.setDdsj(Util.null2String(recordSet.getString("ddsj")));
            hgBean.setTssj(Util.null2String(recordSet.getString("tssj")));
            hgBean.setZwid(Util.null2String(recordSet.getString("zwid")));
            hgBean.setFjid(Util.null2String(recordSet.getString("fjid")));
            String ml = Util.null2String(recordSet.getString("ml"));
            hgBean.setMl(Arrays.asList(ml.split(",")));
            String fjml = Util.null2String(recordSet.getString("fjml"));
            hgBean.setMl(Arrays.asList(fjml.split(",")));
            hgBeans.add(hgBean);
        }
        bean.writeLog("数据条数=",hgBeans.size());
        return hgBeans;
    }

    // 获取指定日期的第一秒
    public static Date getFirstSecondOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    // 获取指定日期的最后一秒
    public static Date getLastSecondOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     *
     * @param ids
     * @return id 路径
     */
    public static void getIdPathName(String ids ,Map<String,String> idFilePathMap ,Map<String,String> idFileNameMap ){
        String sql = "select docid,df.imagefilename filename,filerealpath filepath  from   docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID in ("+ids+")";
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        while (recordSet.next()){
            String docid = Util.null2String(recordSet.getString("docid"));
            String filename = Util.null2String(recordSet.getString("filename"));
            String filepath = Util.null2String(recordSet.getString("filepath"));
            idFileNameMap.put(docid,filename);
            idFilePathMap.put(docid,filepath);
        }
    };

    public static void getIdIMIDName(String ids ,Map<String,String> idimageIDMap  ){
        String sql = "select docid,df.imagefileid imgid  from   docimagefile df left join imagefile imf on df.imagefileid = imf.imagefileid where DOCID in ("+ids+")";
        RecordSet recordSet = new RecordSet();
        recordSet.execute(sql);
        while (recordSet.next()){
            String docid = Util.null2String(recordSet.getString("docid"));
            String imgid = Util.null2String(recordSet.getString("imgid"));
            idimageIDMap.put(docid,imgid);
        }
    };

    // public void put(String filenameL, String filenameR, String tranCode, int flg) throws FtpException {
    //     FtpClientConfig config = FtpClientConfig.getInstance();
    //     log.info("配置文件路径________________________________________________________________"+filePath);
    //     config.loadConf(filePath);
    //     FtpPut put = new FtpPut(filenameL, filenameR, tranCode, flg, config);
    //     log.info("PUT————————>response:[" + put.doPutFile() + "]");
    //     put.close();
    // }

    // public static String putFile(String localFileName, String remoteFileName, String tranCode) throws FtpException, IOException, com.dcfs.fts.common.error.FtpException {
    //     FtpClientConfig config = FtpClientConfig.getInstance();
    //     FtpPut ftpPut = new FtpPut(localFileName, remoteFileName, tranCode, true, true, config);
    //     String filePath = ftpPut.doPutFile();
    //     return filePath;
    // }
}
