package com.jiayue.ipp.idp.service.an;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jiayue.ipp.common.data.entity.an.ParsingChannel;
import com.jiayue.ipp.common.data.entity.an.ParsingLog;
import com.jiayue.ipp.common.data.entity.an.ParsingUrl;
import com.jiayue.ipp.idp.dto.ParsingConstant;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ftp通信业务层
 *
 * @author tl
 * @date 2022-05-11 09:51:21
 */
@AllArgsConstructor
@Slf4j
@Service
@Transactional
public class DownloadService {

    private final ParsingUrlService parsingUrlService;

    private final ParsingFileService parsingFileService;

    private final ParsingLogService parsingLogService;

    /**
     * 解析
     *
     * @param parsingChannel
     */
    public void parsing(ParsingChannel parsingChannel) {

        //过滤出当前解析通道下在使用的《 解析路径 》
        List<ParsingUrl> parsingUrls = parsingUrlService.list(Wrappers.lambdaQuery(ParsingUrl.class).eq(ParsingUrl::getCId, parsingChannel.getId()).eq(ParsingUrl::getUrlStatus, "1"));
        String dateDir = DateFormatUtils.format(new Date(), "yyyyMMdd");
        String dayStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        //遍历解析路径，对文件进行解析
        for (ParsingUrl parsingUrl : parsingUrls) {

            String failDir = parsingUrl.getUrl() + File.separator + "fail" + File.separator + dateDir;

            String success = parsingUrl.getUrl() + File.separator + "success" + File.separator + dateDir;

            String path = parsingUrl.getUrl() + File.separator + "new";

            File dirFile = new File(path);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            File[] files = dirFile.listFiles();
            log.info("扫描路径：{}，文件数：{}",path,files.length);
            //遍历文件
            for (File file : files) {
                String fileName = file.getName();
                ParsingLog parsingLog = new ParsingLog();
                parsingLog.setFileName(fileName);
                parsingLog.setStationCode(parsingUrl.getStationCode());
                parsingLog.setParsingTime(new Date());

                if (!fileName.contains(dayStr)) {
                    file.delete();
                    log.warn(fileName + "不是当天的文件，删除！");
                    break;
                }

                //定义解析的类型，默认为错误（未知），成功后为文件类型，也会作为存储目录名
                String type = parsingFileService.parsingFile(file, parsingUrl);

                if (!type.startsWith(ParsingConstant.FAIL)) {

                    try {
                        File file1 = new File(success + File.separator + fileName);
                        if(file1.exists()){
                            file1.delete();
                        }
                        FileUtils.moveFile(file, new File(success + File.separator + fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    parsingLog.setParsingFileStatus("1");
                    parsingLog.setFileType(type);
                } else {
                    try {
                        File file1 = new File(failDir + File.separator + fileName);
                        if(file1.exists()){
                            file1.delete();
                        }
                        FileUtils.moveFile(file, new File(failDir + File.separator + fileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    parsingLog.setParsingFileStatus("0");
                    //失败情况下会返回失败信息
                    parsingLog.setParsingDescribe(type);
                }
                parsingLogService.save(parsingLog);
            }
        }


        log.info("解析执行完成", parsingChannel.getChannelName());

    }

}
