import { usePagging } from "@/hook/pagging";
import {
  QuoteScene,
  QuoteSceneStatus,
  SceneType,
  getScenePagging,
  getSceneStep,
} from "@/store/scene";
import { computed, reactive, watch, watchEffect } from "vue";

export const useScenePaggingParams = () => {
  const pagging = usePagging({
    get: getScenePagging,
    paramsTemlate: {
      type: SceneType.SWKJ,
      sceneName: "",
      modelTitle: "",
      deptId: "",
      snCode: "",
    },
  });

  const isSwmx = computed(() => pagging.state.query.type === SceneType.SWMX);
  const keyword = computed({
    get: () =>
      isSwmx.value ? pagging.state.query.modelTitle : pagging.state.query.sceneName,
    set: (val: string) => {
      pagging.state.query.modelTitle = val;
      pagging.state.query.sceneName = val;
    },
  });

  let oldSnCode = pagging.state.query.snCode;
  watchEffect(() => {
    if (isSwmx.value) {
      oldSnCode = pagging.state.query.snCode;
      pagging.state.query.snCode = "";
    } else {
      pagging.state.query.snCode = oldSnCode;
    }
  });

  watch(
    () => pagging.state.query.type,
    () => {
      pagging.state.pag.currentPage = 1;
    }
  );

  watch(
    () => pagging.state.table.rows as QuoteScene[],
    (scenes, _, onCleanup) => {
      const getSteps = async () => {
        const runs = scenes.filter((scene) => scene.status === QuoteSceneStatus.RUN);
        if (!runs.length) return clearInterval(interval);

        for (const scene of runs) {
          // 请求进度
          scene.step = (await getSceneStep(scene)) as number;
        }
      };
      const interval = setInterval(getSteps, 1000);
      getSteps();
      onCleanup(() => clearInterval(interval));
    }
  );

  const queryResetRaw = pagging.queryReset;
  pagging.queryReset = () => {
    const type = pagging.state.query.type;
    queryResetRaw();
    pagging.state.query.type = type;
  };

  return reactive({ pagging, keyword, isSwmx });
};
export type ScenePagging = ReturnType<typeof useScenePaggingParams>["pagging"];
