<template>
  <el-dialog
    v-model="visible"
    :title="performanceId ? '编辑' : '新建/编辑'"
    width="900px"
    destroy-on-close
    class="performance-form-dialog"
    @closed="onClosed"
  >
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="120px" @submit.prevent>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="演出名称" prop="name" required>
            <el-input v-model="form.name" placeholder="请输入" maxlength="20" show-word-limit clearable />
          </el-form-item>
          <el-form-item label="演出海报" required>
            <div class="upload-wrap">
              <UploadImgs
                v-model:file-list="posterFileList"
                :api="uploadImgStore"
                :limit="1"
                :file-size="5"
                class="poster-upload"
                @update:file-list="onPosterChange"
              />
              <span class="upload-tip">({{ posterFileList.length }}/1)</span>
            </div>
          </el-form-item>
          <el-form-item label="演出风格" required>
            <el-checkbox-group v-model="form.style">
              <el-checkbox v-for="opt in styleOptions" :key="opt" :label="opt">
                {{ opt }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="演出类型">
            <el-radio-group v-model="form.performanceType">
              <el-radio value="特邀演出"> 特邀演出 </el-radio>
              <el-radio value="常规演出"> 常规演出 </el-radio>
            </el-radio-group>
            <div class="form-tip">特邀演出为单次</div>
          </el-form-item>
          <el-form-item label="演出频次">
            <el-radio-group v-model="form.frequency">
              <el-radio value="单次"> 单次 </el-radio>
              <el-radio value="每天定时进行" :disabled="form.performanceType === '特邀演出'"> 每天定时进行 </el-radio>
              <el-radio value="每周定时进行" :disabled="form.performanceType === '特邀演出'"> 每周定时进行 </el-radio>
            </el-radio-group>
          </el-form-item>

          <!-- 单次：演出时间 -->
          <template v-if="form.frequency === '单次'">
            <el-form-item label="演出时间" required>
              <div class="date-time-row">
                <el-date-picker
                  v-model="singleStartDate"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
                <el-time-picker
                  v-model="singleStartTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
                <span class="sep">至</span>
                <el-date-picker
                  v-model="singleEndDate"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
                <el-time-picker
                  v-model="singleEndTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
              </div>
            </el-form-item>
          </template>
          <!-- 每天：演出日期 + 演出时间 -->
          <template v-if="form.frequency === '每天定时进行'">
            <el-form-item label="演出日期" required>
              <div class="date-time-row">
                <el-date-picker
                  v-model="dailyDateStart"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
                <span class="sep">至</span>
                <el-date-picker
                  v-model="dailyDateEnd"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
              </div>
            </el-form-item>
            <el-form-item label="演出时间" required>
              <div class="date-time-row">
                <el-time-picker
                  v-model="dailyTimeStart"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
                <span class="sep">至</span>
                <el-time-picker
                  v-model="dailyTimeEnd"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
              </div>
            </el-form-item>
          </template>
          <!-- 每周：演出日期(周几) + 演出日期(范围) + 演出时间 -->
          <template v-if="form.frequency === '每周定时进行'">
            <el-form-item label="演出日期">
              <el-checkbox-group v-model="form.weeklyPerformanceWeekdays">
                <el-checkbox v-for="day in weekdays" :key="day" :label="day">
                  {{ day }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="演出日期" required>
              <div class="date-time-row">
                <el-date-picker
                  v-model="weeklyDateStart"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
                <span class="sep">至</span>
                <el-date-picker
                  v-model="weeklyDateEnd"
                  type="date"
                  placeholder="年/月/日"
                  value-format="YYYY-MM-DD"
                  style="width: 140px"
                />
              </div>
            </el-form-item>
            <el-form-item label="演出时间" required>
              <div class="date-time-row">
                <el-time-picker
                  v-model="weeklyTimeStart"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
                <span class="sep">至</span>
                <el-time-picker
                  v-model="weeklyTimeEnd"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="--:--"
                  style="width: 100px"
                />
              </div>
            </el-form-item>
          </template>

          <el-form-item label="图文详情图片">
            <div class="upload-wrap">
              <UploadImgs
                v-model:file-list="detailImageFileList"
                :api="uploadImgStore"
                :limit="9"
                :file-size="5"
                class="detail-upload"
                @update:file-list="onDetailImagesChange"
              />
              <span class="upload-tip">({{ form.detailPicUrl.length }}/9)</span>
            </div>
          </el-form-item>
          <el-form-item label="图文详情描述">
            <el-input
              v-model="form.detailDescription"
              type="textarea"
              placeholder="请输入"
              :rows="3"
              maxlength="300"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="表演嘉宾">
            <el-link type="primary" @click="openGuestSelect"> 请添加 </el-link>
            <div v-if="form.guests.length" class="guest-list">
              <div v-for="g in form.guests" :key="String(g.id)" class="guest-item">
                <el-avatar :size="32" :src="g.avatar">
                  <el-icon><User /></el-icon>
                </el-avatar>
                <span class="guest-name">{{ g.name || g.nickname || "--" }} {{ g.position ? ` ${g.position}` : "" }}</span>
                <el-icon class="guest-remove" @click="removeGuest(g)">
                  <Close />
                </el-icon>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="演出须知">
            <el-input v-model="form.notes" type="textarea" placeholder="请输入" :rows="6" maxlength="300" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" :loading="submitting" @click="submit"> 提交 </el-button>
    </template>
    <GuestSelectDialog v-model="guestSelectVisible" :selected-ids="selectedGuestIds" @confirm="onGuestsConfirm" />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from "vue";
import { ElMessage } from "element-plus";
import { User, Close } from "@element-plus/icons-vue";
import type { FormInstance, FormRules, UploadUserFile } from "element-plus";
import UploadImgs from "@/components/Upload/Imgs.vue";
import { uploadImgStore } from "@/api/modules/upload";
import {
  getPerformanceDetail,
  saveOrUpdatePerformance,
  detailToFormModel,
  getDefaultFormModel,
  buildPerformanceBackendPayload
} from "@/api/modules/performance";
import GuestSelectDialog from "./GuestSelectDialog.vue";
import type { GuestItem } from "./GuestSelectDialog.vue";

const styleOptions = [
  "民谣",
  "爵士",
  "摇滚",
  "电音",
  "流行",
  "蓝调",
  "AXAPPELLA (全人声伴奏)",
  "SOUL",
  "朋克",
  "R&B",
  "EDM",
  "原创",
  "古典",
  "金属",
  "说唱"
];
const weekdays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

const props = defineProps<{
  modelValue: boolean;
  performanceId: string | number | null;
  mode: "add" | "edit";
}>();

const emit = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "success"): void;
}>();

const visible = ref(props.modelValue);
const formRef = ref<FormInstance>();
const submitting = ref(false);
const posterFileList = ref<UploadUserFile[]>([]);
const detailImageFileList = ref<UploadUserFile[]>([]);
const guestSelectVisible = ref(false);

const form = ref<Record<string, any>>(getDefaultFormModel());

watch(
  () => props.modelValue,
  v => {
    visible.value = v;
    if (v) {
      if (props.performanceId) loadDetail();
      else Object.assign(form.value, getDefaultFormModel());
      syncPosterAndDetailFiles();
    }
  },
  { immediate: true }
);
watch(visible, v => emit("update:modelValue", v));
watch(
  () => form.value.performanceType,
  type => {
    if (type === "特邀演出") form.value.frequency = "单次";
  }
);

// 单次时间绑定到 form.performanceTime
const singleStartDate = computed({
  get: () => form.value.performanceTime?.startDate ?? "",
  set: v => {
    if (!form.value.performanceTime) form.value.performanceTime = {};
    form.value.performanceTime.startDate = v;
  }
});
const singleStartTime = computed({
  get: () => form.value.performanceTime?.startTime ?? "",
  set: v => {
    if (!form.value.performanceTime) form.value.performanceTime = {};
    form.value.performanceTime.startTime = v;
  }
});
const singleEndDate = computed({
  get: () => form.value.performanceTime?.endDate ?? "",
  set: v => {
    if (!form.value.performanceTime) form.value.performanceTime = {};
    form.value.performanceTime.endDate = v;
  }
});
const singleEndTime = computed({
  get: () => form.value.performanceTime?.endTime ?? "",
  set: v => {
    if (!form.value.performanceTime) form.value.performanceTime = {};
    form.value.performanceTime.endTime = v;
  }
});
const dailyDateStart = computed({
  get: () => form.value.dailyPerformanceDateRange?.start ?? "",
  set: v => {
    if (!form.value.dailyPerformanceDateRange) form.value.dailyPerformanceDateRange = {};
    form.value.dailyPerformanceDateRange.start = v;
  }
});
const dailyDateEnd = computed({
  get: () => form.value.dailyPerformanceDateRange?.end ?? "",
  set: v => {
    if (!form.value.dailyPerformanceDateRange) form.value.dailyPerformanceDateRange = {};
    form.value.dailyPerformanceDateRange.end = v;
  }
});
const dailyTimeStart = computed({
  get: () => form.value.dailyPerformanceTimeRange?.start ?? "",
  set: v => {
    if (!form.value.dailyPerformanceTimeRange) form.value.dailyPerformanceTimeRange = {};
    form.value.dailyPerformanceTimeRange.start = v;
  }
});
const dailyTimeEnd = computed({
  get: () => form.value.dailyPerformanceTimeRange?.end ?? "",
  set: v => {
    if (!form.value.dailyPerformanceTimeRange) form.value.dailyPerformanceTimeRange = {};
    form.value.dailyPerformanceTimeRange.end = v;
  }
});
const weeklyDateStart = computed({
  get: () => form.value.weeklyPerformanceDateRange?.start ?? "",
  set: v => {
    if (!form.value.weeklyPerformanceDateRange) form.value.weeklyPerformanceDateRange = {};
    form.value.weeklyPerformanceDateRange.start = v;
  }
});
const weeklyDateEnd = computed({
  get: () => form.value.weeklyPerformanceDateRange?.end ?? "",
  set: v => {
    if (!form.value.weeklyPerformanceDateRange) form.value.weeklyPerformanceDateRange = {};
    form.value.weeklyPerformanceDateRange.end = v;
  }
});
const weeklyTimeStart = computed({
  get: () => form.value.weeklyPerformanceTimeRange?.start ?? "",
  set: v => {
    if (!form.value.weeklyPerformanceTimeRange) form.value.weeklyPerformanceTimeRange = {};
    form.value.weeklyPerformanceTimeRange.start = v;
  }
});
const weeklyTimeEnd = computed({
  get: () => form.value.weeklyPerformanceTimeRange?.end ?? "",
  set: v => {
    if (!form.value.weeklyPerformanceTimeRange) form.value.weeklyPerformanceTimeRange = {};
    form.value.weeklyPerformanceTimeRange.end = v;
  }
});

const selectedGuestIds = computed(() => form.value.guests?.map((g: any) => g.id) ?? []);

const formRules: FormRules = {
  name: [{ required: true, message: "请输入演出名称", trigger: "blur" }]
};

async function loadDetail() {
  if (!props.performanceId) return;
  try {
    const res: any = await getPerformanceDetail(props.performanceId);
    const raw = res?.data ?? res;
    if (raw) Object.assign(form.value, detailToFormModel(raw));
    syncPosterAndDetailFiles();
  } catch (e) {
    ElMessage.error("获取详情失败");
  }
}

function syncPosterAndDetailFiles() {
  const poster = form.value.posterUrls?.[0] ?? form.value.imgUrl;
  posterFileList.value = poster ? ([{ name: "poster", url: poster }] as UploadUserFile[]) : [];
  const urls = form.value.detailPicUrl ?? [];
  detailImageFileList.value = urls.map((u: string, i: number) => ({ name: `detail-${i}`, url: u })) as UploadUserFile[];
}

function onPosterChange(list: UploadUserFile[]) {
  const url = list.length ? ((list[0].url as string) ?? "") : "";
  form.value.posterUrls = url ? [url] : [];
  form.value.imgUrl = url;
}

function onDetailImagesChange(list: UploadUserFile[]) {
  form.value.detailPicUrl = list.map(f => (typeof f.url === "string" ? f.url : "")).filter(Boolean);
}

function openGuestSelect() {
  guestSelectVisible.value = true;
}

function onGuestsConfirm(list: GuestItem[]) {
  form.value.guests = list;
}

function removeGuest(g: any) {
  form.value.guests = (form.value.guests || []).filter((x: any) => x.id !== g.id);
}

function onClosed() {
  form.value = getDefaultFormModel();
  posterFileList.value = [];
  detailImageFileList.value = [];
}

function validateForm(): boolean {
  if (!form.value.name?.trim()) {
    ElMessage.warning("请输入演出名称");
    return false;
  }
  const poster = form.value.posterUrls?.[0] ?? form.value.imgUrl;
  if (!poster) {
    ElMessage.warning("请上传演出海报");
    return false;
  }
  if (!form.value.style?.length) {
    ElMessage.warning("请选择演出风格");
    return false;
  }
  if (form.value.frequency === "单次") {
    const pt = form.value.performanceTime || {};
    if (!pt.startDate || !pt.startTime || !pt.endDate || !pt.endTime) {
      ElMessage.warning("请填写演出时间");
      return false;
    }
  }
  if (form.value.frequency === "每天定时进行") {
    const dr = form.value.dailyPerformanceDateRange || {};
    const tr = form.value.dailyPerformanceTimeRange || {};
    if (!dr.start || !dr.end || !tr.start || !tr.end) {
      ElMessage.warning("请填写演出日期与时间");
      return false;
    }
  }
  if (form.value.frequency === "每周定时进行") {
    const wr = form.value.weeklyPerformanceDateRange || {};
    const tr = form.value.weeklyPerformanceTimeRange || {};
    if (!wr.start || !wr.end || !tr.start || !tr.end) {
      ElMessage.warning("请填写演出日期与时间");
      return false;
    }
  }
  return true;
}

async function submit() {
  if (!validateForm() || submitting.value) return;
  submitting.value = true;
  try {
    const payload = buildPerformanceBackendPayload(form.value);
    const res: any = await saveOrUpdatePerformance(payload);
    if (res?.code === 200) {
      ElMessage.success(props.performanceId ? "编辑成功" : "新建成功");
      emit("success");
      visible.value = false;
    } else {
      ElMessage.error(res?.msg || "提交失败");
    }
  } catch (e) {
    ElMessage.error("提交失败");
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped lang="scss">
.upload-wrap {
  display: flex;
  gap: 8px;
  align-items: center;
  .poster-upload,
  .detail-upload {
    :deep(.el-upload-list--picture-card) {
      --el-upload-list-picture-card-size: 100px;
    }
    :deep(.el-upload--picture-card) {
      width: 100px;
      height: 100px;
    }
  }
  .upload-tip {
    font-size: 12px;
    color: #909399;
  }
}
.form-tip {
  margin-top: 4px;
  font-size: 12px;
  color: #909399;
}
.date-time-row {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
  .sep {
    color: #909399;
  }
}
.guest-list {
  margin-top: 8px;
  .guest-item {
    display: flex;
    gap: 8px;
    align-items: center;
    padding: 6px 0;
    .guest-name {
      flex: 1;
      font-size: 14px;
    }
    .guest-remove {
      color: #909399;
      cursor: pointer;
      &:hover {
        color: #f56c6c;
      }
    }
  }
}
</style>
