<!-- 编辑弹窗 -->
<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="type">
        <a-radio-group v-model:value="form.type">
          <a-radio :value="1">满减</a-radio>
          <a-radio :value="2">折扣</a-radio>
          <a-radio :value="3">秒杀</a-radio>
          <a-radio :value="4">拼团</a-radio>
        </a-radio-group>
      </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="活动描述" name="description">
        <a-textarea
          allow-clear
          :rows="3"
          placeholder="请输入活动描述"
          v-model:value="form.description"
        />
      </a-form-item>
      <a-form-item label="活动开始时间" name="startTime">
        <a-date-picker
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          class="ele-fluid"
          placeholder="请选择活动开始时间"
          v-model:value="startTimeValue"
          @change="onStartTimeChange"
        />
      </a-form-item>
      <a-form-item label="活动结束时间" name="endTime">
        <a-date-picker
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          class="ele-fluid"
          placeholder="请选择活动结束时间"
          v-model:value="endTimeValue"
          @change="onEndTimeChange"
        />
      </a-form-item>
      <a-form-item label="活动规则" name="rules">
        <a-textarea
          allow-clear
          :rows="4"
          placeholder="请输入活动规则(JSON格式)"
          v-model:value="form.rules"
        />
      </a-form-item>
      <a-form-item label="商户ID" name="merchantId">
        <a-input-number
          :min="0"
          class="ele-fluid"
          placeholder="请输入商户ID"
          v-model:value="form.merchantId"
        />
      </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-group>
      </a-form-item>
    </a-form>
  </ele-modal>

</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject, uuid } from 'ele-admin-pro';
  import { addShopActivity, updateShopActivity } from '@/api/shop/shopActivity';
  import { ShopActivity } from '@/api/shop/shopActivity/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  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';
  import {
    PlusOutlined
  } from '@ant-design/icons-vue';

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    visible: boolean;
    data?: ShopActivity | 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 startTimeValue = ref<dayjs.Dayjs | null>(null);
  const endTimeValue = ref<dayjs.Dayjs | null>(null);

  const form = reactive<ShopActivity>({
    id: undefined,
    name: undefined,
    description: undefined,
    image: undefined,
    banner: undefined,
    type: 1,
    startTime: undefined,
    endTime: undefined,
    status: 0,
    rules: undefined,
    merchantId: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined
  });

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

  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写活动名称',
        trigger: 'blur'
      }
    ]
  });

  // 日期选择处理
  const onStartTimeChange = (_: any, dateString: string) => {
    form.startTime = dateString;
  };
  const onEndTimeChange = (_: any, dateString: string) => {
    form.endTime = 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 { resetFields } = useForm(form, rules);

  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        // 将字段列表转为JSON字符串
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateShopActivity : addShopActivity;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.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.startTime) {
            startTimeValue.value = dayjs(props.data.startTime);
          }
          if (props.data.endTime) {
            endTimeValue.value = dayjs(props.data.endTime);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style scoped></style>
