/**
 * top顶端待办任务
 */
import { defineStore } from 'pinia';
import {fetchTodoSize} from '/@/api/jsonflow/do-job'
import {Local} from "/@/utils/storage";
import {topJobList} from "./index";
import {locationHash} from "/@/api/order/order-key-vue";
import {windowLocationHref} from "/@/flow/support/extend";

interface Job {
  jobLen: number | null
}

// 是否开启JsonFlow
const jsonFlowEnable = ref(import.meta.env.VITE_JSON_FLOW_ENABLE === 'true');

export const useFlowJob = defineStore('flow/job', {
  state: (): Job => ({
    jobLen: Local.get('jobLen') || 0
  }),
  actions: {
    jsonFlowEnable() {
      return jsonFlowEnable.value;
    },
    topJobList() {
      if (this.jsonFlowEnable()) topJobList();
    },
    onTodoJobClick() {
      // 因a标签href="#"，会先跳转/
      setTimeout(() => {
        windowLocationHref(locationHash.TodoJobHash)
      }, 0)
    },
    // 获取待办任务数
    getJobList() {
      if (!this.jsonFlowEnable()) return Promise.resolve();
      return new Promise((resolve, reject) => {
        fetchTodoSize({belongType: '-1', current: 1, size: 1})
            .then(response => {
              this.jobLen = response.data.total
              Local.set('jobLen', this.jobLen);
              resolve(this.jobLen)
            }).catch(error => {
          reject(error)
        })
      })
    },
    setJobLen(len){
      this.jobLen = len
      Local.set('jobLen', this.jobLen);
    },
    async addJobLen() {
      await this.getJobList()
    },
    async delJobLen() {
      await this.getJobList()
    },
    clearJobLen(){
      this.jobLen = 0
      Local.set('jobLen', 0);
    }
  }
});
