package com.keyware.shandan.bianmu.export;

import cn.hutool.core.io.FileUtil;
import com.keyware.shandan.common.util.UUIDUtil;
import com.keyware.shandan.frame.config.component.AppContext;
import com.keyware.shandan.frame.properties.CustomProperties;
import lombok.Data;

import java.io.File;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Data
public abstract class ExportProgress implements Runnable, Serializable {

    private String exportId = UUIDUtil.getUUID();
    private String userId;
    private String title;
    private Integer currentStep = 0;
    protected final String tempDir;

    protected boolean error = false;

    public ExportProgress(String userId) {
        this.userId = userId;
        this.title = "正在查询需要导出的数据";
        CustomProperties customProperties = AppContext.getContext().getBean(CustomProperties.class);
        tempDir = customProperties.getFileStorage().getTempPath();
    }

    public abstract void run();

    /**
     * 进度总步数
     */
    public abstract long getStepTotal();

    public abstract String getDownloadPath();

    /**
     * 偏移量自增
     */
    public void autoAddStep() {
        this.currentStep++;
    }

    /**
     * 获取百分比
     *
     * @return
     */
    public int getPercentage() {
        return Math.round(currentStep / (float) getStepTotal() * 100);
    }

    /**
     * 判断是否完成
     *
     * @return
     */
    public boolean getIsDone() {
        return currentStep >= getStepTotal() && this.currentStep > 0 && this.getStepTotal() > 0;
    }

    protected void setDone() {
        currentStep = getCurrentStep();
    }

    public String getMsg() {
        return "(" + getPercentage() + "%) " + this.title;
    }

    public Map<String, Object> getProgress() {
        Map<String, Object> map = new HashMap<>();
        map.put("exportId", exportId);
        map.put("title", title);
        map.put("msg", getMsg());
        map.put("isDone", getIsDone());
        map.put("isError", error);
        return map;
    }

    public void clean() {
        File file = new File(getDownloadPath());
        if (file.exists()) {
            FileUtil.del(file);
        }
    }
}