<script setup lang="ts">
import { httpGoldlist } from "/@/api/interest/organize";
import { computed, onMounted, ref } from "vue";
import { useVModel } from "@vueuse/core"

const initialData = { price: '', type: '' }

const emit = defineEmits(['submit'])
const props = withDefaults(defineProps<{ data: any; visible: boolean; disabled: boolean }>(), { data: { price: '', type: '' } })

const title = computed(() => data.value.id ? (props.disabled ? '查看规格' : '编辑规格') : '添加规格')
const visible = useVModel(props, 'visible')
const formRef = ref<any | null>(null)
const data = useVModel(props, 'data')
const goldlist = ref<any[]>([])


const rules = { 
  price: [{ required: true, trigger: 'change', message: '金属类型不能为空' }], 
  type:[{ required: true, trigger: 'change', message: '最新价格不能为空' }] 
}

async function requestGoldlist() {
  const res = await httpGoldlist({ size: 100 })
  goldlist.value = res.code === 0 ? res.data : []
}

function handleClose() {
  data.value = { ...initialData }
  visible.value = false
}

async function onSubmit() {
  try {
    await formRef.value.validate();
    emit("submit");
  } catch (err) {
    console.log(err);
  }
}

onMounted(requestGoldlist)
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef" :disabled="disabled" label-width="100px">
      <ElFormItem label="金属类型" prop="type">
        <ElSelect v-model="data.type" style="width:100%">
          <ElOption v-for="gold in goldlist" :key="gold.type" :value="gold.type" :label="gold.type_cn" />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="最新价格" prop="price">
        <ElInput v-model="data.price">
          <template #append>
            元
          </template>
        </ElInput>
      </ElFormItem>
      
      <div class="flex w-full justify-end">
        <ElButton type="primary" @click="onSubmit">保存</ElButton>
      </div>
    </ElForm>
  </ElDialog>
</template>
