<script setup lang="ts">
import { httpCreate, httpUpdate } from "/@/api/serviceParam/exclusive";
import { computed, onMounted, ref } from "vue";
import { useVModel } from "@vueuse/core"

import Modal from "./modal.vue"
import { ElMessage } from "element-plus";

const initialData = { pid: '', name: '', id: '' , companyNo: ''}
const emit = defineEmits(['refresh'])


const props = withDefaults(defineProps<{ data: any; pid: string; visible: boolean, breadcrumb: any[] }>(), { data: {  companyNo: '',name: '', pid: '', id: '' } })
const prefix = computed(() => { const { breadcrumb = [] } = props; return breadcrumb.slice(0).map(({name}) => name).join('/') })

const title = computed<string>(() => data.value.id ? '编辑专属类型' : '添加专属类型')
const visible = useVModel<boolean>(props, 'visible')
const data = useVModel<any>(props, 'data')


const loading = ref(false)
const formRef = ref<any | null>(null)
const rules = { name: [{ required: true, message: '请输入专属类型名称', trigger: 'blur' }] }

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

const tablebtnSize = 'small'

async function onSubmit(){
  try {
    await formRef.value.validate();
    const { id } = props.data
    const parameter = { pid: props.pid || '0', name: data.value.name }
    const isCreate = id === undefined || !id
    if(!isCreate) parameter.id = id
    const api = isCreate ? httpCreate : httpUpdate
    loading.value = true
    const res = await api(parameter)
    loading.value = false
    
    if (res.code === 0) {
      visible.value = false
      ElMessage.success(`${isCreate ? '添加' : '更新'}成功`)
      emit('refresh')
    } else {
      ElMessage.warning(`${isCreate ? '添加' : '更新'}失败`)
    }
  } catch (err) {
    console.log(err);
  }
}
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef">
      <ElFormItem label="名称" prop="name">
        <ElInput v-if="pid === '0' || pid === ''" v-model="data.name" style="width:100%" placeholder="名称"  />
        <ElInput v-else v-model="data.name">
          <template #prepend>{{prefix}}</template>
        </ElInput>
      </ElFormItem>

      <div class="w-full flex justify-end">
        <ElButton type="primary" :loading="loading" @click="onSubmit">保存</ElButton>
      </div>
    </ElForm>
  </ElDialog>
</template>
