<!-- 编辑弹窗 -->
<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="类型 1实物商品 2虚拟商品" name="type">
        <a-input
          allow-clear
          placeholder="请输入类型 1实物商品 2虚拟商品"
          v-model:value="form.type"
        />
      </a-form-item>
      <a-form-item label="商品编码" name="code">
        <a-input
          allow-clear
          placeholder="请输入商品编码"
          v-model:value="form.code"
        />
      </a-form-item>
      <a-form-item label="商品标题" name="goodsName">
        <a-input
          allow-clear
          placeholder="请输入商品标题"
          v-model:value="form.goodsName"
        />
      </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="content">
        <a-input
          allow-clear
          placeholder="请输入商品详情"
          v-model:value="form.content"
        />
      </a-form-item>
      <a-form-item label="父级分类ID" name="parentId">
        <a-input
          allow-clear
          placeholder="请输入父级分类ID"
          v-model:value="form.parentId"
        />
      </a-form-item>
      <a-form-item label="商品分类ID" name="categoryId">
        <a-input
          allow-clear
          placeholder="请输入商品分类ID"
          v-model:value="form.categoryId"
        />
      </a-form-item>
      <a-form-item label="父级分类" name="parentName">
        <a-input
          allow-clear
          placeholder="请输入父级分类"
          v-model:value="form.parentName"
        />
      </a-form-item>
      <a-form-item label="当前分类" name="categoryName">
        <a-input
          allow-clear
          placeholder="请输入当前分类"
          v-model:value="form.categoryName"
        />
      </a-form-item>
      <a-form-item label="三级分类" name="childrenName">
        <a-input
          allow-clear
          placeholder="请输入三级分类"
          v-model:value="form.childrenName"
        />
      </a-form-item>
      <a-form-item label="商品规格 0单规格 1多规格" name="specs">
        <a-input
          allow-clear
          placeholder="请输入商品规格 0单规格 1多规格"
          v-model:value="form.specs"
        />
      </a-form-item>
      <a-form-item label="货架" name="position">
        <a-input
          allow-clear
          placeholder="请输入货架"
          v-model:value="form.position"
        />
      </a-form-item>
      <a-form-item label="单位名称 (个)" name="unitName">
        <a-input
          allow-clear
          placeholder="请输入单位名称 (个)"
          v-model:value="form.unitName"
        />
      </a-form-item>
      <a-form-item label="进货价格" name="price">
        <a-input
          allow-clear
          placeholder="请输入进货价格"
          v-model:value="form.price"
        />
      </a-form-item>
      <a-form-item label="销售价格" name="salePrice">
        <a-input
          allow-clear
          placeholder="请输入销售价格"
          v-model:value="form.salePrice"
        />
      </a-form-item>
      <a-form-item label="库存计算方式(10下单减库存 20付款减库存)" name="deductStockType">
        <a-input
          allow-clear
          placeholder="请输入库存计算方式(10下单减库存 20付款减库存)"
          v-model:value="form.deductStockType"
        />
      </a-form-item>
      <a-form-item label="封面图" name="files">
        <a-input
          allow-clear
          placeholder="请输入封面图"
          v-model:value="form.files"
        />
      </a-form-item>
      <a-form-item label="销量" name="sales">
        <a-input
          allow-clear
          placeholder="请输入销量"
          v-model:value="form.sales"
        />
      </a-form-item>
      <a-form-item label="库存" name="stock">
        <a-input
          allow-clear
          placeholder="请输入库存"
          v-model:value="form.stock"
        />
      </a-form-item>
      <a-form-item label="商品重量" name="goodsWeight">
        <a-input
          allow-clear
          placeholder="请输入商品重量"
          v-model:value="form.goodsWeight"
        />
      </a-form-item>
      <a-form-item label="消费赚取积分" name="gainIntegral">
        <a-input
          allow-clear
          placeholder="请输入消费赚取积分"
          v-model:value="form.gainIntegral"
        />
      </a-form-item>
      <a-form-item label="推荐" name="recommend">
        <a-input
          allow-clear
          placeholder="请输入推荐"
          v-model:value="form.recommend"
        />
      </a-form-item>
      <a-form-item label="商户ID" name="merchantId">
        <a-input
          allow-clear
          placeholder="请输入商户ID"
          v-model:value="form.merchantId"
        />
      </a-form-item>
      <a-form-item label="商户名称" name="merchantName">
        <a-input
          allow-clear
          placeholder="请输入商户名称"
          v-model:value="form.merchantName"
        />
      </a-form-item>
      <a-form-item label="状态（0：未上架，1：上架）" name="isShow">
        <a-input
          allow-clear
          placeholder="请输入状态（0：未上架，1：上架）"
          v-model:value="form.isShow"
        />
      </a-form-item>
      <a-form-item label="状态, 0上架 1待上架 2待审核 3审核不通过" 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="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </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="用户ID" name="userId">
        <a-input
          allow-clear
          placeholder="请输入用户ID"
          v-model:value="form.userId"
        />
      </a-form-item>
      <a-form-item label="是否删除, 0否, 1是" name="deleted">
        <a-input
          allow-clear
          placeholder="请输入是否删除, 0否, 1是"
          v-model:value="form.deleted"
        />
      </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 { addShopGoods, updateShopGoods } from '@/api/shop/shopGoods';
  import { ShopGoods } from '@/api/shop/shopGoods/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?: ShopGoods | 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<ShopGoods>({
    goodsId: undefined,
    type: undefined,
    code: undefined,
    goodsName: undefined,
    image: undefined,
    content: undefined,
    parentId: undefined,
    categoryId: undefined,
    parentName: undefined,
    categoryName: undefined,
    childrenName: undefined,
    specs: undefined,
    position: undefined,
    unitName: undefined,
    price: undefined,
    salePrice: undefined,
    deductStockType: undefined,
    files: undefined,
    sales: undefined,
    stock: undefined,
    goodsWeight: undefined,
    gainIntegral: undefined,
    recommend: undefined,
    merchantId: undefined,
    merchantName: undefined,
    isShow: undefined,
    status: undefined,
    comments: undefined,
    sortNumber: undefined,
    userId: undefined,
    deleted: undefined,
    tenantId: undefined,
    createTime: undefined,
    updateTime: undefined,
    shopGoodsId: undefined,
    shopGoodsName: '',
    status: 0,
    comments: '',
    sortNumber: 100
  });

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

  // 表单验证规则
  const rules = reactive({
    shopGoodsName: [
      {
        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 ? updateShopGoods : addShopGoods;
        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>
