<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :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="关联商品分类id" name="cid">
        <a-input
          allow-clear
          placeholder="请输入关联商品分类id"
          v-model:value="form.cid"
        />
      </a-form-item>
      <a-form-item label="商品标题" name="title">
        <a-input
          allow-clear
          placeholder="请输入商品标题"
          v-model:value="form.title"
        />
      </a-form-item>
      <a-form-item label="划线价" name="linePrice">
        <a-input
          allow-clear
          placeholder="请输入划线价"
          v-model:value="form.linePrice"
        />
      </a-form-item>
      <a-form-item label="最低价格" name="minPrice">
        <a-input
          allow-clear
          placeholder="请输入最低价格"
          v-model:value="form.minPrice"
        />
      </a-form-item>
      <a-form-item label="最高价格" name="maxPrice">
        <a-input
          allow-clear
          placeholder="请输入最高价格"
          v-model:value="form.maxPrice"
        />
      </a-form-item>
      <a-form-item label="最低积分" name="minIntegral">
        <a-input
          allow-clear
          placeholder="请输入最低积分"
          v-model:value="form.minIntegral"
        />
      </a-form-item>
      <a-form-item label="最高积分" name="maxIntegral">
        <a-input
          allow-clear
          placeholder="请输入最高积分"
          v-model:value="form.maxIntegral"
        />
      </a-form-item>
      <a-form-item label="总库存" name="stockNum">
        <a-input
          allow-clear
          placeholder="请输入总库存"
          v-model:value="form.stockNum"
        />
      </a-form-item>
      <a-form-item label="总销量" name="goodsSales">
        <a-input
          allow-clear
          placeholder="请输入总销量"
          v-model:value="form.goodsSales"
        />
      </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="商品规格(1单规格 2多规格)" name="specType">
        <a-input
          allow-clear
          placeholder="请输入商品规格(1单规格 2多规格)"
          v-model:value="form.specType"
        />
      </a-form-item>
      <a-form-item label="状态：1上架，2下架" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="0">显示</a-radio>
          <a-radio :value="1">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="商品简介" name="desc">
        <a-input
          allow-clear
          placeholder="请输入商品简介"
          v-model:value="form.desc"
        />
      </a-form-item>
      <a-form-item label="商品详细介绍" name="content">
        <a-input
          allow-clear
          placeholder="请输入商品详细介绍"
          v-model:value="form.content"
        />
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input
          allow-clear
          placeholder="请输入排序"
          v-model:value="form.sort"
        />
      </a-form-item>
      <a-form-item label="是否需要发货:1是；0否" name="isFh">
        <a-input
          allow-clear
          placeholder="请输入是否需要发货:1是；0否"
          v-model:value="form.isFh"
        />
      </a-form-item>
      <a-form-item label="积分/金额：1仅积分；2仅金额；3积分/金额" name="isIntegral">
        <a-input
          allow-clear
          placeholder="请输入积分/金额：1仅积分；2仅金额；3积分/金额"
          v-model:value="form.isIntegral"
        />
      </a-form-item>
      <a-form-item label="收货方式：1自提；2快递；3自提/快递" name="shType">
        <a-input
          allow-clear
          placeholder="请输入收货方式：1自提；2快递；3自提/快递"
          v-model:value="form.shType"
        />
      </a-form-item>
      <a-form-item label="" name="updateTime">
        <a-input
          allow-clear
          placeholder="请输入"
          v-model:value="form.updateTime"
        />
      </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 { addThinkGoods, updateThinkGoods } from '@/api/think/thinkGoods';
  import { ThinkGoods } from '@/api/think/thinkGoods/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';

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

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: ThinkGoods | 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 form = reactive<ThinkGoods>({
    goodsId: undefined,
    cid: undefined,
    title: undefined,
    linePrice: undefined,
    minPrice: undefined,
    maxPrice: undefined,
    minIntegral: undefined,
    maxIntegral: undefined,
    stockNum: undefined,
    goodsSales: undefined,
    image: undefined,
    specType: undefined,
    status: undefined,
    desc: undefined,
    content: undefined,
    sort: undefined,
    isFh: undefined,
    isIntegral: undefined,
    shType: undefined,
    createTime: undefined,
    updateTime: undefined,
    thinkGoodsId: undefined,
    thinkGoodsName: '',
    status: 0,
    comments: '',
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    thinkGoodsName: [
      {
        required: true,
        type: 'string',
        message: '请填写名称',
        trigger: 'blur'
      }
    ]
  });

  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;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateThinkGoods : addThinkGoods;
        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'
            })
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
