package com.chinaweal.aiccs.crgs.transfor.schedule;

import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.common.util.filestorage.FileStorageService;
import com.chinaweal.aiccs.crgs.transfor.entity.OtNcaseDownloadLog;
import com.chinaweal.aiccs.crgs.transfor.entity.OtNpermitDownloadLog;
import com.chinaweal.aiccs.crgs.transfor.sdk.XzcfWsBO;
import com.chinaweal.aiccs.crgs.transfor.sdk.XzxkWsBO;
import com.chinaweal.aiccs.crgs.transfor.service.OtNcaseDownloadLogService;
import com.chinaweal.aiccs.crgs.transfor.service.OtNpermitDownloadLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.aegis.databinding.AegisDatabinding;
import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 下载定时任务
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021/11/3 17:20
 **/
@Slf4j
@Component
public class DownloadSchedule {

    @Value("${ot.downloadPath}")
    private String downloadPath;

    @Value("${ot.download.caseUrl}")
    private String caseDownloadUrl;

    @Value("${ot.download.permitUrl}")
    private String permitDownloadUrl;

    @Value("${ot.eap_username}")
    private String userName;

    @Value("${ot.eap_password}")
    private String password;

    @Value("${ot.bakCseDownloadPath}")
    private String bakCseDownloadPath;

    @Value("${ot.bakPermitDownloadPath}")
    private String bakPermitDownloadPath;

    @Autowired
    private OtNcaseDownloadLogService otNcaseDownloadLogService;

    @Autowired
    private OtNpermitDownloadLogService otNpermitDownloadLogService;

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 行政处罚下载，2天一次
     *
     * @author lroyia
     * @since 2021年11月3日 17:31:44
     */
//    @Scheduled(cron = "${scheduling.cron.caseDownload}")
    public void caseDownload2() {
        HSSFWorkbook workbook = null;
        File saveDir = new File(downloadPath + File.separator + "ncase");
        if (!saveDir.exists()) saveDir.mkdirs();
        File[] files = saveDir.listFiles();
        long now = System.currentTimeMillis();
        long last;
        if (files != null && files.length > 0) {
            String name = "";
            for (File file : files) {
                String name1 = file.getName();
                if (name1.compareTo(name) > 0) {
                    name = name1;
                }
            }
            String timestamp = name.substring(0, name.lastIndexOf("."));
            last = Long.parseLong(timestamp);
        } else {
            last = now - (6000 * 60 * 24 * 2);
        }

        try {
            // 上报日期自
            java.sql.Date uploadDateFrom = new java.sql.Date(last);
            // 上报日期至
            java.sql.Date uploadDateto = new java.sql.Date(now);
            // 操作标识
            String oper = "";
            // 下载状态
            String downloadType = "0";
            ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
            factory.setServiceClass(XzcfWsBO.class);
            factory.setAddress(String.format(caseDownloadUrl, userName, password));
            factory.getServiceFactory().setDataBinding(new AegisDatabinding());
            XzcfWsBO service = (XzcfWsBO) factory.create();
            DataHandler dataHandler = service.downloadCreditInfoByXzcf(uploadDateFrom,
                    uploadDateto, oper, downloadType);
            InputStream is = dataHandler.getInputStream();
            workbook = new HSSFWorkbook(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (workbook == null) return;

        // 保存文件到本地路径
        File saveFile = new File(saveDir.getAbsolutePath() + File.separator + last + ".xls");
        try (FileOutputStream fileOutputStream = new FileOutputStream(saveFile)) {
            workbook.write(fileOutputStream);
            fileOutputStream.flush();
        } catch (IOException e) {
            log.error("下载行政处罚信息文件失败，当前时间戳：{}", last, e);
        }

        // 保存数据
        try {
            otNcaseDownloadLogService.saveDownloadData(saveFile);
        } catch (IOException e) {
            log.error("保存数据保存失败，{}", saveFile.getAbsolutePath());
        }

        // 上传ftp
        try {
            InputStream inputStream = new FileInputStream(saveFile);
            Boolean isSuccess = fileStorageService.writeFromStream(bakCseDownloadPath,saveFile.getName(),inputStream);
            if (isSuccess) { // 删除本地文件
//                saveFile.delete();
            } else {
                log.debug("上传文件到ftp失败{}", saveFile.getName());
            }
        } catch (FileNotFoundException e) {
            log.error("上传文件到ftp失败");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "${scheduling.cron.caseDownload}")
    public void caseDownloadTask() {
        caseDownload(null,null);
    }

    public List<OtNcaseDownloadLog> caseDownload(String start, String end) {
        List<OtNcaseDownloadLog> list = new ArrayList<>();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
        File saveDir = new File(bakCseDownloadPath);
        if (!saveDir.exists()) saveDir.mkdirs();
        List<String> files = fileStorageService.getFtpFileNames(bakCseDownloadPath);
        // 上报日期自
        String uploadDateFrom = "";
        // 上报日期至
        String uploadDateto = "";
        // 操作标识
        String oper = "";
        // 下载状态
        String downloadType = "0";
        if (files != null && files.size() > 0) {
            String name = "";
            for (String fileName : files) {
                String name1 = fileName;
                if (name1.compareTo(name) > 0) {
                    name = name1;
                }
            }
            uploadDateFrom = name.substring(0, name.lastIndexOf("."));
        } else {
            // 取当前前2天
            long nowL = System.currentTimeMillis();
            Date now = new Date(nowL);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DAY_OF_MONTH, -2);
            uploadDateFrom = sbf.format(calendar.getTime());
        }
        String returnStr = "";
        try {

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(sbf.parse(uploadDateFrom));
            calendar2.add(Calendar.DAY_OF_MONTH, 1);
            uploadDateto = sbf.format(calendar2.getTime());

            if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {
                uploadDateFrom = start;
                uploadDateto = end;
            } else {
                uploadDateFrom = uploadDateto;
            }

            //拼接xml请求,带有请求头
            String soapRequestData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:jog=\"http://joggle.bo.creditinfotransfer.datacollection.unieap.neusoft.com/\">\n" +
                    "   <soapenv:Header/>\n" +
                    "   <soapenv:Body>\n" +
                    "      <jog:downloadCreditInfoByXzcf>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg0>" + uploadDateFrom + "</jog:arg0>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg1>" + uploadDateto + "</jog:arg1>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg2 xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg3>" + downloadType + "</jog:arg3>\n" +
                    "      </jog:downloadCreditInfoByXzcf>\n" +
                    "   </soapenv:Body>\n" +
                    "</soapenv:Envelope>";
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost postMethod = new HttpPost(String.format(caseDownloadUrl, userName, password));
                postMethod.setHeader("Content-Type", "application/xml; charset=utf-8");
                postMethod.setEntity(new StringEntity(soapRequestData, StandardCharsets.UTF_8));

                CloseableHttpResponse response = client.execute(postMethod);
                int statusCode = response.getStatusLine().getStatusCode();
                String soapResponseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                //200说明正常返回数据
                if (statusCode == 200) {
                    log.info("{}异地流转行政处罚请求下载接口，返回结果：{}", uploadDateto, soapResponseData);
                    int z = soapResponseData.indexOf("<ns1:return>");
                    int j = soapResponseData.indexOf("</ns1:return>");
                    returnStr = soapResponseData.substring(z + "<ns1:return>".length(), j);
                } else {
                    log.info("{}异地流转行政处罚请求下载接口失败，状态值：{}", uploadDateto, statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(returnStr)) return null;
        byte[] bytes = Base64.getDecoder().decode(returnStr);
        // 保存文件到本地路径 /usr/crgs/tomcat/download/ncase
        File saveFile = new File(saveDir.getAbsolutePath() + File.separator + uploadDateto + ".xls");
        try (FileOutputStream fileOutputStream = new FileOutputStream(saveFile)) {
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        } catch (IOException e) {
            log.error("下载行政处罚信息文件失败，当前时间戳：{}", uploadDateto, e);
        }

        // 保存数据
        try {
            list = otNcaseDownloadLogService.saveDownloadData(saveFile);
        } catch (IOException e) {
            log.error("保存数据保存失败，{}", saveFile.getAbsolutePath());
        }

        // 上传ftp
        // /ot/case
//        try {
//            InputStream inputStream = new FileInputStream(saveFile);
//            Boolean isSuccess = fileStorageService.writeFromStream(bakCseDownloadPath,saveFile.getName(),inputStream);
//            if (isSuccess) { // 删除本地文件
//                saveFile.delete();
//            } else {
//                log.debug("上传文件到ftp失败{}", saveFile.getName());
//            }
//        } catch (FileNotFoundException e) {
//            log.error("上传文件到ftp失败");
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return list;
    }


    /**
     * 行政许可下载，2天一次
     *
     * @author lroyia
     * @since 2021年11月3日 17:31:50
     */
//    @Scheduled(cron = "${scheduling.cron.permitDownload}")
    public void permitDownload2() {
        HSSFWorkbook workbook = null;
        File saveDir = new File(downloadPath + File.separator + "npermit");
        if (!saveDir.exists()) saveDir.mkdirs();
        File[] files = saveDir.listFiles();
        long now = System.currentTimeMillis();
        long last;
        if (files != null && files.length > 0) {
            String name = "";
            for (File file : files) {
                String name1 = file.getName();
                if (name1.compareTo(name) > 0) {
                    name = name1;
                }
            }
            String timestamp = name.substring(0, name.lastIndexOf("."));
            last = Long.parseLong(timestamp);
        } else {
            last = now - (6000 * 60 * 24 * 2);
        }

        try {
            // 上报日期自
            java.sql.Date uploadDateFrom = new java.sql.Date(last);
            // 上报日期至
            java.sql.Date uploadDateto = new java.sql.Date(now);
            // 操作标识
            String oper = "";
            // 下载状态
            String downloadType = "0";
            ClientProxyFactoryBean factory = new ClientProxyFactoryBean();
            factory.setServiceClass(XzxkWsBO.class);
            factory.setAddress(String.format(caseDownloadUrl, userName, password));
            factory.getServiceFactory().setDataBinding(new AegisDatabinding());
            XzxkWsBO service = (XzxkWsBO) factory.create();
            DataHandler dataHandler = service.downloadCreditInfoByXzxk(uploadDateFrom,
                    uploadDateto, oper, downloadType);
            InputStream is = dataHandler.getInputStream();
            workbook = new HSSFWorkbook(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (workbook == null) return;

        // 保存文件到本地路径
        File saveFile = new File(saveDir.getAbsolutePath() + File.separator + last + ".xls");
        try (FileOutputStream fileOutputStream = new FileOutputStream(saveFile)) {
            workbook.write(fileOutputStream);
            fileOutputStream.flush();
        } catch (IOException e) {
            log.error("下载行政处罚信息文件失败，当前时间戳：{}", last, e);
        }

        // 保存数据
        try {
            otNpermitDownloadLogService.saveDownloadData(saveFile);
        } catch (IOException e) {
            log.error("保存数据保存失败，{}", saveFile.getAbsolutePath());
        }

        // 上传ftp
        try {
            InputStream inputStream = null;
            inputStream = new FileInputStream(saveFile);
            Boolean isSuccess = fileStorageService.writeFromStream(bakPermitDownloadPath,saveFile.getName(),inputStream);
            if (isSuccess) { // 删除本地文件
//                saveFile.delete();
            } else {
                log.debug("上传文件到ftp失败{}", saveFile.getName());
            }
        } catch (FileNotFoundException e) {
            log.error("上传文件到ftp失败");
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "${scheduling.cron.permitDownload}")
    public void permitDownloadTask() {
        permitDownload(null,null);
    }

    public List<OtNpermitDownloadLog> permitDownload(String start, String end) {
        List<OtNpermitDownloadLog> list = new ArrayList<>();
        SimpleDateFormat sbf = new SimpleDateFormat("yyyy-MM-dd");
        File saveDir = new File(bakPermitDownloadPath);
        if (!saveDir.exists()) saveDir.mkdirs();
        List<String> files = fileStorageService.getFtpFileNames(bakPermitDownloadPath);
        // 上报日期自
        String uploadDateFrom = "";
        // 上报日期至
        String uploadDateto = "";
        // 操作标识
        String oper = "";
        // 下载状态
        String downloadType = "0";
        if (files != null && files.size() > 0) {
            String name = "";
            for (String fileName : files) {
                String name1 = fileName;
                if (name1.compareTo(name) > 0) {
                    name = name1;
                }
            }
            uploadDateFrom = name.substring(0, name.lastIndexOf("."));
        } else {
            // 取当前前2天
            long nowL = System.currentTimeMillis();
            Date now = new Date(nowL);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            calendar.add(Calendar.DAY_OF_MONTH, -2);
            uploadDateFrom = sbf.format(calendar.getTime());
        }
        String returnStr = "";

        try {

            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(sbf.parse(uploadDateFrom));
            calendar2.add(Calendar.DAY_OF_MONTH, 1);
            uploadDateto = sbf.format(calendar2.getTime());

            if (StringUtils.isNotBlank(start) && StringUtils.isNotBlank(end)) {
                uploadDateFrom = start;
                uploadDateto = end;
            } else {
                uploadDateFrom = uploadDateto;
            }

            //拼接xml请求,带有请求头
            String soapRequestData = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:jog=\"http://joggle.bo.creditinfotransfer.datacollection.unieap.neusoft.com/\">\n" +
                    "   <soapenv:Header/>\n" +
                    "   <soapenv:Body>\n" +
                    "      <jog:downloadCreditInfoByXzxk>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg0>" + uploadDateFrom + "</jog:arg0>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg1>" + uploadDateto + "</jog:arg1>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg2 xsi:nil=\"true\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>\n" +
                    "         <!--Optional:-->\n" +
                    "         <jog:arg3>" + downloadType + "</jog:arg3>\n" +
                    "      </jog:downloadCreditInfoByXzxk>\n" +
                    "   </soapenv:Body>\n" +
                    "</soapenv:Envelope>";
            try (CloseableHttpClient client = HttpClients.createDefault()) {
                HttpPost postMethod = new HttpPost(String.format(permitDownloadUrl, userName, password));
                postMethod.setHeader("Content-Type", "application/xml; charset=utf-8");
                postMethod.setEntity(new StringEntity(soapRequestData, StandardCharsets.UTF_8));

                CloseableHttpResponse response = client.execute(postMethod);
                int statusCode = response.getStatusLine().getStatusCode();
                String soapResponseData = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                //200说明正常返回数据
                if (statusCode == 200) {
                    log.info("{}异地流转行政许可请求下载接口，返回结果：{}", uploadDateto, soapResponseData);
                    int z = soapResponseData.indexOf("<ns1:return>");
                    int j = soapResponseData.indexOf("</ns1:return>");
                    returnStr = soapResponseData.substring(z + "<ns1:return>".length(), j);
                } else {
                    log.info("{}异地流转行政许可请求下载接口失败，状态值：{}", uploadDateto, statusCode);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (StringUtils.isBlank(returnStr)) return null;
        byte[] bytes = Base64.getDecoder().decode(returnStr);
        // 保存文件到本地路径
        // /usr/crgs/tomcat/download/npermit
        File saveFile = new File(saveDir.getAbsolutePath() + File.separator + uploadDateto + ".xls");
        try (FileOutputStream fileOutputStream = new FileOutputStream(saveFile)) {
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
        } catch (IOException e) {
            log.error("下载行政处罚信息文件失败，当前时间戳：{}", uploadDateto, e);
        }

        // 保存数据
        try {
            list = otNpermitDownloadLogService.saveDownloadData(saveFile);
        } catch (IOException e) {
            log.error("保存数据保存失败，{}", saveFile.getAbsolutePath());
        }

        // 上传ftp
        // /ot/permit
//        try {
//            InputStream inputStream = new FileInputStream(saveFile);
//            Boolean isSuccess = fileStorageService.writeFromStream(bakPermitDownloadPath,saveFile.getName(),inputStream);
//            if (isSuccess) { // 删除本地文件
//                saveFile.delete();
//            } else {
//                log.debug("上传文件到ftp失败{}", saveFile.getName());
//            }
//        } catch (FileNotFoundException e) {
//            log.error("上传文件到ftp失败");
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return list;
    }

}
