<template>
  <RightFillPano>
    <template #header>
      <div class="btns header-btns">
        <ui-button class="start" @click="start" type="primary">开始录制</ui-button>
      </div>
    </template>

    <ui-group title="全部视频" class="tree">
      <Draggable :list="records" draggable=".sign" itemKey="id">
        <template #item="{ element: record }">
          <Sign
            :record="getSignRecord(record)"
            :key="record.id"
            @delete="deleteRecord(record)"
            @updateTitle="(title: string) => (record.title = title)"
            @updateCover="(cover: string) => (record.cover = cover)"
          />
        </template>
      </Draggable>
    </ui-group>
  </RightFillPano>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { showMeasuresStack, showTaggingsStack } from "@/env";
import { useViewStack } from "@/hook";
import { diffArrayChange, togetherCallback } from "@/utils";
import { RecordProcess } from "./help";
import {
  records,
  createRecord,
  Record,
  RecordStatus,
  autoSaveRecords,
  initialRecords,
  getRecordFragmentBlobs,
  isTemploraryID,
  initialTaggingStyles,
  initialPaths,
} from "@/store";
import { RightFillPano } from "@/layout";
import Draggable from "vuedraggable";
import Sign from "./sign.vue";
import { Dialog } from "bill/index";
import { initialTaggings } from "@/store/tagging";
import { initialMeasures } from "@/store/measure";
import { initialGuides } from "@/store/guide";

initialRecords();
initialTaggingStyles();
initialTaggings();
initialMeasures();
initialGuides();
initialPaths();

const start = () => records.value.push(createRecord());
const deleteRecord = async (record: Record) => {
  const isTemp = getRecordFragmentBlobs(record).length === 0 && isTemploraryID(record.id);
  if (isTemp || (await Dialog.confirm("确定要删除视频吗？"))) {
    const index = records.value.indexOf(record);
    if (~index) {
      records.value.splice(index, 1);
    }
  }
};

const getSignRecord = (record: Record): RecordProcess => ({
  ...record,
  immediately: record.status === RecordStatus.UN,
});

const setOptions = [
  { value: "tagging", label: "标签" },
  { value: "measure", label: "测量" },
] as const;

type SetKey = typeof setOptions[number]["value"];
const setting = ref<SetKey[]>(["tagging", "measure"]);
watch(
  setting,
  (setting, oldSetting = [], onCleanup) => {
    const { added } = diffArrayChange(setting, oldSetting);
    const pops = added.map((value) => {
      if (value === "measure") {
        return showMeasuresStack.push(ref(true));
      } else {
        return showTaggingsStack.push(ref(true));
      }
    });
    onCleanup(togetherCallback(pops));
  },
  { flush: "sync" }
);

useViewStack(() => {
  // const pop = showTaggingsStack.push(ref(false))
  return () => {
    setting.value = [];
    // pop()
  };
});
useViewStack(autoSaveRecords);
</script>

<style lang="scss" src="./style.scss" scoped></style>
