<template>
    <a-modal :open="modal.open" :title="modal.title" :width="1000" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" @ok="handleOk" @cancel="handleCancel">
        <a-card>
            <div style="display: flex;justify-content: space-around;">
                <div
                    style="width:280px;margin-top: 20px;border-right: 1px solid #f0f0f0;display: flex;flex-direction: column;align-items: center;">
                    <gx-upload v-model="formData.imgList" accept-types=".jpg,.png,.webp" :fileNumber="1" />
                    <div>
                        <p>{{ formData.name }}{{ formData.gender }}{{ formData.age }}</p>
                        <p>身份证号：{{ formData.idNumber }}</p>
                        <p>手机号：{{ formData.contact1 }}</p>
                        <!-- <p>联系人：{{ formData.contactman }}</p>
                        <p>联系方式：{{ formData.contact1 }}</p> -->
                        <p><a-tag color="#2db7f5">#2db7f5</a-tag></p>
                    </div>

                </div>
                <div style="width: calc(100% - 280px);padding: 20px;">
                    <!-- Tab 页签 -->
                    <a-tabs v-model:activeKey="activeKey" @change="handleTabChange">
                        <a-tab-pane v-for="(tab, index) in tabsList" :key="index" :tab="tab" />
                    </a-tabs>
                    <!-- 动态组件区域 -->
                    <div style="flex: 1; padding: 16px; overflow-y: auto;">
                        <keep-alive>
                            <component v-if="currentComponent" :is="currentComponent" :ref="activeKey"
                                :key="activeKey" />
                        </keep-alive>
                    </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, getCurrentInstance, nextTick } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { useDicsStore } from '@/store'
const emit = defineEmits(['ok'])
const activeKey = ref('1')
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const cancelText = ref('取消')
const imgList = ref([])
const tabsList = ['基本信息', '残疾人信息', '联系人信息', '附件', '病史信息', '服务记录', '工单图片和视频', '联络历史', '操作记录', '转入转出记录']


// 组件映射表：tab 名称 -> 异步组件（懒加载）
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];
    return componentMap[tabName];
});

// 当 tab 切换时触发
const handleTabChange = (key) => {
    // 等待组件渲染完成后再调用方法
    nextTick(() => {
        const tabName = tabsList[key];
        const componentName = componentMap[tabName];
        if (componentName) {
            // 获取组件实例
            const instance = proxy.$refs[key];
            if (instance && typeof instance.onTabClick === 'function') {
                instance.onTabClick(); // 调用组件的 onTabClick 方法
            } else if (instance && typeof instance.loadData === 'function') {
                instance.loadData(); // 或者 loadData
            }
        }
    });
};

// 兼容 setup 中使用 $refs
const { proxy } = getCurrentInstance();
/**
 * 新建
 */
function handleCreate(record) {
    showModal({
        type: 'create',
        title: '新建项',
    })
    formData.value = record
}

/**
 * 编辑
 */
function handleEdit(record = {}) {
    console.log('record', record)
    showModal({
        type: 'edit',
        title: '编辑项',
    })
    formRecord.value = record
    formData.value = cloneDeep(record)
}
const callback = (val) => {
    console.log(val);
};
/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                const params = {
                    ...formData.value,
                }
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.serverObj.createItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.serverObj.updateItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.code) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}

/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    hideLoading()
}

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

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