<template>
    <div class="edit-add-detail">
        <div v-loading="detailLoading" class="form-content" element-loading-text="加载中...">
            <div class="page-form">
                <!-- 主要内容区域 -->
                <el-form
                    ref="addEditFormRef"
                    :model="addEditForm"
                    :rules="addEditFormRules"
                    size="large"
                    label-position="left"
                    label-suffix="："
                >
                    <el-collapse v-model="activeCollapse">
                        <!-- 基本情况 -->
                        <div class="content-section" id="basic-info">
                            <el-collapse-item name="basic-info">
                                <template #title>
                                    <div class="section-title">
                                        <el-icon><Document /></el-icon>
                                        <span>企业基本信息</span>
                                    </div>
                                </template>
                                <div class="section-content">
                                    <el-descriptions :column="2" border>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span class="required-asterisk">*</span>
                                                企业名称
                                            </template>
                                            <el-form-item prop="enterpriseName">
                                                {{ addEditForm.enterpriseName }}
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span class="required-asterisk">*</span>姓名
                                            </template>
                                            <el-form-item prop="fullname">
                                                <el-input
                                                    v-model="addEditForm.fullname"
                                                    placeholder="请输入"
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span class="required-asterisk">*</span>
                                                联系方式
                                            </template>
                                            <el-form-item prop="mobile">
                                                <el-input
                                                    v-model="addEditForm.mobile"
                                                    placeholder="请输入"
                                                >
                                                </el-input>
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label>
                                                <span class="required-asterisk">*</span>
                                                职务
                                            </template>
                                            <el-form-item prop="duties">
                                                <el-input
                                                    v-model="addEditForm.duties"
                                                    placeholder="请选择"
                                                />
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label> 性别 </template>
                                            <el-form-item prop="sex">
                                                <el-select v-model="addEditForm.sex" placeholder="请选择">
                                                    <el-option
                                                        v-for="item in options"
                                                        :key="item.value"
                                                        :label="item.label"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </el-form-item>
                                        </el-descriptions-item>

                                        <el-descriptions-item>
                                            <template #label> 出生日期 </template>
                                            <el-form-item prop="birthday">
                                                <el-date-picker
                                                    v-model="addEditForm.birthday"
                                                    clearable
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请输入"
                                                />
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label> 学历 </template>
                                            <el-form-item prop="education">
                                                <el-input
                                                    v-model="addEditForm.education"
                                                    clearable
                                                    placeholder="请输入"
                                                />
                                            </el-form-item>
                                        </el-descriptions-item>
                                        <el-descriptions-item>
                                            <template #label>
                                                邮箱
                                            </template>
                                            <el-form-item prop="email">
                                                <el-input
                                                    v-model="addEditForm.email"
                                                    clearable
                                                    placeholder="请输入"
                                                />
                                            </el-form-item>
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </div>
                            </el-collapse-item>
                        </div>
                    </el-collapse>
                </el-form>
            </div>
        </div>
        <div class="footer">
            <el-button type="primary" @click="handleSubmit" :loading="btnLoading">提 交</el-button>
            <el-button @click="handleCancel">关 闭</el-button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { useRoute, useRouter } from 'vue-router'
import { dataUpdate, dataAdd, dataDetail } from '@/api/supplierMonitor/PersonalInfoManage/userInfo'

interface AddEditForm {
    [key: string]: string | number | undefined | null | any
}

interface FileItem {
    id?: string
    fileId?: string
    status: string

    [key: string]: any
}

const route = useRoute()
const router = useRouter()
const options = [
    { value: '男', label: '男' },
    { value: '女', label: '女' }
]
// 获取路由参数
const userDetail = ref<any>({})
const editId = ref((route.query.id as string) || '')
const isEdit = computed(() => !!editId.value)
const detailLoading = ref(false) // 详情加载状态
const btnLoading = ref<Boolean>(false)
// 表单相关
const activeCollapse = ref('basic-info') // 当前激活的折叠面板
const addEditFormRef = ref<FormInstance>()
const addEditFormRules = reactive<FormRules>({
    fullname: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' },
        {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/,
            message: '姓名只能包含中文和英文字母',
            trigger: 'blur'
        }
    ],
    mobile: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        {
            pattern: /^(1[3-9]\d{9}|0\d{2,3}-?\d{7,8})$/,
            message: '请输入正确的手机号或座机号格式',
            trigger: 'blur'
        }
    ],
    duties: [{ required: true, message: '请输入职务', trigger: 'blur' }],
    status: [{ required: true, message: '请输入组织机构代码', trigger: 'blur' }],
    email: [
        {
            pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
            message: '请输入正确的邮箱格式',
            trigger: 'blur'
        }
    ]
})
const addEditForm = reactive<AddEditForm>({
    enterpriseName: '',
    enterpriseId: '',
    enterpriseCode: '',
    fullname: '',
    mobile: '',
    duties: '',
    sex: '',
    birthday: '',
    education: '',
    email: '',
    status:'1',
})

// 获取详情逻辑
const getDetail = async (id: string) => {
    detailLoading.value = true
    try{
        const { ...rest } = (await dataDetail(id)) as AddEditForm
        Object.assign(addEditForm, {
            ...rest
        })
    }
    finally{
        detailLoading.value = false
    }
}

const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                const value = addEditForm.id
                    ? await dataUpdate({ ...addEditForm })
                    : await dataAdd({ ...addEditForm })
                if (value.state) {
                    ElMessage.success('保存成功')
                    handleCancel()
                }
            } finally {
                btnLoading.value = false // 无论成功或失败，都关闭加载状态
            }
        } else {
            ElMessage.warning(
                `有${Object.keys(object || {}).length}个字段未通过校验，请正确填写表单内容。`
            )
        }
    })
}

const handleCancel = () => {
    router.push({ name: 'userInfo' })
}
onMounted(() => {
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }
    addEditForm.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
    addEditForm.enterpriseId = userDetail.value.userDetail.org[0].orgId
    addEditForm.enterpriseName = userDetail.value.userDetail.org[0].orgName
    if (route.query.id) {
        getDetail(route.query.id)
    }
})

onUnmounted(() => {})
</script>

<style lang="scss" scoped></style>
