<!-- 编辑弹窗 -->
<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="orderId">
        <a-input
          allow-clear
          placeholder="请输入关联订单表id"
          v-model:value="form.orderId"
        />
      </a-form-item>
      <a-form-item label="订单标识" name="orderCode">
        <a-input
          allow-clear
          placeholder="请输入订单标识"
          v-model:value="form.orderCode"
        />
      </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="商品封面图"
          name="image">
          <SelectFile
            :placeholder="`请选择图片`"
            :limit="1"
            :data="images"
            @done="chooseImage"
            @del="onDeleteItem"
          />
        </a-form-item>
      <a-form-item label="关联商品id" name="goodsId">
        <a-input
          allow-clear
          placeholder="请输入关联商品id"
          v-model:value="form.goodsId"
        />
      </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="spec">
        <a-input
          allow-clear
          placeholder="请输入商品规格"
          v-model:value="form.spec"
        />
      </a-form-item>
      <a-form-item label="" name="skuId">
        <a-input
          allow-clear
          placeholder="请输入"
          v-model:value="form.skuId"
        />
      </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="totalNum">
        <a-input
          allow-clear
          placeholder="请输入购买数量"
          v-model:value="form.totalNum"
        />
      </a-form-item>
      <a-form-item label="0 未付款 1已付款，2无需付款或占用状态" name="payStatus">
        <a-input
          allow-clear
          placeholder="请输入0 未付款 1已付款，2无需付款或占用状态"
          v-model:value="form.payStatus"
        />
      </a-form-item>
      <a-form-item label="0未使用，1已完成，2已取消，3取消中，4退款申请中，5退款被拒绝，6退款成功，7客户端申请退款" name="orderStatus">
        <a-input
          allow-clear
          placeholder="请输入0未使用，1已完成，2已取消，3取消中，4退款申请中，5退款被拒绝，6退款成功，7客户端申请退款"
          v-model:value="form.orderStatus"
        />
      </a-form-item>
      <a-form-item label="是否免费：0收费、1免费" name="isFree">
        <a-input
          allow-clear
          placeholder="请输入是否免费：0收费、1免费"
          v-model:value="form.isFree"
        />
      </a-form-item>
      <a-form-item label="系统版本 0当前版本 其他版本" name="version">
        <a-input
          allow-clear
          placeholder="请输入系统版本 0当前版本 其他版本"
          v-model:value="form.version"
        />
      </a-form-item>
      <a-form-item label="预约时间段" name="timePeriod">
        <a-input
          allow-clear
          placeholder="请输入预约时间段"
          v-model:value="form.timePeriod"
        />
      </a-form-item>
      <a-form-item label="预定日期" name="dateTime">
        <a-input
          allow-clear
          placeholder="请输入预定日期"
          v-model:value="form.dateTime"
        />
      </a-form-item>
      <a-form-item label="开场时间" name="startTime">
        <a-input
          allow-clear
          placeholder="请输入开场时间"
          v-model:value="form.startTime"
        />
      </a-form-item>
      <a-form-item label="结束时间" name="endTime">
        <a-input
          allow-clear
          placeholder="请输入结束时间"
          v-model:value="form.endTime"
        />
      </a-form-item>
      <a-form-item label="毫秒时间戳" name="timeFlag">
        <a-input
          allow-clear
          placeholder="请输入毫秒时间戳"
          v-model:value="form.timeFlag"
        />
      </a-form-item>
      <a-form-item label="过期时间" name="expirationTime">
        <a-input
          allow-clear
          placeholder="请输入过期时间"
          v-model:value="form.expirationTime"
        />
      </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="用户id" name="userId">
        <a-input
          allow-clear
          placeholder="请输入用户id"
          v-model:value="form.userId"
        />
      </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 { addShopOrderGoods, updateShopOrderGoods } from '@/api/shop/shopOrderGoods';
  import { ShopOrderGoods } from '@/api/shop/shopOrderGoods/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?: ShopOrderGoods | 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<ShopOrderGoods>({
    id: undefined,
    orderId: undefined,
    orderCode: undefined,
    merchantId: undefined,
    merchantName: undefined,
    image: undefined,
    goodsId: undefined,
    goodsName: undefined,
    spec: undefined,
    skuId: undefined,
    price: undefined,
    totalNum: undefined,
    payStatus: undefined,
    orderStatus: undefined,
    isFree: undefined,
    version: undefined,
    timePeriod: undefined,
    dateTime: undefined,
    startTime: undefined,
    endTime: undefined,
    timeFlag: undefined,
    expirationTime: undefined,
    comments: undefined,
    userId: undefined,
    tenantId: undefined,
    updateTime: undefined,
    createTime: undefined
  });

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

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