<template>
    <el-dialog :model-value="modelValue" :title="title" :width="width" :close-on-click-modal="false" append-to-body
        @open="onOpen" @close="onClose">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
            <el-form-item label="经纪人" prop="agentName">
                <el-input v-model="form.agentName" placeholder="请输入经纪人名字" maxlength="50" show-word-limit clearable />
            </el-form-item>

            <el-form-item label="公会" prop="guildName">
                <el-input v-model="form.guildName" placeholder="请输入公会名字" maxlength="50" show-word-limit clearable />
            </el-form-item>

            <!-- 自由输入的联系工具（可不填） -->
            <el-form-item label="联系工具" prop="contactTool">
                <el-input v-model="form.contactTool" placeholder="例如：微信 / Telegram / 邮箱 / WhatsApp / 其它（可不填）"
                    maxlength="30" show-word-limit clearable />
            </el-form-item>

            <!-- 联系方式：仅当联系工具已填写时才必填 -->
            <el-form-item label="联系方式" prop="contact">
                <el-input v-model="form.contact" placeholder="请输入联系方式（当填写了联系工具时必填）" maxlength="100" show-word-limit
                    clearable />
            </el-form-item>
        </el-form>

        <template #footer>
            <el-button @click="onCancel">取 消</el-button>
            <el-button type="primary" :loading="submitting" @click="onConfirm">保 存</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue'

const props = defineProps({
    modelValue: { type: Boolean, default: false },
    title: { type: String, default: '设置经纪信息' },
    width: { type: [String, Number], default: '480px' },
    // 初始值：新增 contactTool 字段（可为空）
    model: {
        type: Object,
        default: () => ({
            agentName: '',
            guildName: '',
            contactTool: '',
            contact: ''
        })
    }
})

const emits = defineEmits(['update:modelValue', 'save', 'open'])

const formRef = ref()
const submitting = ref(false)
const form = reactive({
    agentName: '',
    guildName: '',
    contactTool: '',
    contact: ''
})

function syncFromProps() {
    form.agentName = props.model?.agentName ?? ''
    form.guildName = props.model?.guildName ?? ''
    form.contactTool = props.model?.contactTool ?? ''
    form.contact = props.model?.contact ?? ''
}

watch(() => props.modelValue, v => { if (v) syncFromProps() })

function onOpen() {
    syncFromProps()
    emits('open')
}
function onClose() { emits('update:modelValue', false) }
function onCancel() { onClose() }

const rules = {
    agentName: [{ required: true, message: '请输入经纪人名字', trigger: 'blur' }],
    guildName: [{ required: true, message: '请输入公会名字', trigger: 'blur' }],
    // contactTool 不必填，不加 required
    contact: [
        {
            validator: (rule, value, cb) => {
                const tool = (form.contactTool || '').trim()
                const contact = (value || '').trim()
                if (tool && !contact) {
                    return cb(new Error('已填写联系工具时，联系方式为必填'))
                }
                cb()
            },
            trigger: ['blur', 'change']
        }
    ]
}

async function onConfirm() {
    try {
        submitting.value = true
        await formRef.value?.validate()

        // 提交前做一次 trim
        const payload = {
            agentName: form.agentName.trim(),
            guildName: form.guildName.trim(),
            contactTool: form.contactTool.trim(),
            contact: form.contact.trim()
        }
        emits('save', payload)
        onClose()
    } finally {
        submitting.value = false
    }
}
</script>

<style scoped>
:deep(.el-dialog__body) {
    padding-top: 12px;
}
</style>