package com.dxhy.core.service.filemigration;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.dxhy.api.model.sign.TDxInvoiceImg;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dxhy.common.constant.DbConstant;
import com.dxhy.common.datasource.config.DynamicContextHolder;
import com.dxhy.common.utils.Aops;
import com.dxhy.core.dao.CoreFileMigrationDao;
import com.dxhy.oss.config.OssReturnConfig;
import com.dxhy.oss.model.FileModel;
import com.dxhy.oss.service.FileService;
import com.dxhy.oss.service.FtpService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @author jiaohongyang（焦红阳）
 * @date 2021-01-05
 */
@Service("fileMigrationService")
@Slf4j
public class FileMigrationServiceImpl implements FileMigrationService {
    @Resource
    private CoreFileMigrationDao fileMigrationDao;
    @Resource
    private FtpService ftpService;
    @Resource
    private FileService fileService;
    private static final int MAX_SIZE = 500;

    @Override
    public void fileMigrationOss(String createYear) throws Exception {
        log.info("FTP文件迁移至OSS开始");
        String localPath = fileService.getLocalPathDefault() + "img/tos/";
        List<Long> ids;
        // 获取所有图片信息
        DynamicContextHolder.push("business" + DbConstant.BUSINESS_WRITE);
        List<TDxInvoiceImg> tDxInvoiceImgList = fileMigrationDao.selectInvoiceImageFileGroup(createYear);
        if (tDxInvoiceImgList.size() > 0) {
            for (TDxInvoiceImg dxInvoiceImg : tDxInvoiceImgList) {
                List<TDxInvoiceImg> tDxInvoiceImgs =
                    fileMigrationDao.selectInvoiceImageFile(DateUtil.format(dxInvoiceImg.getCreateDate(), "yyyy-MM"));
                if (tDxInvoiceImgs.size() > 0) {
                    ids = new ArrayList<>();
                    for (TDxInvoiceImg img : tDxInvoiceImgs) {
                        String imageRemotePath = img.getImagePath();
                        File file = new File(imageRemotePath);
                        String fileName = file.getName();
                        String directory = imageRemotePath.substring(0, imageRemotePath.lastIndexOf("/"));
                        String saveFile = localPath + fileName;

                        boolean b = ftpService.downloadFile(directory, fileName, localPath);
                        if (b) {
                            FileModel fileModel = fileService.uploadFile(imageRemotePath, saveFile);
                            if (OssReturnConfig.SUCCESS.equals(fileModel.getCode())) {
                                ids.add(img.getId());
                            }
                            // 删除本地文件
                            FileUtil.del(saveFile);
                        }

                    }
                    if (ids.size() > 0) {
                        // 修改迁移状态信息
                        Aops.getSelf(this)
                            .updateMigrationStatusList(DateUtil.format(dxInvoiceImg.getCreateDate(), "yyyy-MM"), ids);
                    }
                }
            }
        }
        log.info("FTP文件迁移至OSS结束");
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateMigrationStatusList(String createMonth, List<Long> ids) {
        int size = ids.size();
        int startIndex = 0;
        // 每批入库list大小 比如：500条一批
        int endIndex = MAX_SIZE;
        // 定义临时list
        List<Long> idList;
        boolean flg = true;
        while (flg) {
            endIndex = Math.min(endIndex, size);
            idList = ids.subList(startIndex, endIndex);
            if (idList.size() == MAX_SIZE) {
                fileMigrationDao.updateMigrationStatus(createMonth, idList);
            } else {
                if (idList.size() > 0) {
                    fileMigrationDao.updateMigrationStatus(createMonth, idList);
                } else {
                    flg = false;
                }
            }
            startIndex = endIndex;
            if (endIndex >= size) {
                flg = false;
            } else {
                endIndex = startIndex + MAX_SIZE;
            }
        }
    }
}
