<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-select
                                                    v-model="addEditForm.duties"
                                                    placeholder="请选择"
                                                    clearable
                                                >
                                                    <el-option
                                                        v-for="item in getDictionaryByCode(
                                                            'ryxx-rylx'
                                                        )"
                                                        :key="item.value"
                                                        :label="item.name"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </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 getDictionaryByCode(
                                                            'ryxx-xb'
                                                        )"
                                                        :key="item.value"
                                                        :label="item.name"
                                                        :value="item.value"
                                                    >
                                                    </el-option>
                                                </el-select>
                                            </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-item :span="2">
                                            <template #label> 证书附件 </template>
                                            <el-form-item prop="files">
                                                <ChunkFileUploader
                                                    type="button"
                                                    :fileList="addEditForm.files"
                                                    :previewAndDownload="false"
                                                    :typeRegularArr="typeRegularArr"
                                                    @change="handleFileChange"
                                                    @startUpload="handleStartUpload"
                                                >
                                                </ChunkFileUploader>
                                            </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'
import CustomUploader from '@/components/CustomUploader/index.vue'
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 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}$/,
            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',
    files: []
})

// 附件上传
const typeRegularArr = [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'txt',
    'pdf', // 文档格式
    'jpg',
    'png',
    'gif' // 图像文件
]
const handleStartUpload = () => {
    btnLoading.value = true
}

const handleFileChange = (file: [FileItem]) => {
    addEditForm.files = file.map((item) => ({
        ...item,
        // 确保文件数据格式统一
        id: item.fileId || item.id,
        fileId: item.fileId || item.id,
        fileName: item.fileName || item.name,
        name: item.fileName || item.name
    }))
    btnLoading.value = !file.every((item: FileItem) => item.status === 'success')
}
// 获取详情逻辑
const getDetail = async (id: string) => {
    detailLoading.value = true
    try {
        const { files, ...rest } = (await dataDetail(id)) as AddEditForm
        Object.assign(addEditForm, {
            ...rest,
            files: formatFilesForUploader(files || [])
        })
    } finally {
        detailLoading.value = false
    }
}

// 格式化文件数据以匹配 ChunkFileUploader 组件期望的格式
const formatFilesForUploader = (files: any[]) => {
    return files.map((file) => ({
        id: file.fileId || file.id,
        fileId: file.fileId || file.id,
        fileName: file.fileName || file.name,
        name: file.fileName || file.name,
        size: file.size || file.byteCount,
        byteCount: file.size || file.byteCount,
        extensionName: file.extensionName || file.fileExt,
        fileType: file.fileType,
        status: 'success', // 已存在的文件状态设为成功
        _prevProgress: 1 // 进度设为100%
    }))
}

const handleSubmit = () => {
    addEditFormRef.value?.validate(async (valid: boolean, object: any) => {
        if (valid) {
            try {
                btnLoading.value = true
                // 格式化文件数据以匹配后端期望的格式
                const submitData = {
                    ...addEditForm,
                    files: addEditForm.files.map((file: any) => ({
                        fileId: file.fileId || file.id,
                        fileName: file.fileName || file.name,
                        size: file.size || file.byteCount,
                        extensionName: file.extensionName,
                        fileType: file.fileType
                    }))
                }
                const value = addEditForm.id
                    ? await dataUpdate(submitData)
                    : await dataAdd(submitData)
                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>
