<script setup lang="ts">
import { ref, unref, computed } from "vue";
import { ElForm } from "element-plus";
import { goodTypeOptions } from "../config/_options";
import { ladderFormRules } from "../config/_rules";
import { ImageUpload } from "/@/components/Upload";

import { AmountInput, NumberInput } from "/@/components/Input";
import GoodClass from "/@/components/GoodClass";

const emit = defineEmits(["push", "update"]);

const defaultData = {
  budget_price: "0.00",
  good_type: "1",
  good_name: "",
  cat_info: [],
  num: "0"
};

const isUpdate = ref(false);
const visible = ref(false);
const formRef = ref<InstanceType<typeof ElForm> | null>(null);
const updateIndex = ref("0");

const formData = ref<Record<string, any>>({ ...defaultData });

const title = computed(() => {
  return isUpdate.value ? "修改商品参数" : "添加商品参数";
});

function handleConfirm() {
  formRef.value.validate(isValid => {
    if (!isValid) return;

    emit(
      isUpdate.value ? "update" : "push",
      unref(formData),
      unref(updateIndex)
    );

    visible.value = false;
  });
}

defineExpose({
  onDisplay: (data?: Record<string, any>, index = "0") => {
    if (data) {
      data.cat_info = [];
      formData.value = data;
      updateIndex.value = index;
    }

    visible.value = true;
    isUpdate.value = !!data;
  }
});
</script>

<template>
  <ElDialog
    center
    :title="title"
    v-model="visible"
    @close="() => (formData = { ...defaultData })"
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="ladderFormRules"
      label-width="100px"
      size="small"
    >
      <ElFormItem label="类型" prop="key">
        <ElInput v-model="formData.key" placeholder="类型" />
      </ElFormItem>

      <ElFormItem label="类型值" prop="value">
        <ElInput placeholder="类型值" v-model="formData.value" />
      </ElFormItem>

      <ElFormItem>
        <div class="w-full flex justify-end">
          <ElButton type="primary" @click="handleConfirm">保存</ElButton>
          <ElButton @click="() => (visible = false)">取消</ElButton>
        </div>
      </ElFormItem>
    </ElForm>
  </ElDialog>
</template>
