package com.qmth.sop.business.util;

import com.alibaba.fastjson.JSONObject;
import com.qmth.sop.business.cache.CommonCacheService;
import com.qmth.sop.business.entity.SysConfig;
import com.qmth.sop.business.entity.TBTask;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.UploadFileEnum;
import com.qmth.sop.common.util.FileStoreUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 导入导出util
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2023/7/31
 */
@Component
public class ImportExportUtil {
    private final static Logger log = LoggerFactory.getLogger(ImportExportUtil.class);

    @Resource
    FileStoreUtil fileStoreUtil;

    @Resource
    CommonCacheService commonCacheService;

    /**
     * 创建txt文件
     *
     * @param message
     * @return
     * @throws Exception
     */
    public JSONObject createTxt(String message) throws Exception {
        File txtFileTemp = null;
        try {
            StringJoiner stringJoiner = SystemConstant.getDirName(UploadFileEnum.FILE, true);
            stringJoiner.add(SystemConstant.getNanoId()).add(SystemConstant.JSON_PREFIX);
            String path = stringJoiner.toString().replaceAll("\\\\", SystemConstant.ORG_SPLIT);
            txtFileTemp = SystemConstant.getFileTempVar(SystemConstant.JSON_PREFIX);

            String charset = SystemConstant.CHARSET_NAME;
            SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SYS_CONFIG_KEY_CHARSETS);
            if (Objects.nonNull(sysConfig) && StringUtils.isNotBlank(sysConfig.getConfigValue())) {
                charset = sysConfig.getConfigValue();
            }
            IOUtils.write(message.getBytes(charset), new FileOutputStream(txtFileTemp));

            String txtFileMd5 = DigestUtils.md5Hex(new FileInputStream(txtFileTemp));
            fileStoreUtil.ossUpload(path, txtFileTemp, txtFileMd5, UploadFileEnum.FILE.getFssType());
            JSONObject json = new JSONObject();
            json.put(SystemConstant.PATH, path);
            json.put(SystemConstant.TYPE, fileStoreUtil.uploadFileEnumIsOss(UploadFileEnum.FILE) ? SystemConstant.OSS : SystemConstant.LOCAL);
            json.put(SystemConstant.UPLOAD_TYPE, UploadFileEnum.FILE);
            return json;
        } finally {
            if (Objects.nonNull(txtFileTemp)) {
                txtFileTemp.delete();
            }
        }
    }

    /**
     * 获取上传的文件
     *
     * @param tbTask
     * @return
     * @throws Exception
     */
    public InputStream getUploadFileInputStream(TBTask tbTask) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(tbTask.getImportFilePath());
        String path = (String) jsonObject.get(SystemConstant.PATH);
        UploadFileEnum uploadType = Enum.valueOf(UploadFileEnum.class, (String) jsonObject.get(SystemConstant.UPLOAD_TYPE));
        return fileStoreUtil.ossDownloadIs(path, uploadType.getFssType());
    }

    /**
     * 输出文件
     *
     * @param inputStream
     * @param fileName
     */
    public void outputFile(InputStream inputStream, String fileName) throws IOException {
        try {
            HttpServletResponse response = ServletUtil.getResponse();
            BufferedInputStream br = new BufferedInputStream(inputStream);
            String fName = SystemConstant.urlEncode(fileName);

            response.reset();
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + fName);
            IOUtils.copy(br, response.getOutputStream());
            br.close();
        } catch (IOException e) {
            log.error(SystemConstant.LOG_ERROR, e);
        } finally {
            if (Objects.nonNull(inputStream)) {
                inputStream.close();
            }
        }
    }
}
