package com.qmth.distributed.print.business.templete.importData;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.qmth.boot.api.exception.ApiException;
import com.qmth.teachcloud.common.contant.SpringContextHolder;
import com.qmth.teachcloud.common.contant.SystemConstant;
import com.qmth.teachcloud.common.entity.SysConfig;
import com.qmth.teachcloud.common.entity.TBTask;
import com.qmth.teachcloud.common.enums.*;
import com.qmth.teachcloud.common.service.CommonCacheService;
import com.qmth.teachcloud.common.service.SysConfigService;
import com.qmth.teachcloud.common.service.TBTaskService;
import com.qmth.teachcloud.common.util.FileStoreUtil;
import com.qmth.teachcloud.common.util.Result;
import com.qmth.teachcloud.common.util.ResultUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.StringJoiner;

/**
 * @Description: 异步导入模版
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/3/29
 */
public abstract class AsyncImportTaskTemplete {

    private final static Logger log = LoggerFactory.getLogger(AsyncImportTaskTemplete.class);

    public static final String BEGIN_TITLE = "->开始准备处理导入的";
    public static final String EXCEPTION_TITLE = "->数据处理发生异常!";
    public static final String EXCEPTION_DATA = "错误信息:";
    public static final String FINISH_TITLE = "->数据处理结束，共处理了";
    public static final String FINISH_SIZE = "条数据";
    public static final String TXT_PREFIX = ".txt";
    public static final String EXCEPTION_CREATE_TXT_TITLE = "->创建导出日志时发生异常!";

    /**
     * 异步导入任务
     *
     * @param map
     * @return
     * @throws IOException
     */
    @Async
    public abstract Result importTask(Map<String, Object> map) throws IOException, Exception;

    /**
     * 获取上传的文件
     *
     * @param tbTask
     * @return
     * @throws IOException
     */
    public InputStream getUploadFileInputStream(TBTask tbTask) throws Exception {
        FileStoreUtil fileStoreUtil = SpringContextHolder.getBean(FileStoreUtil.class);
        JSONObject jsonObject = JSONObject.parseObject(tbTask.getImportFilePath());
        String path = (String) jsonObject.get(SystemConstant.PATH);
        String type = (String) jsonObject.get(SystemConstant.TYPE);
        UploadFileEnum uploadType = Enum.valueOf(UploadFileEnum.class, (String) jsonObject.get(SystemConstant.UPLOAD_TYPE));
        InputStream inputStream = null;
        if (Objects.equals(type, SystemConstant.OSS)) {
            inputStream = fileStoreUtil.ossDownloadIs(path, uploadType.getFssType());
        } else {
//            StringJoiner localPath = new StringJoiner("").add(SystemConstant.TEMP_FILES_DIR).add(File.separator).add(path);
            inputStream = new FileInputStream(new File(path));
//            inputStream = fileStoreUtil.ossDownloadIs(path, "localfile");
        }
        return inputStream;
    }

    /**
     * 创建txt文件
     *
     * @param tbTask
     */
    public void createTxt(TBTask tbTask) {
//        OssUtil ossUtil = SpringContextHolder.getBean(OssUtil.class);
        TBTaskService tbTaskService = SpringContextHolder.getBean(TBTaskService.class);
        ByteArrayOutputStream out = null;
        InputStream inputStream = null;
        try {
            JSONObject jsonObject = JSONObject.parseObject(tbTask.getImportFilePath());
            if (Objects.isNull(jsonObject)) {
                jsonObject = new JSONObject();
                LocalDateTime nowTime = LocalDateTime.now();
                StringJoiner stringJoiner = new StringJoiner("");
                stringJoiner.add(UploadFileEnum.FILE.getTitle()).add(File.separator);
                stringJoiner.add(String.valueOf(nowTime.getYear())).add(File.separator)
                        .add(String.format("%02d", nowTime.getMonthValue())).add(File.separator)
                        .add(String.format("%02d", nowTime.getDayOfMonth()))
                        .add(File.separator).add(SystemConstant.getUuid()).add(TXT_PREFIX);
                jsonObject.put(SystemConstant.TYPE, SystemConstant.OSS);
                jsonObject.put(SystemConstant.PATH, stringJoiner.toString());
            }
            String path = (String) jsonObject.get(SystemConstant.PATH);
            path = path.replaceAll("\\\\", "/");
            String type = (String) jsonObject.get(SystemConstant.TYPE);

            String charset = SystemConstant.CHARSET_GBK;
            CommonCacheService commonCacheService = SpringContextHolder.getBean(CommonCacheService.class);
            if (commonCacheService != null) {
                SysConfig sysConfig = commonCacheService.addSysConfigCache(SystemConstant.SYS_CONFIG_KEY_CHARSETS);
                if (sysConfig != null && StringUtils.isNotBlank(sysConfig.getConfigValue())) {
                    charset = sysConfig.getConfigValue();
                }
            }

            out = new ByteArrayOutputStream();
            out.write(tbTask.getSummary().getBytes(charset));
            byte[] bookByteAry = out.toByteArray();
            inputStream = new ByteArrayInputStream(bookByteAry);
            StringJoiner stringJoiner = new StringJoiner("");
            if (tbTask.getType() == TaskTypeEnum.CREATE_PDF) {
                path = path.replaceAll(UploadFileEnum.PDF.getTitle(), UploadFileEnum.FILE.getTitle());
            }

            path = path.substring(0, path.lastIndexOf("/") + 1);
            stringJoiner.add(path).add(SystemConstant.getUuid()).add(TXT_PREFIX).toString();
            if (Objects.equals(type, SystemConstant.OSS)) {//上传至oss
                stringJoiner.add(path).add(SystemConstant.getUuid()).add(TXT_PREFIX).toString();
                FileStoreUtil fileStoreUtil = SpringContextHolder.getBean(FileStoreUtil.class);
                fileStoreUtil.ossUpload(stringJoiner.toString(), inputStream, DigestUtils.md5Hex(new ByteArrayInputStream(bookByteAry)), fileStoreUtil.getUploadEnumByPath(stringJoiner.toString()).getFssType());
            } else {//上传至服务器
                FileStoreUtil fileStoreUtil = SpringContextHolder.getBean(FileStoreUtil.class);
                fileStoreUtil.copyInputStreamToFile(inputStream,new File(stringJoiner.toString()),DigestUtils.md5Hex(new ByteArrayInputStream(bookByteAry)),LocalCatalogEnum.LOCAL_FILE);
            }
            JSONObject json = new JSONObject();
            json.put(SystemConstant.PATH, stringJoiner.toString());
            json.put(SystemConstant.TYPE, type);
            json.put(SystemConstant.UPLOAD_TYPE, UploadFileEnum.FILE);

            tbTask.setReportFilePath(json.toJSONString());
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
            StringJoiner stringJoinerSummary = new StringJoiner("").add(tbTask.getSummary()).add("\n");
            stringJoinerSummary.add(MessageFormat.format("{0}{1}{2}{3}", DateUtil.format(new Date(), SystemConstant.DEFAULT_DATE_PATTERN), EXCEPTION_CREATE_TXT_TITLE, EXCEPTION_DATA, e.getMessage()));

            String summary = stringJoinerSummary.toString();
            if (summary.length() >= 65535) {
                summary = "Data too long : " + summary.substring(0, 100) + "......" + summary.substring(summary.length() - 100);
            }

            tbTask.setSummary(summary);
            tbTask.setResult(TaskResultEnum.ERROR);
//            TBTask dbTask = tbTaskService.getById(tbTask.getId());
//            if (tbTask.getVersion() == dbTask.getVersion()) {
//                tbTask.setResetCount(new AtomicInteger(tbTask.getResetCount()).incrementAndGet());
//            }
            if (e instanceof ApiException) {
                ResultUtil.error((ApiException) e, e.getMessage());
            } else {
                ResultUtil.error(e.getMessage());
            }
        } finally {
            try {
                if (Objects.nonNull(inputStream)) {
                    inputStream.close();
                }
                if (Objects.nonNull(out)) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                log.error(SystemConstant.LOG_ERROR, e);
            }
            tbTask.setStatus(TaskStatusEnum.FINISH);
            if (tbTask.getType() == TaskTypeEnum.CREATE_PDF) {
                tbTask.setResultFilePath(tbTask.getImportFilePath());
                tbTask.setImportFileName(null);
                tbTask.setImportFilePath(null);
                tbTask.setErrorMessage(null);
            }
            tbTaskService.updateById(tbTask);
        }
    }
}
