<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加餐饮公司关系' : '编辑餐饮公司关系'"
    width="30%"
    align-center
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <ElFormItem label="关系人" prop="name">
        <ElInput v-model="formData.name" maxlength="20" type="text" />
      </ElFormItem>
      <ElFormItem label="餐饮公司" prop="company_id">
        <ElSelect v-model="formData.company_id" :empty-values="[0]" :value-on-clear="0">
          <ElOption
            v-for="item in selectList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="手机号" prop="phone">
        <ElInput v-model="formData.phone" maxlength="20" type="text" />
      </ElFormItem>
      <ElFormItem label="微信号" prop="weixin">
        <ElInput v-model="formData.weixin" maxlength="20" type="text" />
      </ElFormItem>
      <ElFormItem label="职位" prop="position">
        <ElInput v-model="formData.position" maxlength="20" type="text" />
      </ElFormItem>
      <ElFormItem label="备注" prop="memo" >
        <ElInput v-model="formData.memo" maxlength="255" type="textarea" :rows="4"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleSubmit">提交</ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { companyRelationApi } from '@/api/companyRelationApi'

  interface Props {
    visible: boolean
    type: string
    userData?: any
    selectList: Api.Common.SelectRelationInfo[]
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive<Form.CompanyContact>({
    id: 0,
    name: '', // 关系人,
    company_id: 0, // 餐饮公司ID,
    phone: '', // 手机号,
    weixin: '', // 微信号,
    position: '', // 职位,
    memo: '' // 备注,
  })

  // 表单验证规则
  const rules: FormRules = {
    name: [
      { required: true, message: '请输入关系人', trigger: 'blur' },
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    company_id: [{ required: true, message: '请输入餐饮公司', trigger: 'blur' }],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    weixin: [
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    position: [
      { required: true, message: '请输入职位', trigger: 'blur' },
      { max: 20, message: '长度最多20个字符', trigger: 'blur' }
    ],
    memo: [{ max: 255, message: '长度最多255个字符', trigger: 'blur' }]
  }

  const isEdit = ref(false)
  // 初始化表单数据
  const initFormData = () => {
    isEdit.value = props.type === 'edit' && props.userData
    const row = props.userData
    Object.assign(formData, {
      id: props.userData.id,
      name: isEdit.value ? row.name || '' : '',
      phone: isEdit.value ? row.phone || '' : '',
      company_id: isEdit.value ? row.company_id : 0,
      weixin: isEdit.value ? row.weixin || '' : '',
      position: isEdit.value ? row.position || '' : '',
      memo: isEdit.value ? row.memo || '' : ''
    })
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.userData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return
    await formRef.value.validate((valid) => {
      if (valid) {
        if (isEdit.value) {
          companyRelationApi.edit(formData).then(() => {
            dialogVisible.value = false
            emit('submit')
          })
        } else {
          companyRelationApi.add(formData).then(() => {
            dialogVisible.value = false
            emit('submit')
          })
        }
      }
    })
  }
</script>
