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

import Modal from "./modal.vue"

const initialData = {
  companyNo: '',
  name: '',
  pid: '',
  id: ''
}

const emit = defineEmits(['submit'])
const props = withDefaults(
  defineProps<{ data: any; visible: boolean; disabledBusiness:boolean }>(),
  { data: {  companyNo: '',name: '', pid: '', id: '' } }
)

const business = ref<any[]>([])
const title = computed(() => data.value.id ? '编辑组织' : '添加组织')
const visible = useVModel(props, 'visible')
const data = useVModel(props, 'data')

const formRef = ref<any | null>(null)


const rules = {
  companyNo: [ { required: true,message: '请选择业务公司', trigger: 'change' }],
  name: [
    { required: true,message: '请输入组织名称',trigger: 'blur' },
    { min: 1,max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

async function requestBusiness(){
  const res = await httpBusinesslist({ size:100 })
  business.value = res.code === 0 ? res.data.list : []
}

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

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

onMounted(requestBusiness)
</script>


<template>
  <ElDialog v-model="visible" :title="title" center @close="handleClose">
    <ElForm :model="data" :rules="rules" size="small" ref="formRef">
      <ElFormItem label="业务公司" prop="companyNo">
        <ElSelect v-model="data.companyNo" style="width:100%" placeholder="业务公司" :disabled="disabledBusiness">
          <ElOption 
            v-for="item in business" 
            :label="item.company" 
            :value="item.companyNo" 
            :key="item.companyNo" 
          />
        </ElSelect>
      </ElFormItem>

      <ElFormItem label="组织名称" prop="name">
        <ElInput v-model="data.name" style="width:100%" placeholder="组织名称" />
      </ElFormItem>

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