<script setup>
import { ref } from "vue";
import { storeToRefs } from "pinia";
import { useWorkflowStore } from "../../stores/workflow.js";

const workflow = useWorkflowStore();
const {
  ipBrainModalVisible,
  ipBrainProfileUrl,
  ipBrainCollecting,
  ipBrainCollectProgress,
} = storeToRefs(workflow);

const feedback = ref({ severity: "", message: "" });

const tipItems = [
  "输入账号主页或分享链接后点击「开始采集」按钮",
  "系统会自动打开浏览器并抓取数据，请保持网络连接正常",
  "无需任何手动操作，等待采集完成即可",
  "采集完成后会自动将最多 6 个视频标题添加到选题库中",
];

function onCancel() {
  if (ipBrainCollecting.value) return;
  feedback.value = { severity: "", message: "" };
  workflow.closeIpBrainDialog();
}

async function onStart() {
  feedback.value = { severity: "", message: "" };
  const result = await workflow.startIpBrainCollect();
  if (result.ok) {
    feedback.value = { severity: "success", message: result.message };
  } else {
    feedback.value = { severity: "error", message: result.message };
  }
}
</script>

<template>
  <Dialog
    v-model:visible="ipBrainModalVisible"
    modal
    header="添加IP大脑"
    :style="{ width: '600px' }"
    :draggable="false"
    class="ip-brain-dialog"
    :closable="!ipBrainCollecting"
  >
    <div class="space-y-4">
      <Message
        v-if="feedback.message && !ipBrainCollecting"
        :severity="feedback.severity"
        :closable="false"
        class="w-full"
      >
        {{ feedback.message }}
      </Message>

      <Message
        v-if="ipBrainCollecting && ipBrainCollectProgress"
        severity="info"
        :closable="false"
        class="w-full"
      >
        {{ ipBrainCollectProgress }}
      </Message>

      <div>
        <label class="mb-2 block font-medium text-slate-200">
          账号主页或分享链接
        </label>
        <InputText
          v-model="ipBrainProfileUrl"
          type="text"
          size="large"
          class="w-full"
          placeholder="请输入抖音账号主页或用户分享链接，例如：https://www.douyin.com/user/..."
          :disabled="ipBrainCollecting"
          @keyup.enter="onStart"
        />
        <p class="mt-2 text-xs text-slate-500">
          当前 IP 学习支持抖音账号主页、用户分享链接和短链接，程序会自动识别并采集最新
          6 个视频标题
        </p>
      </div>

      <div class="elegant-tip-box rounded-lg p-3">
        <div class="text-sm text-slate-300">
          <div class="mb-1 font-medium">提示:</div>
          <ul class="list-inside list-disc space-y-1">
            <li v-for="(tip, i) in tipItems" :key="i">{{ tip }}</li>
          </ul>
        </div>
      </div>
    </div>

    <template #footer>
      <Button
        label="取消"
        severity="secondary"
        :disabled="ipBrainCollecting"
        @click="onCancel"
      />
      <Button label="开始采集" :loading="ipBrainCollecting" @click="onStart" />
    </template>
  </Dialog>
</template>
