<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="900"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑赛事' : '添加赛事'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="赛事名称" name="name">
        <a-input
          allow-clear
          placeholder="请输入赛事名称"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="赛事封面图" name="image">
        <SelectFile
          :placeholder="'请选择封面图'"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteItem"
        />
      </a-form-item>
      <a-form-item label="banner图" name="banner">
        <SelectFile
          :placeholder="'请选择banner图'"
          :limit="1"
          :data="banners"
          @done="chooseBanner"
          @del="onDeleteBanner"
        />
      </a-form-item>
      <a-form-item label="赛事日期" name="eventDate">
        <a-date-picker
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          class="ele-fluid"
          placeholder="请选择赛事日期"
          v-model:value="eventDateValue"
          @change="onEventDateChange"
        />
      </a-form-item>
      <a-form-item label="赛事地点" name="location">
        <a-input
          allow-clear
          placeholder="请输入赛事地点"
          v-model:value="form.location"
        />
      </a-form-item>
      <a-form-item label="报名费(元)" name="entryFee">
        <a-input-number
          :min="0"
          :precision="2"
          class="ele-fluid"
          placeholder="0表示免费"
          v-model:value="form.entryFee"
        />
      </a-form-item>
      <a-form-item label="名额上限" name="maxParticipants">
        <a-input-number
          :min="0"
          class="ele-fluid"
          placeholder="0表示不限名额"
          v-model:value="form.maxParticipants"
        />
      </a-form-item>
      <a-form-item label="尺码选项" name="sizeOptions">
        <a-input
          allow-clear
          placeholder="如: XS,S,M,L,XL,XXL（逗号分隔，不需尺码可留空）"
          v-model:value="form.sizeOptions"
        />
      </a-form-item>
      <a-form-item label="报名必填项">
        <a-checkbox-group v-model:value="requiredFields">
          <a-checkbox :value="1">姓名</a-checkbox>
          <a-checkbox :value="2">手机号</a-checkbox>
          <a-checkbox :value="3">身份证</a-checkbox>
          <a-checkbox :value="4">尺码</a-checkbox>
        </a-checkbox-group>
      </a-form-item>
      <a-form-item label="赛事描述" name="description">
        <a-textarea
          allow-clear
          :rows="3"
          placeholder="请输入赛事描述"
          v-model:value="form.description"
        />
      </a-form-item>
      <a-form-item label="是否热门" name="isHot">
        <a-radio-group v-model:value="form.isHot">
          <a-radio :value="0">否</a-radio>
          <a-radio :value="1">是</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">未开始</a-radio>
          <a-radio :value="1">报名中</a-radio>
          <a-radio :value="2">已截止</a-radio>
          <a-radio :value="3">已结束</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { useThemeStore } from '@/store/modules/theme';
  import { addShopEvent, updateShopEvent } from '@/api/shop/shopEvent';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { FileRecord } from '@/api/system/file/model';
  import dayjs from 'dayjs';

  // 获取主题状态
  const themeStore = useThemeStore();
  const styleResponsive = ref(true);

  const props = defineProps<{
    visible: boolean;
    data?: any | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const loading = ref(false);
  const maxable = ref(true);
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const banners = ref<ItemType[]>([]);

  // 日期相关
  const eventDateValue = ref<dayjs.Dayjs | null>(null);

  // 必填项复选框
  const requiredFields = ref<number[]>([]);

  const form = reactive({
    id: undefined as number | undefined,
    name: undefined as string | undefined,
    description: undefined as string | undefined,
    image: undefined as string | undefined,
    banner: undefined as string | undefined,
    eventDate: undefined as string | undefined,
    location: undefined as string | undefined,
    maxParticipants: 0 as number,
    entryFee: 0 as number,
    sizeOptions: undefined as string | undefined,
    requireName: 0 as number,
    requirePhone: 0 as number,
    requireIdCard: 0 as number,
    requireSize: 0 as number,
    status: 0 as number,
    isHot: 0 as number,
    tenantId: undefined as number | undefined,
    createTime: undefined as string | undefined,
    updateTime: undefined as string | undefined
  });

  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写赛事名称',
        trigger: 'blur'
      }
    ],
    location: [
      {
        required: true,
        type: 'string',
        message: '请填写赛事地点',
        trigger: 'blur'
      }
    ]
  });

  // 日期选择处理
  const onEventDateChange = (_: any, dateString: string) => {
    form.eventDate = dateString;
  };

  const chooseImage = (data: FileRecord) => {
    images.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.image = data.path;
  };

  const onDeleteItem = (index: number) => {
    images.value.splice(index, 1);
    form.image = '';
  };

  const chooseBanner = (data: FileRecord) => {
    banners.value.push({
      uid: data.id,
      url: data.path,
      status: 'done'
    });
    form.banner = data.path;
  };

  const onDeleteBanner = (index: number) => {
    banners.value.splice(index, 1);
    form.banner = '';
  };

  // 监听必填项变化
  watch(requiredFields, (val) => {
    form.requireName = val.includes(1) ? 1 : 0;
    form.requirePhone = val.includes(2) ? 1 : 0;
    form.requireIdCard = val.includes(3) ? 1 : 0;
    form.requireSize = val.includes(4) ? 1 : 0;
  });

  const { resetFields } = Form.useForm;

  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 根据是否更新选择接口
        const saveOrUpdate = isUpdate.value ? updateShopEvent : addShopEvent;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e: Error) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  const isUpdate = computed(() => !!props.data?.id);

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        banners.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if (props.data.image) {
            images.value.push({
              uid: uuid(),
              url: props.data.image,
              status: 'done'
            });
          }
          if (props.data.banner) {
            banners.value.push({
              uid: uuid(),
              url: props.data.banner,
              status: 'done'
            });
          }
          // 解析日期
          if (props.data.eventDate) {
            eventDateValue.value = dayjs(props.data.eventDate);
          }
          // 解析必填项
          requiredFields.value = [];
          if (props.data.requireName === 1) requiredFields.value.push(1);
          if (props.data.requirePhone === 1) requiredFields.value.push(2);
          if (props.data.requireIdCard === 1) requiredFields.value.push(3);
          if (props.data.requireSize === 1) requiredFields.value.push(4);
        } else {
          // 重置表单
          form.id = undefined;
          form.name = undefined;
          form.description = undefined;
          form.image = undefined;
          form.banner = undefined;
          form.eventDate = undefined;
          form.location = undefined;
          form.maxParticipants = 0;
          form.entryFee = 0;
          form.sizeOptions = undefined;
          form.requireName = 0;
          form.requirePhone = 0;
          form.requireIdCard = 0;
          form.requireSize = 0;
          form.status = 0;
          form.isHot = 0;
          requiredFields.value = [];
        }
      } else {
        // 重置表单
        if (formRef.value) {
          formRef.value.resetFields();
        }
      }
    },
    { immediate: true }
  );
</script>

<style scoped>
  .form-fields-config {
    border: 1px solid #d9d9d9;
    border-radius: 8px;
    padding: 16px;
    background: #fafafa;
  }
</style>
