<template>
    <a-modal :open="modal.open" :title="modal.title" :width="1200" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" @ok="handleOk" @cancel="handleCancel">
        <a-card>
            <div style="display: flex; justify-content: space-around;flex-direction: column;">
                <!-- 左侧信息栏 -->
                <div style="margin-top: 20px;display: flex;align-items: center;margin-left: 20px;">
                    <gx-upload v-model="idCardPhotos" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                    <div style="margin-left: 20px;">
                        <p style="font-weight: bold;">
                            <span>{{ customerName }}</span>
                            <span style="margin: 0 50px;">{{ customerGender === '1' ? '男' : '女' }}</span>
                            <span>{{ customerAge }}</span>
                        </p>
                        <p>
                            <span>身份证号：{{ customerIdNumber }}</span>
                            <span style="margin: 0 50px;">手机号：{{ customerContact }}</span>
                        </p>
                        <p>
                            <a-tag color="#2db7f5" v-for="value in customerServiceRecipientCategory" :key="value">
                                {{ value }}
                            </a-tag>
                        </p>
                    </div>
                </div>
                <!-- 右侧 Tab 区域 -->
                <div style="padding: 20px;">
                    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
                        <a-tab-pane v-for="(tab, index) in tabsList" :key="index + 1" :tab="tab" />
                    </a-tabs>

                    <!-- 动态组件 + keep-alive -->
                    <div style="flex: 1; padding: 16px; overflow-y: auto;">
                        <component v-if="currentComponent" :is="currentComponent" ref="dynamicComponentRef"
                            :key="tabsList[activeKey - 1]" :formData="formData" />
                    </div>
                </div>
            </div>
        </a-card>
    </a-modal>
</template>

<script setup>
import GxUpload from '@/components/GxUpload/index.vue'
import { cloneDeep } from 'lodash-es'
import {
    ref,
    computed,
    defineAsyncComponent,
    defineExpose,
    nextTick
} from 'vue'
import { useForm, useModal } from '@/hooks'
import { config } from '@/config'
import apis from '@/apis'
const childData = ref({})
const emit = defineEmits(['ok'])
// 当前 tab key
const activeKey = ref(1)
const idCardPhotos = ref([])
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formData, resetForm } = useForm()

const customerAge=ref('')
const customerContact=ref('')
const customerGender=ref('')
const customerIdNumber=ref('')
const customerName=ref('')
const customerServiceRecipientCategory=ref([])

const cancelText = ref('取消')
const recordId = ref('');
const disabledId=ref('')
// Tab 列表
const tabsList = [
    '基本信息',
    '残疾人信息',
    '联系人信息',
    '附件',
    '病史信息',
    '服务记录',
    '工单图片和视频',
    '联络历史',
    '操作记录',
    '转入转出记录'
]

// 创建 ref 来引用当前动态组件
const dynamicComponentRef = ref(null) // ✅ 用于获取当前组件实例

// 组件映射表（懒加载）
const componentMap = {
    '基本信息': defineAsyncComponent(() => import('./BasicInfo.vue')),
    '残疾人信息': defineAsyncComponent(() => import('./DisabledPersonInfo.vue')),
    '联系人信息': defineAsyncComponent(() => import('./ContactInfo.vue')),
    '附件': defineAsyncComponent(() => import('./Attachments.vue')),
    '病史信息': defineAsyncComponent(() => import('./MedicalHistory.vue')),
    '服务记录': defineAsyncComponent(() => import('./ServiceRecords.vue')),
    '工单图片和视频': defineAsyncComponent(() => import('./WorkOrderMedia.vue')),
    '联络历史': defineAsyncComponent(() => import('./ContactHistory.vue')),
    '操作记录': defineAsyncComponent(() => import('./OperationLog.vue')),
    '转入转出记录': defineAsyncComponent(() => import('./TransferRecords.vue')),
}

// 当前组件
const currentComponent = computed(() => {
    const tabName = tabsList[activeKey.value - 1]
    return componentMap[tabName] || null
})
const getBasicInfo = async () => {
    const { data, success } = await apis.serverObj.getItem(recordId.value).catch()
    if (!success) {
        return
    }
    idCardPhotos.value = data.archive.idCardPhotos ? data.archive.idCardPhotos.map(item => config('http.apiUpload') + item) : []
    return data;
}

// Tab 切换时调用子组件方法
const handleTabChange = async (key) => {
    switch (tabsList[key - 1]) {
        case '基本信息':
            formData.value = await getBasicInfo();
            break;
        case '残疾人信息':
            formData.value = { id: disabledId.value };
            break;
        case '联系人信息':
            formData.value = { customerId: recordId.value };
            break;
        case '附件':
        case '病史信息':
        case '服务记录':
        case '工单图片和视频':
        case '联络历史':
        case '操作记录':
        case '转入转出记录':

            break
    }
}
// 其他方法保持不变...
function handleCreate(record) {
    showModal({
        type: 'create',
        title: '新建项',
    })
    formData.value = record
}

function handleEdit(record = {}) {
    activeKey.value = 1
    showModal({
        type: 'edit',
        title: '详情',
    })
    recordId.value = record.id
    disabledId.value=record.disabledPerson.id
    formData.value = cloneDeep(record)

    customerAge.value=record.age
    customerContact.value=record.contact1
    customerGender.value=record.gender
    customerIdNumber.value=record.identityNo
    customerName.value=record.name
    customerServiceRecipientCategory.value=record.serviceRecipientCategory
    idCardPhotos.value = record.archive.idCardPhotos ? record.archive.idCardPhotos.map(item => config('http.apiUpload') + item) : []
}

function handleOk() {
    // 省略验证逻辑...
}

function handleCancel() {
    hideModal()
}

function onAfterClose() {
    activeKey.value = 1
    formData.value = { archive: { idCardPhotos: [] } }
    hideLoading()
}

defineExpose({
    handleCreate,
    handleEdit,
})
</script>