<script setup lang="ts">
import { ref, unref, computed } from "vue";
import { ElForm } from "element-plus";
import { FormRules } from "element-plus";

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

const defaultData = {
  budget_price: "0.00",
  good_type: "1",
  good_name: "",
  cat_info: [],
  num: "0"
};
const ladderFormRules: FormRules = {
  key: {
    trigger: "change",
    required: true,
    message: "请选择商品类型"
  },
  value: {
    trigger: "change",
    required: true,
    message: "请选择单位"
  }
};
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"
    :width="'500px'"
    @close="() => (formData = { ...defaultData })"
  >
    <ElForm
      ref="formRef"
      :model="formData"
      :rules="ladderFormRules"
      label-width="70px"
    >
      <ElFormItem label="类型" prop="key">
        <ElInput v-model="formData.key" placeholder="类型" />
      </ElFormItem>

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

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