<!-- 规格值编辑弹窗 -->
<template>
  <ele-modal
    :width="520"
    :visible="visible"
    :maskClosable="false"
    :title="isUpdate ? '编辑规格值' : '添加规格值'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ flex: '80px' }"
      :wrapper-col="{ flex: '1' }"
    >
      <a-form-item label="所属规格" name="specId">
        <a-select
          v-model:value="form.specId"
          placeholder="请选择所属规格组"
          :loading="specLoading"
          allow-clear
          show-search
          :filter-option="filterSpec"
        >
          <a-select-option
            v-for="spec in specList"
            :key="spec.specId"
            :value="spec.specId"
          >
            {{ spec.specName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="规格值" name="specValue">
        <a-input
          allow-clear
          placeholder="如：红色、XL、棉质"
          v-model:value="form.specValue"
        />
      </a-form-item>
      <a-form-item label="图片" name="image">
        <div class="image-row">
          <a-image
            v-if="form.image"
            :src="form.image"
            :width="56"
            :height="56"
            style="object-fit: cover; border-radius: 4px; margin-right: 8px"
          />
          <a-upload
            :show-upload-list="false"
            accept="image/*"
            :before-upload="(file: File) => handleImageUpload(file)"
          >
            <a-button size="small">
              <template #icon><UploadOutlined /></template>
              {{ form.image ? '更换图片' : '上传图片' }}
            </a-button>
          </a-upload>
          <a-button
            v-if="form.image"
            size="small"
            danger
            style="margin-left: 6px"
            @click="form.image = ''"
          >删除</a-button>
        </div>
        <div class="ele-text-secondary" style="font-size: 12px; margin-top: 4px">
          适用于颜色类规格，上传颜色色板图片（可选）
        </div>
      </a-form-item>
      <a-form-item label="排序号" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="数值越小越靠前"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-input
          allow-clear
          placeholder="可选"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, onMounted } from 'vue';
  import { message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { addShopSpecValue, updateShopSpecValue } from '@/api/shop/shopSpecValue';
  import type { ShopSpecValue } from '@/api/shop/shopSpecValue/model';
  import { listShopSpec } from '@/api/shop/shopSpec';
  import type { ShopSpec } from '@/api/shop/shopSpec/model';
  import { uploadFile } from '@/api/system/file';
  import { FormInstance } from 'ant-design-vue/es/form';

  const isUpdate = ref(false);

  const props = defineProps<{
    visible: boolean;
    data?: ShopSpecValue | null;
    /** 可传入预设的 specId（从规格组页面跳转过来时） */
    defaultSpecId?: number;
  }>();

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

  const loading = ref(false);
  const formRef = ref<FormInstance | null>(null);

  // 规格组列表
  const specList = ref<ShopSpec[]>([]);
  const specLoading = ref(false);

  const form = reactive<ShopSpecValue>({
    specValueId: undefined,
    specId: undefined,
    specValue: undefined,
    image: '',
    comments: undefined,
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules: Record<string, any> = {
    specId: [{ required: true, message: '请选择所属规格组', trigger: 'change' }],
    specValue: [
      { required: true, type: 'string', message: '请填写规格值', trigger: 'blur' }
    ]
  };

  // 加载规格组列表
  const loadSpecList = async () => {
    specLoading.value = true;
    try {
      specList.value = await listShopSpec({ status: 0 } as any) || [];
    } catch (e) {
      // 忽略
    } finally {
      specLoading.value = false;
    }
  };

  // 规格搜索过滤
  const filterSpec = (input: string, option: any) => {
    return (option?.children?.[0] || '').toLowerCase().includes(input.toLowerCase());
  };

  // 图片上传
  const handleImageUpload = async (file: File) => {
    try {
      const res = await uploadFile(file);
      form.image = res.path;
      message.success('上传成功');
    } catch (e: any) {
      message.error(e.message || '上传失败');
    }
    return false;
  };

  const save = () => {
    if (!formRef.value) return;
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateShopSpecValue : addShopSpecValue;
        saveOrUpdate({ ...form })
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  onMounted(() => {
    loadSpecList();
  });

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignObject(form, props.data);
          if (!form.image) form.image = '';
          isUpdate.value = true;
        } else {
          Object.assign(form, {
            specValueId: undefined,
            specId: props.defaultSpecId,
            specValue: undefined,
            image: '',
            comments: undefined,
            sortNumber: 100
          });
          isUpdate.value = false;
        }
      } else {
        formRef.value?.resetFields();
      }
    },
    { immediate: true }
  );
</script>

<style lang="less" scoped>
  .image-row {
    display: flex;
    align-items: center;
  }
</style>
