<!-- 重绘项目编辑对话框，负责项目元数据和主演信息录入。 -->
<script setup lang="ts">
import { reactive, watch } from "vue";
import { Plus, Trash2 } from "@/icons";
import type { ProjectCastMember, ProjectDetail, ProjectPayload } from "@/api/creative";

const props = defineProps<{
  modelValue: boolean;
  project?: ProjectDetail | null;
  saving?: boolean;
}>();
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  save: [payload: ProjectPayload];
}>();

type RedrawProjectForm = {
  name: string;
  short_drama_type: string;
  play_count: string;
  audience_profile: string;
  producer: string;
  cast_members: ProjectCastMember[];
};

const form = reactive<RedrawProjectForm>({
  name: "",
  short_drama_type: "",
  play_count: "",
  audience_profile: "",
  producer: "",
  cast_members: [{ name: "", follower_count: undefined }],
});
const errors = reactive({
  name: "",
  short_drama_type: "",
  audience_profile: "",
  producer: "",
  cast_members: [] as Array<{ name: string; follower_count: string }>,
});

watch(
  () => [props.modelValue, props.project] as const,
  () => {
    if (!props.modelValue) return;
    const project = props.project;
    form.name = project?.name || "";
    form.short_drama_type = project?.short_drama_type || "";
    form.play_count = project?.play_count || "";
    form.audience_profile = project?.audience_profile || "";
    form.producer = project?.producer || "";
    form.cast_members = project?.cast_members?.length
      ? project.cast_members.map((member) => ({ ...member }))
      : [{ name: "", follower_count: undefined }];
    resetErrors();
  },
  { immediate: true },
);

function resetErrors() {
  errors.name = "";
  errors.short_drama_type = "";
  errors.audience_profile = "";
  errors.producer = "";
  errors.cast_members = [];
}

function addCastMember() {
  if (form.cast_members.length >= 50) return;
  form.cast_members.push({ name: "", follower_count: undefined });
}

function removeCastMember(index: number) {
  form.cast_members.splice(index, 1);
  errors.cast_members.splice(index, 1);
}

function submit() {
  resetErrors();
  errors.name = form.name.trim() ? "" : "请输入短剧名";
  errors.cast_members = form.cast_members.map((member) => {
    const hasName = Boolean(member.name.trim());
    const hasFollowerCount = Boolean(member.follower_count?.trim());
    return {
      name: !hasName && hasFollowerCount ? "请输入主演姓名" : "",
      follower_count: "",
    };
  });
  const invalid = errors.name || errors.cast_members.some((item) => item.name || item.follower_count);
  if (invalid) return;

  emit("save", {
    project_type: "video_redraw",
    name: form.name.trim(),
    style_id: props.project?.style_id || "",
    era_type: props.project?.era_type || "modern_city",
    custom_era: props.project?.custom_era || null,
    aspect_ratio: props.project?.aspect_ratio || "9:16",
    localization: props.project?.localization || "china",
    short_drama_type: form.short_drama_type.trim(),
    play_count: form.play_count.trim(),
    audience_profile: form.audience_profile.trim(),
    producer: form.producer.trim(),
    cast_members: form.cast_members
      .filter((member) => member.name.trim())
      .map((member) => ({
        name: member.name.trim(),
        follower_count: member.follower_count?.trim() || undefined,
      })),
  });
}
</script>

<template>
  <el-dialog
    :model-value="modelValue"
    :title="project ? '编辑反推项目' : '创建反推项目'"
    width="min(680px, calc(100vw - 28px))"
    align-center
    class="web-dialog creative-dialog redraw-project-dialog"
    @close="emit('update:modelValue', false)"
  >
    <el-form
      class="redraw-project-form"
      label-position="top"
    >
      <div class="redraw-form-grid">
        <el-form-item
          label="短剧名"
          required
          :class="{ 'field-invalid': errors.name }"
        >
          <el-input
            v-model.trim="form.name"
            maxlength="100"
            placeholder="请输入短剧名"
          />
          <div
            v-if="errors.name"
            class="field-error"
          >
            {{ errors.name }}
          </div>
        </el-form-item>
        <el-form-item
          label="短剧类型"
          :class="{ 'field-invalid': errors.short_drama_type }"
        >
          <el-input
            v-model.trim="form.short_drama_type"
            maxlength="100"
            placeholder="例如：都市情感、悬疑"
          />
          <div
            v-if="errors.short_drama_type"
            class="field-error"
          >
            {{ errors.short_drama_type }}
          </div>
        </el-form-item>
        <el-form-item label="播放量">
          <el-input
            v-model.trim="form.play_count"
            maxlength="100"
            placeholder="请输入播放量"
          />
        </el-form-item>
        <el-form-item
          label="出品方"
          :class="{ 'field-invalid': errors.producer }"
        >
          <el-input
            v-model.trim="form.producer"
            maxlength="200"
            placeholder="请输入出品方"
          />
          <div
            v-if="errors.producer"
            class="field-error"
          >
            {{ errors.producer }}
          </div>
        </el-form-item>
      </div>

      <el-form-item
        label="受众群体画像"
        :class="{ 'field-invalid': errors.audience_profile }"
      >
        <el-input
          v-model.trim="form.audience_profile"
          type="textarea"
          :rows="3"
          maxlength="2000"
          show-word-limit
          placeholder="请输入年龄、性别、地域、兴趣偏好等受众特征"
        />
        <div
          v-if="errors.audience_profile"
          class="field-error"
        >
          {{ errors.audience_profile }}
        </div>
      </el-form-item>

      <section class="cast-editor">
        <header>
          <div>
            <strong>主演</strong>
            <span>填写主演姓名和粉丝量</span>
          </div>
          <button
            type="button"
            :disabled="form.cast_members.length >= 50"
            @click="addCastMember"
          >
            <Plus :size="16" />增加主演
          </button>
        </header>
        <div
          v-if="!form.cast_members.length"
          class="cast-empty"
        >
          <span>{{ errors.cast_members[0]?.name || "暂无主演" }}</span>
          <button
            type="button"
            @click="addCastMember"
          >
            <Plus :size="16" />添加主演
          </button>
        </div>
        <div
          v-for="(member, index) in form.cast_members"
          :key="index"
          class="cast-row"
        >
          <el-form-item
            :label="`主演 ${index + 1}`"
            :class="{ 'field-invalid': errors.cast_members[index]?.name }"
          >
            <el-input
              v-model.trim="member.name"
              maxlength="100"
              placeholder="主演姓名"
            />
            <div
              v-if="errors.cast_members[index]?.name"
              class="field-error"
            >
              {{ errors.cast_members[index].name }}
            </div>
          </el-form-item>
          <el-form-item label="粉丝量">
            <el-input
              v-model.trim="member.follower_count"
              maxlength="100"
              placeholder="粉丝量"
            />
          </el-form-item>
          <button
            type="button"
            class="remove-cast"
            @click="removeCastMember(index)"
          >
            <Trash2 :size="17" />
          </button>
        </div>
      </section>
    </el-form>
    <template #footer>
      <el-button @click="emit('update:modelValue', false)">取消</el-button>
      <el-button
        type="primary"
        :loading="saving"
        @click="submit"
      >
        {{ project ? "保存项目" : "创建项目" }}
      </el-button>
    </template>
  </el-dialog>
</template>

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