<!-- 编辑弹窗 -->
<template>
  <ele-modal
    width="720px"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑商品' : '新增商品'"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ flex: '90px' }"
      :wrapper-col="{ flex: '1' }"
      style="overflow-x: hidden"
    >
      <a-form-item label="商品名称" name="productName">
        <a-input v-model:value="form.productName" placeholder="请输入商品名称" />
      </a-form-item>
      <a-form-item label="商品描述" name="description">
        <a-textarea
          v-model:value="form.description"
          placeholder="请输入商品描述"
          :rows="3"
        />
      </a-form-item>
      <a-form-item label="封面图片" name="productImage">
        <SelectFile
          :placeholder="'请选择封面图'"
          :limit="1"
          :data="images"
          @done="chooseImage"
          @del="onDeleteImage"
        />
      </a-form-item>
      <a-form-item label="图片集" name="images">
        <SelectFile
          :placeholder="'请选择图片集'"
          :limit="9"
          :data="imageList"
          @done="chooseImageList"
          @del="onDeleteImageList"
        />
      </a-form-item>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="所需积分" name="pointsPrice">
            <a-input-number
              v-model:value="form.pointsPrice"
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="库存" name="stock">
            <a-input-number
              v-model:value="form.stock"
              :min="-1"
              placeholder="-1表示不限"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="热销" name="isHot">
            <a-switch
              v-model:checked="form.isHot"
              :checkedValue="1"
              :uncheckedValue="0"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="排序" name="sortNumber">
            <a-input-number
              v-model:value="form.sortNumber"
              :min="0"
              style="width: 100%"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <a-radio-group v-model:value="form.status">
              <a-radio :value="1">上架</a-radio>
              <a-radio :value="0">下架</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { FormInstance } from 'ant-design-vue/es/form';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FileRecord } from '@/api/system/file/model';
  import {
    addShopPointsProduct,
    updateShopPointsProduct,
    type ShopPointsProduct
  } from '@/api/shop/shopPointsProduct';

  const props = defineProps<{
    visible: boolean;
    data?: ShopPointsProduct | 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 imageList = ref<ItemType[]>([]);

  const form = reactive<ShopPointsProduct>({
    productName: '',
    productImage: '',
    images: '',
    description: '',
    pointsPrice: 0,
    stock: -1,
    sortNumber: 0,
    status: 1
  });

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

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

  const rules = {
    productName: [
      { required: true, message: '请输入商品名称', trigger: 'blur' }
    ] as any[],
    pointsPrice: [
      { required: true, message: '请输入所需积分', trigger: 'blur' }
    ] as any[]
  };

  // 选择封面图
  const chooseImage = (data: FileRecord) => {
    images.value.push({ uid: data.id, url: data.path, status: 'done' });
    form.productImage = data.path;
  };

  // 删除封面图
  const onDeleteImage = (index: number) => {
    images.value.splice(index, 1);
    form.productImage = '';
  };

  // 选择图片集
  const chooseImageList = (data: FileRecord) => {
    imageList.value.push({ uid: data.id, url: data.path, status: 'done' });
    form.images = imageList.value.map((i) => i.url).join(',');
  };

  // 删除图片集
  const onDeleteImageList = (index: number) => {
    imageList.value.splice(index, 1);
    form.images = imageList.value.map((i) => i.url).join(',');
  };

  // 保存
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateShopPointsProduct : addShopPointsProduct;
        const submitData = isUpdate.value ? { ...form, id: props.data?.id } : form;
        saveOrUpdate(submitData as any)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e: Error) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  // 监听 visible 变化
  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        imageList.value = [];
        if (props.data) {
          // 编辑模式
          Object.assign(form, props.data);
          if (props.data.productImage) {
            images.value = [{
              uid: props.data.id ?? -1,
              url: props.data.productImage,
              status: 'done'
            }];
          }
          if (props.data.images) {
            const imgArr = props.data.images.split(',').filter(Boolean);
            imageList.value = imgArr.map((url, idx) => ({
              uid: -idx - 1,
              url,
              status: 'done' as const
            }));
          }
        } else {
          // 新增模式
          Object.assign(form, {
            productName: '',
            productImage: '',
            images: '',
            description: '',
            pointsPrice: 0,
            stock: -1,
            sortNumber: 0,
            status: 1
          });
        }
      }
    },
    { immediate: true }
  );
</script>
