package com.trs.project.timer;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
import com.trs.project.entity.BusinessInfo;
import com.trs.project.service.BusinessInfoService;
import com.trs.project.utils.SFTPUtils;
import com.trs.project.utils.TRSParser;
import com.trs.project.utils.ZipUtil;
import lombok.extern.slf4j.Slf4j;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTRotY;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Component
public class BusinessFtpTask {

    @Autowired
    private BusinessInfoService businessInfoService;

    @Autowired
    private BusinessTask businessTask;

    @Value("${ftp.fileURL}")
    private String fileUrl_config;

    @Value("${ftp.host}")
    private String host_config;

    @Value("${ftp.port}")
    private int port_config;

    @Value("${ftp.username}")
    private String username_config;

    @Value("${ftp.password}")
    private String password_config;

    @Value("${ftp.targetUrl}")
    private String targetUrl;

    public void saveOrUpdateFTP() throws Exception {

        String fileUrl = fileUrl_config+"/ftp/";
        ChannelSftp sftp = new ChannelSftp();
        SFTPUtils sftpUtils   =  new SFTPUtils(host_config, port_config, username_config, password_config);
        //获取文件列表
        Vector<?> listFiles = sftpUtils.listFiles(targetUrl, sftpUtils.sftp);
        List<Long> dateNumber = new ArrayList<Long>();
        for (Object listFile : listFiles) {
            log.info("文件列表："+listFile);
            String[] s = listFile.toString().split(" ");
            String fileNameData = s[s.length - 1];
            if(!fileNameData.equals(".") && !fileNameData.equals("..")){
                try {
                    dateNumber.add(Long.parseLong(fileNameData));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        Long max = Collections.max(dateNumber);
        targetUrl = targetUrl +"/"+max+"/";

        Vector<?> objects = sftpUtils.listFiles(targetUrl, sftpUtils.sftp);
        ArrayList<String> stringArrayList = new ArrayList<String>();
        ArrayList<String> stringArrayListDelete = new ArrayList<String>();
        for (Object object : objects) {
            String[] s = object.toString().split(" ");
            String fileName = s[s.length - 1];
            if(!fileName.equals(".") && !fileName.equals("..")){
                try {
                    System.out.println(fileName);
                    sftpUtils.download(targetUrl,fileName,fileUrl+fileName, sftpUtils.sftp);
                    //Java 解压zip
                    String newFilename = ZipUtil.unzipFile(fileUrl+fileName, fileUrl);
                    System.out.println(fileUrl+fileName);
                    stringArrayListDelete.add(fileUrl+fileName);
                    stringArrayList.add(fileUrl+newFilename);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
        sftpUtils.disconnect(sftpUtils.sftp, sftpUtils.sshSession, sftpUtils.channel);
        QueryWrapper<BusinessInfo> queryWrapper = new QueryWrapper<BusinessInfo>();
        queryWrapper.eq("BUSINESS_TYPE",1);
        List<BusinessInfo> list1 = businessInfoService.list(queryWrapper);
        QueryWrapper<BusinessInfo> queryWrapperFtp = new QueryWrapper<BusinessInfo>();
        queryWrapperFtp.eq("BUSINESS_TYPE",2);
        List<BusinessInfo> listFtp = businessInfoService.list(queryWrapperFtp);
        list1.addAll(listFtp);
        Map<String,String> BusinessInfoMap = new HashMap<String,String>();
        for (BusinessInfo businessInfo : list1) {
            BusinessInfoMap.put(businessInfo.getName(),businessInfo.getName());
        }
        for (String url : stringArrayList) {
            List<Map<String,Object>> list = TRSParser.readFile(
                    FileUtil.newFile(url),"GBK");

            for (Map<String, Object> map : list) {
                //log.info(map.toString());
                BusinessInfo businessInfo = new BusinessInfo();
                businessInfo.setId(map.get("eid").toString());
                businessInfo.setName(map.get("entname").toString());
                //查询5000条数据当中有没有当前数据如果跳出当前循环
                String isMap = BusinessInfoMap.get(businessInfo.getName());
                if(!ObjectUtils.isEmpty(isMap)){
                    log.info("跳出循环");
                    continue;
                }
                businessInfo.setOperName(map.get("legal_person").toString());
                businessInfo.setRegistCapi(map.get("regcap").toString()+" 万人民币");
                try {
                    String esdate = map.get("esdate").toString();
                    String esdateNew = esdate.replace("/", "-").split(" ")[0];
                    businessInfo.setStartDate(esdateNew);
                }catch (Exception e){
                    e.printStackTrace();
                    businessInfo.setStartDate(map.get("esdate").toString());
                }
                businessInfo.setCreditNo(map.get("credit_code").toString());
                businessInfo.setStatus(map.get("entstatus_name").toString());
                businessInfo.setNewStatus(map.get("entstatus_name").toString());
                businessInfo.setRegNo(map.get("regno").toString());
                businessInfo.setEconKind(map.get("enttype_name_char").toString());
                try {
                    String apprdate = map.get("apprdate").toString();
                    String apprdateNew = apprdate.replace("/", "-").split(" ")[0];
                    businessInfo.setCheckDate(apprdateNew);
                }catch (Exception e){
                    businessInfo.setCheckDate(map.get("apprdate").toString());
                    e.printStackTrace();
                }
                businessInfo.setIndustry(map.get("industryco_name").toString());
                businessInfo.setBelongOrg(map.get("regorg_name").toString());
                businessInfo.setBusinessType("3");
                businessInfo.setSocialStaffNum(map.get("endo_ins_num").toString());
                businessInfo.setManagementLocation(map.get("dom").toString());
                businessInfo.setSocialStaffNum(map.get("endo_ins_num").toString());
                businessInfo.setScope(map.get("opscope").toString());
                try {
                    String opfrom = map.get("opfrom").toString();
                    String opfromNew = opfrom.replace("/", "-").split(" ")[0];
                    businessInfo.setTermStart(opfromNew);
                }catch (Exception e){
                    businessInfo.setTermStart(map.get("opfrom").toString());
                    e.printStackTrace();
                }
                try {
                    String opto = map.get("opto").toString();
                    String optoNew = opto.replace("/", "-").split(" ")[0];
                    businessInfo.setTermEnd(optoNew);
                }catch (Exception e){
                    businessInfo.setTermEnd(map.get("opto").toString());
                    e.printStackTrace();
                }
                QueryWrapper<BusinessInfo> queryWrapperInfo = new QueryWrapper<BusinessInfo>();
                queryWrapperInfo.eq("id",businessInfo.getId());
                businessInfo.setSavetime(LocalDateTime.now());
                boolean save = businessInfoService.saveOrUpdate(businessInfo,queryWrapperInfo);
                log.info("保存状态"+save);
            }
        }
        try {
            Path path = Paths.get(fileUrl_config+"/ftp/");
            Files.walkFileTree(path,
                    new SimpleFileVisitor<Path>() {
                        // 先去遍历删除文件
                        @Override
                        public FileVisitResult visitFile(Path file,
                                                         BasicFileAttributes attrs) throws IOException {
                            Files.delete(file);
                            System.out.printf("文件被删除 : %s%n", file);
                            return FileVisitResult.CONTINUE;
                        }
                    }
            );
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
