<template>
    <a-form ref="formRef" :model="formData" :rules="formRules">
        <a-row :gutter="24">
            <!-- 姓名 -->
            <a-col :span="12">
                <a-form-item label="服务对象" name="name">
                    <a-input v-model:value="formData.name" placeholder="请输入姓名" disabled />
                </a-form-item>
            </a-col>

            <!-- 性别 -->
            <a-col :span="12">
                <a-form-item label="服务站点" name="stationId">
                    <a-select v-model:value="formData.stationId" style="width: 100px; margin-right: 8px;">
                        <a-select-option v-for="item in stationList" :key="item.id" :value="item.id">
                            {{ item.name }}
                        </a-select-option>
                    </a-select>
                </a-form-item>
            </a-col>

            <!-- 出生日期 -->
            <a-col :span="12">]
                <a-button @click="ceshi">测试</a-button>
                <a-form-item label="服务项目" name="serviceItems">
                    <!-- 显示已选项目 -->
                
                        <a-tag v-for="item in selectedServices" :key="item.id" closable @close="handleRemove(item)">
                            {{ item.name }}
                        </a-tag>
                        <a-button @click="showModal2">
                            <PlusOutlined /> 添加服务
                        </a-button>
                   
                </a-form-item>
            </a-col>

        </a-row>
    </a-form>
     <a-button type="primary" @click="visible3=true">Open Modal</a-button>
    <a-modal v-model:visible="visible3" title="Basic Modal" :getContainer="() => document.body">
      <p>Some contents...</p>
      <p>Some contents...</p>
      <p>Some contents...</p>
    </a-modal>
    <a-modal v-model:open="modalVisible" title="选择服务项目" @ok="handleConfirm" @cancel="handleCancel2" okText="确认"
        cancelText="取消" :width="600">
        <a-table :dataSource="serviceList" :columns="columns" :row-selection="rowSelection" :pagination="false"
            :loading="loading" size="small">
            <template #bodyCell="{ index, column, record }">
                <template v-if="column.key === 'categoryType'">
                    <span>{{ dicsStore.getDictLabel('PROJECT_TYPE', record.categoryType) }}</span>
                </template>
            </template>
        </a-table>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, defineProps,defineExpose } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal } from '@/hooks'
import { useDicsStore } from '@/store'
import AreaCascader from '@/components/AreaCascader/index.vue'
import { validatePhone, validateEmail, validateIdCard } from '@/utils/validate'
import { getBirthDate, spliceUrl } from '@/utils/util'
import dayjs from 'dayjs'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
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 stationList = ref([])
const visible3=ref(false)
const props = defineProps({
    serviceName: {
        type: String,
        default: ''
    }
})
formRules.value = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    identityType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
    identityNo: [{ required: true, message: '请输入证件号码', trigger: 'blur' }],
    contact1: [{ validator: validatePhone, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
    archive: {
        healthStatus: [{ required: true, message: '请选择健康状况', trigger: 'change' }],
        serviceStatus: [{ required: true, message: '请选择服务状态', trigger: 'change' }],
        homeAreaCodes: [{ required: true, message: '请选择并输入家庭地址', trigger: 'change' }],
        homeDetailAddress: [{ required: true, message: '请输入详细地址', trigger: 'change' }],

    },
}

const dicsStore = useDicsStore()
// 已选中的服务项目（用于显示）
const selectedServices = ref([])

// 模态框控制
const modalVisible = ref(false)
const loading = ref(false)

// 服务项目列表（来自接口）
const serviceList = ref([])

// 表格列定义
const columns = [
    { title: '类型', dataIndex: 'categoryType', key: 'categoryType', align: 'center', width: 100, },
    { title: '分类名称', dataIndex: 'name', key: 'name', align: 'center', width: 180, },
    { title: '项目名称', dataIndex: 'name', key: 'name', align: 'center', },
    { title: '价格', dataIndex: 'price', key: 'price', align: 'center', },
    { title: '简介', dataIndex: 'remark', key: 'remark', align: 'center', },
]
// 模拟接口请求（替换为真实 API）
async function  fetchServices(){
   try {
        const { pageSize, current } = paginationState
        const { success, data, total } = await apis.serviceProject
            .getProjectList({
                pageSize, current,
                ...searchFormData.value,
            })
            .catch(() => {
                throw new Error()
            })

        if (config('http.code.success') === success) {
            listData.value = data
            paginationState.total = total
        }
    } catch (error) {

    }
}

// 表格行选择配置
const rowSelection = {
    type: 'checkbox',
    selectedRowKeys: ref([]),
    onChange: (selectedRowKeys, selectedRows) => {
        rowSelection.selectedRowKeys.value = selectedRowKeys
    },
    getCheckboxProps: (record) => ({
        disabled: false
    })
}

// 打开模态框
 function ceshi(){
    console.log(111)
    modalVisible.value = true
    // 第一次加载数据
    if (serviceList.value.length === 0) {
        fetchServices()
    }
    // 恢复已选中状态
    const selectedIds = selectedServices.value.map(s => s.id)
    rowSelection.selectedRowKeys.value = selectedIds
}

// 移除已选项目
const handleRemove = (item) => {
    selectedServices.value = selectedServices.value.filter(s => s.id !== item.id)
    // 同步到 form（可选）
    form.serviceItems = selectedServices.value.map(s => s.id)
}

// 确认选择
const handleConfirm = () => {
    const selectedRows = serviceList.value.filter(item =>
        rowSelection.selectedRowKeys.value.includes(item.id)
    )
    selectedServices.value = selectedRows
    // 同步到 form 字段（可用于表单提交）
    form.serviceItems = selectedRows.map(s => s.id)
    modalVisible.value = false
}

// 取消
const handleCancel2 = () => {
    modalVisible.value = false
}
/**
 * 编辑
 */
handleEdit()
async function handleEdit(record = {}) {
    formData.value.name = record.name
    try {
        showLoading()
        const { data, success } = await apis.serviceMenu.getServiceSiteList({ pageSize: 100, current: 1 })
        if (!success) {
            hideModal()
            return
        }
        stationList.value = data.map(item => ({ id: item.id, name: item.name }))
    } catch (error) {
        hideModal()
    }
}

/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                let params = {
                    ...formData.value,
                    labels: formData.value.labelsCode ? formData.value.labelsCode.map(item => dicsStore.getDictLabel('Service_Recipient_Category2', item)) : [],
                    birthDate: dayjs(formData.value.birthDate).format('YYYY-MM-DD')
                }
                params.archive.idCardPhotos = formData.value.archive.idCardPhotos.length > 0 ? formData.value.archive.idCardPhotos.map(item => spliceUrl(item)) : [ ]
                params.archive.uploadedDocuments = formData.value.archive.uploadedDocuments.length > 0 ? formData.value.archive.uploadedDocuments.map(item => spliceUrl(item)) : [ ]
                if (formData.value.governmentPurchasedServiceStartDate.length > 0) {
                    params.archive.starGovernmentService = dayjs(formData.value.governmentPurchasedServiceStartDate[0]).format('YYYY-MM-DD')
                    params.archive.endGovernmentService = dayjs(formData.value.governmentPurchasedServiceStartDate[1]).format('YYYY-MM-DD')
                }
                // 单独封装一个同步校验函数
                if (params.identityType === '1' && !isValidIdCard(params.identityNo)) {
                    return message.error('请输入正确的身份证号码')
                }
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.serverObj.createItem(params).catch(() => {
                            throw new Error()
                        })
                        console.log('result', result.code)
                        break
                    case 'edit':
                        console.log(params)
                        result = await apis.serverObj.updateItem(params.id, params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === result?.code) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                hideLoading()
                // message.error(error.message)
            }
        })
        .catch(() => {
            hideLoading()
        })
}
// 提取出生日期方法
const extractBirthDateFromIdCard = () => {
    console.log(111)
    const { identityNo } = formData.value;
    if (!identityNo) {
        formData.value.birthDate = '';
        return;
    }
    console.log(getBirthDate(identityNo))
    formData.value.birthDate = dayjs(getBirthDate(identityNo));
};
function onAreaChange(value, labels) {

    formData.value.archive.homeAreaLabels = [...labels]
}
function onAreaHoldChange(value, labels) {

    formData.value.archive.houseAreaLabels = [...labels]
}
function handleGetLng(obj) {
    formData.value.lat = obj.lat
    formData.value.lag = obj.lng
}
// 修复自定义上传方法
const handleCustomRequest = async (options) => {
    const { file, onProgress, onSuccess, onError } = options;

    try {
        const formData = new FormData();
        formData.append('file', file);
        const { data } = await apis.common.uploadFile(formData);
        const fullUrl = config('http.apiUpload') + data;
        console.log(fullUrl)
    } catch (err) {
        message.error('上传失败');
    }
};
/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

/**
 * 关闭后
 */
function onAfterClose() {
    resetForm()
    formData.value.archive = {}
    hideLoading()
}

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

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