package com.tax.file.service.async.down;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tax.file.constants.CommonConstants;
import com.tax.file.constants.FileConstants;
import com.tax.file.model.*;
import com.tax.file.model.invoice.InvoiceFileModel;
import com.tax.file.service.api.FileTokenService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.utils.NationDic;
import com.tax.file.utils.NationUtil;
import com.yxcheng.tax.fs.minio.service.MinioTemplate;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.constants.RedisContants;
import com.yxcheng.token.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class AbstractFileDownService extends DataFileDownService{

    protected static final Logger logger = LoggerFactory.getLogger(AbstractFileDownService.class);

    @Autowired
    private MinioTemplate minioTemplate;
    @Autowired
    protected RedisService redisService;
    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    private FileTokenService fileTokenService;

    protected boolean doDownLoad(String uuidFlag, DownFileModel model) {
        boolean isFinish = false;

        Map<String, TkFile> tkFileMap = model.getTkFileMap();
        TkTaxUser taxUser = model.getTaxUser();
        String taxno = taxUser.getTaxno();


        List<InvoiceFileModel> invoiceFileList = transInvoiceFileList(model);
        for(InvoiceFileModel invoiceFile:invoiceFileList) {
            if(tkFileMap.containsKey(invoiceFile.getFileMd5())) {
                TkFile tkFile = tkFileMap.get(invoiceFile.getFileMd5());
                tkFile.setApplyDate(invoiceFile.getApplyDate());
                tkFile.setDownloadTaxStatus(invoiceFile.getProcessStatus());
                //文件在局端已经处理完成、文件处理完成
                if(StringUtil.isNotEmpty(invoiceFile.getProcessStatus()) && invoiceFile.getProcessStatus().equals("1")) {
                    boolean downloadFlag = true;
                    //不符合下载
                    if("1".equals(invoiceFile.getNationUrlStatus())){
                        tkFileDownFinishStatus(tkFile);
                        tkFile.setDownDate(DateUtils.getDate());
                        tkFile.setFileName(invoiceFile.getNationUrl());
                    }else if(invoiceFile.getNationUrl().equals(NationDic.fileDisable)) {
                        //如果是当月数据，已过期的，直接返回
                        if(tkFile.getFileDataType().equals("0")) {
                            tkFile.setDownStatus(NationDic.APPLY_STATUS_YES);
                            tkFile.setResponseStatus(NationDic.RESPONSE_STATUS_PAST);
                            tkFile.setDownDate(DateUtils.getDate());
                        } else {
                            tkFile.setDownStatus("2");
                        }
                        tkFile.setFileName(invoiceFile.getNationUrl());
                        tkFile.setErrorCode(DownFileInfoModel.BEYOND_TAX_NATION_DAY);
                    } else {
                        String fileName = NationDic.transferFileName(invoiceFile.getNationUrl());
                        tkFile.setFileName(fileName);
                        tkFile.setToken(model.getContext().getToken());

                        //下载并上传文件服务器
                        if(fileName.contains(",")){
                            //有多个文件
                            downloadFlag = downMultiFile(uuidFlag, taxUser, tkFile, invoiceFile);
                        }else{
                            downloadFlag = downSingleFile(uuidFlag, taxUser, tkFile, invoiceFile);
                        }
                        if(downloadFlag) {
                            tkFile.setResponseStatus("0");
                            tkFile.setDownDate(DateUtils.getDate());
                        }
                        tkFile.setFileName(StringUtil.getShortLog(fileName, 3000));
                        logger.info(uuidFlag + " taxno is " + taxno + ", doDownLoad downloadFlag is : " + downloadFlag
                                + ", tkFile errorCode is " + tkFile.getErrorCode()
                                + ", tkFile fileName is " + fileName);
                    }
                    if(downloadFlag) {
                        tkFile.setUpdateDate(DateUtils.getDate());
                        tkFileService.updateByPrimaryKeySelective(tkFile);
                        //同一日期段只取第一条记录
                        tkFileMap.remove(tkFile.getFileMd5());
                    } else {
                        saveErrorFile(tkFile, tkFileMap, "1");
                    }
                } else {
                    saveErrorFile(tkFile, tkFileMap, "2");
                    //增加长期处理中降频逻辑
                    logger.info(uuidFlag + " taxno is " + taxno + ", doDownLoad info is : " + invoiceFile.getLogInfo());
                }
            } else {
                if(FileConstants.viewFlag.equals("0")) {
                    logger.info(uuidFlag + " taxno is " + taxno + ", doDownLoad info is : " + invoiceFile.getLogInfo() + " not in download list.");
                }
            }

        }
        //清理申请月限制
        clearOverMonth(taxUser.getUserName(), invoiceFileList);
        return isFinish;
    }

    public void clearOverMonth(String userName, List<InvoiceFileModel> invoiceFileList) {
        for(InvoiceFileModel invoiceFile:invoiceFileList) {
            if (StringUtil.isNotEmpty(invoiceFile.getProcessStatus()) && invoiceFile.getProcessStatus().equals("1")) {
                //检测当月和下月
                checkOverMonth(userName, invoiceFile.getTaxno(), invoiceFile.getInvType(), invoiceFile.getInvSpec(), invoiceFile.getFileMonth());
                String fileMonth = DateUtils.getPastMonth(invoiceFile.getFileMonth(), -1);
                checkOverMonth(userName, invoiceFile.getTaxno(), invoiceFile.getInvType(), invoiceFile.getInvSpec(), fileMonth);
            }
        }
    }

    public void checkOverMonth(String userName, String taxno, String invType, String invSpec, String fileMonth) {

        if(redisService.exists(RedisContants.getLimitName(RedisContants.FILE_APPLY_ALARM, userName, taxno) + invType + invSpec + fileMonth)) {
            if(redisService.exists(RedisContants.getLimitName(RedisContants.FILE_APPLY_ALARM, userName, taxno))) {
                redisService.del(RedisContants.getLimitName(RedisContants.FILE_APPLY_ALARM, userName, taxno));
            }
            redisService.del(RedisContants.getLimitName(RedisContants.FILE_APPLY_ALARM, userName, taxno) + invType + invSpec + fileMonth);
        }
    }

    public void saveErrorFile(TkFile tkFile, Map<String, TkFile> tkFileMap, String errorType) {
        int downloadCount = getRetryNumberRedis(tkFile.getUserName(), tkFile.getTaxno(), errorType, tkFile.getFileMd5());
        tkFile.setDownCount(++downloadCount);
        if (tkFile.getDownCount() == 3) {
            tkFileService.saveErrorFileInfo(tkFile, errorType);
            delRetryNumberRedis(tkFile.getUserName(), tkFile.getTaxno(), errorType, tkFile.getFileMd5());
        } else {
            setRetryNumberRedis(tkFile.getUserName(), tkFile.getTaxno(), errorType, tkFile.getFileMd5(), tkFile.getDownCount());
        }
        tkFileMap.remove(tkFile.getFileMd5());
    }

    private List<InvoiceFileModel> transInvoiceFileList(DownFileModel model) {
        List<InvoiceFileModel> invoiceFileModelList = Lists.newArrayList();
        TkTaxUser taxUser = model.getTaxUser();
        JSONArray jsonArray = model.getInvList();
        for(int i =0;i<jsonArray.size();i++){
            InvoiceFileModel invoiceFileModel = new InvoiceFileModel();
            JSONArray array = jsonArray.getJSONArray(i);
            /** 2 申请日期=3 发票类型= 4 开票开始日期= 5 开票结束日期=6 进销项=7 状态值=8 url*/
            Date applyDate = array.getDate(2);
//            String invType = NationDic.transfer(array.getString(3));
            String invType = array.getString(0);
            if(StringUtil.isNotEmpty(invType) && invType.split("=").length==3) {
                invType = invType.split("=")[2];
            } else {
                invType = NationDic.transfer(invType);
            }
            Date invDateStart = array.getDate(4);
            Date invDateEnd = array.getDate(5);
            String invSpec = NationDic.transfer(array.getString(6));
            String processStatus = NationDic.transfer(array.getString(7));
            String nationUrlStatus = NationDic.transfer(array.getString(8));
            String nationUrl = array.getString(8);

            invoiceFileModel.setTaxno(taxUser.getTaxno());
            invoiceFileModel.setApplyDate(applyDate);
            invoiceFileModel.setInvType(invType);
            invoiceFileModel.setInvTypeCn(array.getString(3));
            invoiceFileModel.setInvDateStart(invDateStart);
            invoiceFileModel.setInvDateEnd(invDateEnd);
            invoiceFileModel.setInvSpec(invSpec);
            invoiceFileModel.setProcessStatus(processStatus);
            invoiceFileModel.setProcessStatusCn(array.getString(7));
            invoiceFileModel.setNationUrlStatus(nationUrlStatus);
            invoiceFileModel.setNationUrlStatusCn(array.getString(8));
            invoiceFileModel.setNationUrl(nationUrl);
            String beMonth = DateUtils.getMonth(invDateStart);
            invoiceFileModel.setFileMonth(beMonth);
            invoiceFileModel.setFileMd5(MD5Util.MD5Encode(taxUser.getTaxno() + invSpec + invType
                    + DateUtils.date2Str(invDateStart, new SimpleDateFormat("yyyy-MM-dd")) + DateUtils.date2Str(invDateEnd, new SimpleDateFormat("yyyy-MM-dd"))));

            invoiceFileModelList.add(invoiceFileModel);
        }
        return invoiceFileModelList;
    }

    private boolean downSingleFile(String uuidFlag, TkTaxUser taxUser, TkFile tkFile, InvoiceFileModel invoiceFile) {
        try {
            String fullFileName = tkFile.getFileName();
            String[] fullFileNameArr = tkFile.getFileName().split("\\*");
            String firstName = fullFileNameArr[0];
            String[] firstNameArr = firstName.split("=");
            String fileName = firstNameArr[0];
            String fileNameMd5 = firstNameArr[1];

            TkFile query = new TkFile();
            BeanUtils.copyProperties(tkFile,query);
            query.setFileName(fullFileName);
            JSONObject jsonObject = fileDownload(uuidFlag, taxUser, query);
            if(jsonObject!=null) {
                if(checkIsOverDate24Hour(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                    tkFile.setDownStatus("2");
                    tkFile.setErrorCode(DownFileInfoModel.DOWNLOAD_OVER_24);
                    tkFile.setFileName(DownFileInfoModel.DOWNLOAD_OVER_24_CN);
                } else if(checkIsOverDate(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                    tkFile.setDownStatus("2");
                    tkFile.setErrorCode(DownFileInfoModel.OVER_DATE);
                    tkFile.setFileName(DownFileInfoModel.OVER_DATE_CN);
                } else if(checkIsTokenOver(uuidFlag, taxUser.getTaxno(), jsonObject)) {
                    //token过期直接跳出
                    fileTokenService.noticeGetNewToken(uuidFlag, taxUser);
                    return false;
                } else if(checkIsError(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                    //未知异常直接返回
                    return false;
                } else {
                    DownFileInfoModel downFileInfoModel = NationUtil.downFile(uuidFlag, jsonObject, query);
                    File file = new File(downFileInfoModel.getPath());
                    if(isFileComplete(file, fileNameMd5, fileName)){
                        tkFile.setFileNum(1);
//                        backupTaxnoFile(uuidFlag, tkFile, downFileInfoModel);
                        boolean uploadFlag = upLoadFileSystem(uuidFlag, tkFile, downFileInfoModel);
                        if(uploadFlag) {
                            //删除主文件
                            deleteTaxnoFileList(uuidFlag, tkFile, downFileInfoModel.getPath());
                        }
                        return uploadFlag;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(uuidFlag + " taxno is " + invoiceFile.getTaxno() + " downSingleFile is error!" +e.getMessage());
        }
        return false;
    }

    public void backupTaxnoFile(String uuidFlag, TkFile tkFile, DownFileInfoModel downFileInfoModel) {
        if(FileConstants.backupFlag.equals("0")) {
            boolean bakFlag = false;
            String bakFilePath = FileUtils.fileBakPath(FileConstants.nationFilePath, tkFile.getZoneCode(), tkFile.getUserName(), tkFile.getTaxno()) + ZipDecompress.getOriginName(downFileInfoModel.getPath()) + ".zip";
            try {
                bakFlag = FileUtils.copyFile(downFileInfoModel.getPath(), bakFilePath, true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件被复制到备份文件夹" + getGenNote(bakFlag) + "：" + bakFilePath);
        }
    }

    public void deleteTaxnoFile(String uuidFlag, TkFile tkFile, String filePath) {
        if(FileConstants.deleteFlag.equals("0")) {
            boolean deleteFlag = false;
            try {
                deleteFlag = FileUtils.deleteFile(filePath);
            } catch (Exception e) {
                e.printStackTrace();
            }
            logger.info(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件删除" + getGenNote(deleteFlag) + "：" + filePath);
        }
    }

    public void deleteTaxnoFileList(String uuidFlag, TkFile tkFile, String filePath) {
        if(FileConstants.deleteFlag.equals("0")) {
            boolean deleteFlag = false;
            try {
                filePath = filePath.substring(0, filePath.lastIndexOf("/"));
                logger.info(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件删除开始：" + filePath);
                File targetFile = new File(filePath);
                File[] zipFileList = targetFile.listFiles();
                int fileNum = 0;
                for(File zipFile:zipFileList) {
                    deleteFlag = zipFile.delete();
                    fileNum++;
                    logger.info(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件删除" + getGenNote(deleteFlag) + "：" + zipFile.getAbsolutePath());
                }
                logger.info(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件删除结束：" + filePath + ",数量是：" + fileNum);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(uuidFlag + ">>>" + tkFile.getTaxno() + ">>>文件删除error：" + e.getMessage());
            }
        }
    }

    private void tkFileDownFinishStatus(TkFile tkFile){
        tkFile.setApplyStatus("1");
        tkFile.setDownStatus("1");
        tkFile.setResponseStatus("0");
        tkFile.setDownCount(0);
        tkFile.setErrorCode("0");
        tkFile.setExcelImportCount(0);
    }

    public boolean upLoadFileSystem(String uuidFlag, TkFile tkFile, DownFileInfoModel downFileInfoModel) {
        String status = downFileInfoModel.getStatus();
        if(DownFileInfoModel.SUCCESS.equals(status)) {
            String fileKey = getFileKeyPath(tkFile) + UUIDGenerator.generate() + ".zip";
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(downFileInfoModel.getPath());

                //兼容b的桶前缀
                String bucketName = CommonConstants.BUCKET_NAME;
                logger.info(uuidFlag + " taxno is " + tkFile.getTaxno() + ",upLoadFileSystem is <<<start>>>!" + downFileInfoModel.getPath() + "==>" + minioTemplate.getEndpoint() + bucketName + FileConstants.systemName.toLowerCase());
                minioTemplate.putObject(bucketName + FileConstants.systemName.toLowerCase(), fileKey, fis);
                String fileSysUrl = minioTemplate.getObjectURL(bucketName + FileConstants.systemName.toLowerCase(),
                         fileKey, CommonConstants.EXPIRES);
                if(StringUtil.isNotEmpty(fileSysUrl)) {
                    fileSysUrl = fileSysUrl.split("\\?")[0];
                    fileSysUrl = fileSysUrl.replace(minioTemplate.getEndpoint(), minioTemplate.getDownEndpoint());
                    if(tkFile.getUserName().equals("qixiangyun")) {
                        fileSysUrl = fileSysUrl.replace("file.taxservices.cn", "qxy.taxservices.cn");
                    }
                }
                tkFile.setFileKey(fileKey);
                tkFile.setUploadTime(DateUtils.getDate());
                tkFile.setUrl(fileSysUrl);
                tkFile.setIsHasData("1");
                tkFileDownFinishStatus(tkFile);
                logger.info(uuidFlag + " taxno is " + tkFile.getTaxno() + ",upLoadFileSystem is <<<success>>>!" + downFileInfoModel.getPath() + "==>" + fileKey);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                //监控minio异常计数
                timesLimitStrategy.addTime(RedisContants.FILE_DOWN_MINIO_ERROR_COUNT,20*60, 20);
                logger.error(uuidFlag + " taxno is " + tkFile.getTaxno() + ",upLoadFileSystem:" +e.getMessage());
            } finally {
                if(fis!=null){
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                        logger.error(uuidFlag + " taxno is " + tkFile.getTaxno() + ",upLoadFileSystem IOException:" + e.getMessage());
                    }
                }
            }
        }
        return false;
    }

    private boolean downMultiFile(String uuidFlag, TkTaxUser taxUser, TkFile tkFile, InvoiceFileModel invoiceFile) {
        boolean success = true;
        String fileDPath = null;
        List<TkFileSegment> segmentList = getFileSegmentList(uuidFlag, tkFile);
        try {
            for(TkFileSegment fileSegment:segmentList) {
                fileDPath = fileSegment.getPath();
                if(fileSegment.getIsComplete().equals("1")) {
                    continue;
                }
                TkFile query = new TkFile();
                BeanUtils.copyProperties(tkFile,query);
                query.setFileName(fileSegment.getFileName());
                JSONObject jsonObject = fileDownload(uuidFlag, taxUser, query);

                if(jsonObject == null) {
                    success = false;
                    continue;
                } else {
                    if(checkIsOverDate24Hour(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                        tkFile.setDownStatus("2");
                        tkFile.setErrorCode(DownFileInfoModel.DOWNLOAD_OVER_24);
                        tkFile.setFileName(DownFileInfoModel.DOWNLOAD_OVER_24_CN);
                        break;
                    } else if(checkIsOverDate(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                        tkFile.setDownStatus("2");
                        tkFile.setErrorCode(DownFileInfoModel.OVER_DATE);
                        tkFile.setFileName(DownFileInfoModel.OVER_DATE_CN);
                        break;
                    } else if(checkIsTokenOver(uuidFlag, taxUser.getTaxno(), jsonObject)) {
                        //token过期直接跳出
                        fileTokenService.noticeGetNewToken(uuidFlag, taxUser);
                        success = false;
                        break;
                    } else if(checkIsError(uuidFlag, tkFile.getTaxno(), jsonObject)) {
                        success = false;
                    } else {
                        String[] fileNamed = fileSegment.getFileName().split("\\*");
                        String[] fileNameMd5 = fileNamed[0].split("=");
                        String fileName = fileNameMd5[0];
                        String Md5 = fileNameMd5[1];

                        String segFilePath = NationUtil.downToNative2(jsonObject, fileDPath, getFullName(fileName));
                        //判断文件是否是完好的
                        File segFile = new File(segFilePath);
                        if(segFile.exists() && isFileComplete(segFile,Md5,fileName)){
                            updateFileSegment(fileSegment, (int)segFile.length());
                        }else {
                            segFile.delete();
                            success = false;
                        }
                    }
                }
            }
            if(success){
                DownFileInfoModel downFileInfoModel = NationUtil.unZipVolumeFile(uuidFlag, fileDPath, tkFile);
                tkFile.setFileNum(segmentList.size());
//                backupTaxnoFile(uuidFlag, tkFile, downFileInfoModel);
                boolean uploadFlag = upLoadFileSystem(uuidFlag, tkFile, downFileInfoModel);
                if(uploadFlag) {
                    deleteTaxnoFileList(uuidFlag, tkFile, downFileInfoModel.getPath());
                }
                return uploadFlag;
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
            logger.error(uuidFlag + " taxno is " + invoiceFile.getTaxno() + " downMultiFile is error!" +e.getMessage());
        }
        return success;
    }


    public boolean isFileComplete(File file, String Md5,String fileName){
        boolean isComplete = false;
        if(file.exists()){
            //123:超过文件允许下载的次数，不能下载！
            //134:超过文件24小时内允许下载的次数，不能下载
            //7530:一个空的xls压缩包大小
            isComplete =  (file.length()<500)?false:true;
        }
        return isComplete;
    }

    private String getFullName(String fileName) {
        int index = fileName.lastIndexOf("/");
        return fileName.substring(index + 1);
    }

    private String getFileKeyPath(TkFile tkFile){
        String splitChar = "/";
        String dfStr = DateUtils.getDataString(DateUtils.date_sdf_s);
        dfStr = dfStr + tkFile.getUserName()
                + splitChar + tkFile.getTaxno()
                + splitChar + tkFile.getInvSpec()
                + splitChar + tkFile.getInvType()
                + splitChar + DateUtils.date2Str(tkFile.getInvDateEnd(), DateUtils.yyyyMMdd)
                + splitChar;
        return dfStr;
    }

    private boolean checkIsError(String uuidFlag, String taxno, JSONObject jsonObject) {
        boolean checkFlag = false;
        String fileStr = jsonObject.getString("file");
        try {
            String resultStr = new String(Base64Util.decode(fileStr));
            if(StringUtil.isNotEmpty(resultStr) && resultStr.contains("jQuery")) {
                checkFlag = true;
                logger.info(uuidFlag + " taxno is " + taxno + " checkIsError " + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " taxno is " + taxno + " the checkIsError error is " + e.getMessage());
        }
        return checkFlag;
    }

    private boolean checkIsOverDate(String uuidFlag, String taxno, JSONObject jsonObject) {
        boolean checkFlag = false;
        String fileStr = jsonObject.getString("file");
        try {
            String resultStr = new String(Base64Util.decode(fileStr));
            if(StringUtil.isNotEmpty(resultStr) && resultStr.contains("400001")
                    && (resultStr.contains("超过文件允许下载的次数") || resultStr.contains("文件服务器异常"))) {
                checkFlag = true;
                logger.info(uuidFlag + " taxno is " + taxno + " checkIsOverDate " + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " taxno is " + taxno + " the checkIsOverDate error is " + e.getMessage());
        }
        return checkFlag;
    }

    private boolean checkIsOverDate24Hour(String uuidFlag, String taxno, JSONObject jsonObject) {
        boolean checkFlag = false;
        String fileStr = jsonObject.getString("file");
        try {
            String resultStr = new String(Base64Util.decode(fileStr));
            if(StringUtil.isNotEmpty(resultStr) && resultStr.contains("400001") && resultStr.contains("24小时")) {
                checkFlag = true;
                logger.info(uuidFlag  + " taxno is " + taxno + " checkIsOverDate24Hour " + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " taxno is " + taxno + " the checkIsOverDate24Hour error is " + e.getMessage());
        }
        return checkFlag;
    }

    private boolean checkIsTokenOver(String uuidFlag, String taxno, JSONObject jsonObject) {
        boolean checkFlag = false;
        String fileStr = jsonObject.getString("file");
        try {
            String resultStr = new String(Base64Util.decode(fileStr));
            if(StringUtil.isNotEmpty(resultStr) && resultStr.contains("w4000000")) {
                checkFlag = true;
                logger.info(uuidFlag + " taxno is " + taxno + " checkIsTokenOver " + resultStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info(uuidFlag + " taxno is " + taxno + " the checkIsTokenOver error is " + e.getMessage());
        }
        return checkFlag;
    }

    public int getRetryNumberRedis(String userName, String taxno, String errorType, String fileMd5) {
        int retryNum = 0;
        String retryNumStr = redisService.get(getDownloadRetryName(userName, taxno, errorType, fileMd5));
        if (StringUtil.isNotEmpty(retryNumStr)) {
            retryNum = Integer.parseInt(retryNumStr);
        }
        return retryNum;
    }

    public void setRetryNumberRedis(String userName, String taxno, String errorType, String fileMd5, int retryNum) {
        redisService.set(getDownloadRetryName(userName, taxno, errorType, fileMd5), String.valueOf(retryNum), 60 * 60);
    }

    public void delRetryNumberRedis(String userName, String taxno, String errorType, String fileMd5) {
        if(redisService.exists(getDownloadRetryName(userName, taxno, errorType, fileMd5))) {
            redisService.del(getDownloadRetryName(userName, taxno, errorType, fileMd5));
        }
    }

    public String getDownloadRetryName(String userName, String taxno, String errorType, String fileMd5) {
        return "download:retry:" + userName + ":" + taxno + ":" + errorType + ":" + fileMd5;
    }

    public List<TkFileSegment> getFileSegmentList(String uuidFlag, TkFile tkFile) {
        String fileDPath = FileUtils.filePath(FileConstants.nationMultiFilePath, tkFile.getZoneCode(), tkFile.getUserName(), tkFile.getTaxno()) + System.nanoTime();
        List<TkFileSegment> segments = Lists.newArrayList();

        TkFileSegmentExample segmentExample = new TkFileSegmentExample();
        segmentExample.createCriteria().andTaxnoEqualTo(tkFile.getTaxno())
                .andUserNameEqualTo(tkFile.getUserName())
                .andFileMd5EqualTo(tkFile.getFileMd5())
                .andApplyDateEqualTo(tkFile.getApplyDate());
        int segmentNum = tkFileSegmentService.countByExample(segmentExample);

        if(segmentNum==0){
            String[] fileNamea = tkFile.getFileName().split("\\*");
            String[] fileNames = fileNamea[0].split(", ");
            String lastName = fileNamea[1];
            for(int i=1;i<= fileNames.length;i++) {
                String fileNamed = fileNames[i - 1];
                String fullFileName = fileNamed + "*" + lastName;
                segments.add(assembleTkTFileSegment(tkFile, fullFileName, fileDPath));
            }
            insertSegmentList(segments);
        }
        List<TkFileSegment> segmentList = tkFileSegmentService.selectByExample(segmentExample);
        logger.info(uuidFlag + " taxno is " + tkFile.getTaxno() + " the segments number is " + segmentList.size());
        return segmentList;
    }

    public void updateFileSegment(TkFileSegment fileSegment, int fileLength) {
        fileSegment.setIsComplete("1");
        fileSegment.setSize(fileLength);
        fileSegment.setUpdateDate(DateUtils.getDate());
        tkFileSegmentService.updateByPrimaryKey(fileSegment);
    }

    public String getGenNote(boolean genFlag) {
        if (genFlag) {
            return "成功";
        } else {
            return "失败";
        }
    }

    public static void main(String[] args) {
        String splitChar = "/";
        String filePath = "D:/testfie/72680472757914225/91511900709136415P-20220308194571101-202006-销项票-增值税普通发票（电子）-complate.zip";
        filePath = filePath.substring(0, filePath.lastIndexOf("/"));
//        String filePath = DateUtils.getDataString(DateUtils.date_sdf_s);
        System.out.println(filePath);

//        List<File> zipFileList = Lists.newArrayList();;
        File targetFile = new File(filePath);
        File[] zipFileList = targetFile.listFiles();
//        targetFile.listFiles(new FileFilter(){
//            public boolean accept(File file){
//                zipFileList.add(file);
//                return true;
//            }
//        });
        for(File zipFile:zipFileList) {
            System.out.println(zipFile.getAbsolutePath());
            zipFile.delete();
        }
    }
}