<template>
    <a-modal :open="modal.open" :title="modal.title" :width="800" :confirm-loading="modal.confirmLoading"
        :after-close="onAfterClose" :cancel-text="cancelText" @ok="handleOk" @cancel="handleCancel">
        <a-spin tip="Loading..." :spinning="spining">
            <a-card>
                <a-form ref="formRef" :model="formData" :rules="formRules">
                    <a-tabs v-model:activeKey="activeKey">
                        <!-- 基本信息 -->
                        <a-tab-pane key="1" tab="基本信息">
                            <a-row :gutter="24">
                                
                                <!-- 社保卡号 -->
                                <a-col :span="12">
                                    <a-form-item label="社保卡号" name="socialSecurityCardNumber">
                                        <a-input v-model:value="formData.archive.socialSecurityCardNumber"
                                            placeholder="请输入社保卡号" />
                                    </a-form-item>
                                </a-col>


                                <!-- 政府购买服务开始时间 -->
                                <a-col :span="12">
                                    <a-form-item label="政府购买服务时间" name="governmentPurchasedServiceStartDate">
                                        <a-range-picker v-model:value="formData.governmentPurchasedServiceStartDate"
                                            placeholder="请选择政府购买服务时间" style="width: 100%;" />
                                    </a-form-item>
                                </a-col>

                                <!-- 健康状况 -->
                                <a-col :span="12">
                                    <a-form-item label="健康状况" :name="['archive', 'healthStatus']">
                                        <a-select v-model:value="formData.archive.healthStatus" placeholder="请选择健康状况"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Health_Condition"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 服务状态 -->
                                <a-col :span="12">
                                    <a-form-item label="服务状态" :name="['archive', 'serviceStatus']">
                                        <a-select v-model:value="formData.archive.serviceStatus" placeholder="请选择服务状态">
                                            <a-select-option v-for="item in dicsStore.dictOptions.SERVICE_STATUS"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 生存状态 -->
                                <a-col :span="12">
                                    <a-form-item label="生存状态" :name="['archive', 'survivalStatus']">
                                        <a-select v-model:value="formData.archive.survivalStatus" placeholder="请选择生存状态">
                                            <a-select-option v-for="item in dicsStore.dictOptions.LIVING_STATUS"
                                                :key="item.dval" :value="item.dval">{{
                                                    item.introduction }}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 服务形式 -->
                                <a-col :span="12">
                                    <a-form-item label="服务形式" name="archive.serviceForm">
                                        <a-select v-model:value="formData.archive.serviceForm" placeholder="请选择服务形式"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Service_Format"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 护理等级 -->
                                <a-col :span="24">
                                    <a-form-item label="护理等级" name="archive.nursingLevel">
                                        <a-select v-model:value="formData.archive.nursingLevel" placeholder="请选择护理等级"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Care_Level"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <!-- 家庭地址 -->
                                <a-col :span="12">
                                    <a-form-item label="家庭地址" :name="['archive', 'homeAreaCodes']">
                                        <AreaCascader v-model:value="formData.archive.homeAreaCodes"
                                            @change="onAreaChange" ref="areaCascaderRef" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item label="详细地址" :name="['archive', 'homeDetailAddress']">
                                        <a-input v-model:value="formData.archive.homeDetailAddress"
                                            placeholder="请输入详细地址" />
                                    </a-form-item>
                                </a-col>
                                <!-- 户口所在地 -->
                                <a-col :span="12" >
                                    <a-form-item label="户口所在地" name="houseAreaCodes">
                                        <AreaCascader v-model:value="formData.archive.houseAreaCodes"
                                            @change="onAreaHoldChange" ref="houseAreaRef" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="12">
                                    <a-form-item label="详细地址" name="householdDetailAddress">
                                        <a-input v-model:value="formData.archive.householdDetailAddress"
                                            placeholder="请输入详细地址" />
                                    </a-form-item>
                                </a-col>

                            </a-row>

                        </a-tab-pane>

                        <!-- 家庭信息 -->
                        <a-tab-pane key="2" tab="地图定位">
                            <a-row :gutter="24">
                                <!-- 经度 -->
                                <a-col :span="12">
                                    <a-form-item label="经度" name="lat">
                                        <a-input-number v-model:value="formData.archive.lat" placeholder="请输入经度"
                                            style="width: 100%;" />
                                    </a-form-item>
                                </a-col>

                                <!-- 纬度 -->
                                <a-col :span="12">
                                    <a-form-item label="纬度" name="lag">
                                        <a-input-number v-model:value="formData.archive.lag" placeholder="请输入纬度"
                                            style="width: 100%;" />
                                    </a-form-item>
                                </a-col>
                                <gx-map @handleGetLng="handleGetLng" />
                            </a-row>

                        </a-tab-pane>

                        <!-- 更多 -->
                        <a-tab-pane key="3" tab="更多">
                            <a-row :gutter="24">

                                <a-col :span="8">
                                    <a-form-item label="联系状态" name="contactStatus">
                                        <a-select v-model:value="formData.archive.contactStatus" placeholder="联系状态"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.CONTACT_STATUS"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>


                                <!-- 居住情况 -->
                                <a-col :span="8">
                                    <a-form-item label="居住情况" name="livingSituation">
                                        <a-select v-model:value="formData.archive.livingSituation" placeholder="请选择居住情况"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Living_Situation"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 子女情况 -->
                                <a-col :span="8">
                                    <a-form-item label="子女情况" name="childrenSituation">
                                        <a-select v-model:value="formData.archive.childrenSituation"
                                            placeholder="请选择子女情况" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.CHILDREN_STATE"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 统计分类 -->
                                <a-col :span="8">
                                    <a-form-item label="统计分类" name="statisticsCategory">
                                        <a-select v-model:value="formData.archive.statisticsCategory"
                                            placeholder="请选择统计分类" allow-clear>
                                            <a-select-option
                                                v-for="item in dicsStore.dictOptions.Statistical_Classification"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 智力情况 -->
                                <a-col :span="8">
                                    <a-form-item label="智力情况" name="intellectualSituation">
                                        <a-select v-model:value="formData.archive.intellectualSituation"
                                            placeholder="请选择智力情况" allow-clear>
                                            <a-select-option
                                                v-for="item in dicsStore.dictOptions.Intellectual_Condition"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 是否长期照料失能子女 -->
                                <a-col :span="8">
                                    <a-form-item label="是否长期照料失能子女" name="longTermCareForDisabledChildren">
                                        <a-select v-model:value="formData.archive.longTermCareForDisabledChildren"
                                            placeholder="请选择是否长期照料失能子女" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Disabled_Child"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 老人子女探望情况 -->
                                <a-col :span="8">
                                    <a-form-item label="老人子女探望情况" name="childrenVisitStatus">
                                        <a-select v-model:value="formData.archive.childrenVisitStatus"
                                            placeholder="请选择老人子女探望情况" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Frequency_Visits"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 是否人户分离 -->
                                <a-col :span="8">
                                    <a-form-item label="是否人户分离" name="householdResidenceSeparation">
                                        <a-select v-model:value="formData.archive.householdResidenceSeparation"
                                            placeholder="请选择是否人户分离" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Separation"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 民族 -->
                                <a-col :span="8">
                                    <a-form-item label="民族" name="ethnicity">
                                        <a-select v-model:value="formData.archive.ethnicity" placeholder="请选择民族"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Ethnicity"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 是否完成能力评估 -->
                                <a-col :span="8">
                                    <a-form-item label="是否完成能力评估" name="completedCapacityAssessment">
                                        <a-select v-model:value="formData.archive.completedCapacityAssessment"
                                            placeholder="请选择是否完成能力评估" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Capability_Assessment"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 是否住出租屋/地下室 -->
                                <a-col :span="8">
                                    <a-form-item label="是否住出租屋/地下室" name="livesInRentedRoomOrBasement">
                                        <a-select v-model:value="formData.archive.livesInRentedRoomOrBasement"
                                            placeholder="请选择是否住出租屋/地下室" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Property_Basement"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 经济来源 -->
                                <a-col :span="8">
                                    <a-form-item label="经济来源" name="economicSource">
                                        <a-select v-model:value="formData.archive.economicSource" placeholder="请选择经济来源"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Source_Income"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 文化程度 -->
                                <a-col :span="8">
                                    <a-form-item label="文化程度" name="educationLevel">
                                        <a-select v-model:value="formData.archive.educationLevel" placeholder="请选择文化程度"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Level_Education"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 宗教信仰 -->
                                <a-col :span="8">
                                    <a-form-item label="宗教信仰" name="religion">
                                        <a-select v-model:value="formData.archive.religion" placeholder="请选择宗教信仰"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Religious_belief"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 职业情况 -->
                                <a-col :span="8">
                                    <a-form-item label="职业情况" name="occupation">
                                        <a-select v-model:value="formData.archive.occupation" placeholder="请选择职业情况"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Employment_Status"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 政治面貌 -->
                                <a-col :span="8">
                                    <a-form-item label="政治面貌" name="politicalAffiliation">
                                        <a-select v-model:value="formData.archive.politicalAffiliation"
                                            placeholder="请选择政治面貌" allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Political_affiliation"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>

                                <!-- 婚姻情况 -->
                                <a-col :span="8">
                                    <a-form-item label="婚姻情况" name="maritalStatus">
                                        <a-select v-model:value="formData.archive.maritalStatus" placeholder="请选择婚姻情况"
                                            allow-clear>
                                            <a-select-option v-for="item in dicsStore.dictOptions.Marital_Status"
                                                :key="item.dval" :value="item.dval">
                                                {{ item.introduction }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span='16'>
                                    <a-form-item label="分类标签" name="labelCodes">
                                        <a-select v-model:value="formData.labelCodes" allowClear mode="multiple"
                                            style="width: 100%;">
                                            <a-select-option
                                                v-for="item in dicsStore.dictOptions.Service_Recipient_Category2"
                                                :key="item.dval" :value="item.dval">{{
                                                    item.introduction }}</a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                
                                <!-- 其他 -->
                                <a-col :span="24">
                                    <a-form-item label="其他" name="otherNotes">
                                        <a-textarea v-model:value="formData.archive.otherNotes" placeholder="请输入"
                                            :rows="1" :auto-size="{ minRows: 1, maxRows: 2 }" />
                                    </a-form-item>
                                </a-col>

                                <!-- 身份证照片 -->
                                <a-col :span="12">
                                    <a-form-item label="身份证照片" name="idCardPhotos">
                                        <gx-upload v-model="formData.archive.idCardPhotos"
                                            accept-types=".jpg,.png,.webp" :fileNumber="1" />
                                    </a-form-item>
                                </a-col>

                                <!-- 上传资料 -->
                                <a-col :span="12">
                                    <a-form-item label="上传资料" name="uploadedDocuments">
                                        <UploadInput v-model="uploadedDocuments"/>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </a-tab-pane>
                    </a-tabs>
                </a-form>
            </a-card>
        </a-spin>
    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, defineProps, nextTick,watch } from 'vue'
import { config } from '@/config'
import apis from '@/apis'
import { useForm, useModal, useSpining } 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 storage from '@/utils/storage'
import { message } from 'ant-design-vue'
import { FastBackwardFilled } from '@ant-design/icons-vue'
import UploadInput from '@/components/Upload/UploadInput.vue'
import ServiceStation from '@/components/ServiceStation/index.vue'
const emit = defineEmits(['ok'])
const activeKey = ref('1')
const uploadedDocuments=ref([])
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const areaCascaderRef = ref()
const houseAreaRef = ref()
const cancelText = ref('取消')
const spining = ref(false)
const isShow=ref(false)
formRules.value = {
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    identityType: [{ required: true, message: '请选择证件类型', trigger: 'change' }],
    stationId:[{ 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()
formData.value = {
    stationId: storage.local.getItem('stationId'),
    companyId: storage.local.getItem('companyId'),
    archive: {

    }
}
/**
 * 新建
 */
function handleCreate() {
    formData.value.gender = '1'
    showModal({
        type: 'create',
        title: '新建项',
    })
}

/**
 * 编辑
 */
async function handleEdit(record = {}) {
    showModal({
        type: 'edit',
        title: '编辑对象'
    })
    try {
        spining.value = true
        const { data, success } = await apis.serverObj.getItem(record.id).catch()
        if (!success) {
            spining.value = false
            hideModal()
            return
        }
        formData.value = { ...data }
        formData.value.birthDate = dayjs(data.birthDate)
        formData.value.archive.idCardPhotos = data.archive.idCardPhotos ? data.archive.idCardPhotos.map(item => config('http.apiUpload') + item) : []
        uploadedDocuments.value = data.archive.uploadedDocuments ? data.archive.uploadedDocuments.map(item => config('http.apiUpload') + item) : []
        
        formData.value.governmentPurchasedServiceStartDate = [dayjs(formData.value.starGovernmentService), dayjs(formData.value.endGovernmentService)]
        nextTick(() => {
            areaCascaderRef.value.initData(data.archive.homeAreaCodes||[''])
            houseAreaRef.value.initData(data.archive.houseAreaCodes||[''])
        })
        spining.value = false
    } catch (error) {
        console.log(error.message)
        spining.value = false
    }

}
// utils/idCard.js
function isValidIdCard(value) {
    if (!value || typeof value !== 'string') return false;

    const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{18}X$)/i;
    if (!idCardRegex.test(value)) return false;

    // 18位校验码验证
    if (value.length === 18) {
        const Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];
        const Vi = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

        let sum = 0;
        for (let i = 0; i < 17; i++) {
            sum += parseInt(value[i], 10) * Wi[i];
        }
        const checkCode = Vi[sum % 11];
        if (checkCode !== value[17].toUpperCase()) {
            return false;
        }
    }

    // 验证生日
    let year, month, day;
    if (value.length === 15) {
        year = '19' + value.substring(6, 8);
        month = value.substring(8, 10);
        day = value.substring(10, 12);
    } else {
        year = value.substring(6, 10);
        month = value.substring(10, 12);
        day = value.substring(12, 14);
    }

    const date = new Date(year, month - 1, day);
    if (
        date.getFullYear() !== parseInt(year, 10) ||
        date.getMonth() + 1 !== parseInt(month, 10) ||
        date.getDate() !== parseInt(day, 10)
    ) {
        return false;
    }

    const currentYear = new Date().getFullYear();
    const birthYear = parseInt(year, 10);
    if (birthYear < 1900 || birthYear > currentYear) {
        return false;
    }

    return true;
}
/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                let params = {
                    ...formData.value,
                    labels: formData.value.labelCodes ? formData.value.labelCodes.map(item => dicsStore.getDictLabel('Service_Recipient_Category2', item)) : [],
                }
                params.archive.idCardPhotos = formData.value.archive.idCardPhotos && formData.value.archive.idCardPhotos.length > 0 ? formData.value.archive.idCardPhotos.map(item => spliceUrl(item)) : []
                params.archive.uploadedDocuments = uploadedDocuments.value && uploadedDocuments.value.length > 0 ? uploadedDocuments.value.map(item => spliceUrl(item)) : []
                if (formData.value.governmentPurchasedServiceStartDate && formData.value.governmentPurchasedServiceStartDate.length > 0) {
                    params.archive.starGovernmentService = formData.value.governmentPurchasedServiceStartDate[0]
                    params.archive.endGovernmentService = formData.value.governmentPurchasedServiceStartDate[1]
                }
                // params.stationId=storage.local.getItem('stationId')
                // 单独封装一个同步校验函数
                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') === true) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                console.log(error.message)
                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.archive.lat = obj.lat
    formData.value.archive.lag = obj.lng
}
/**
 * 取消
 */
function handleCancel() {
    formData.value = {archive: {}}
    hideModal()
}

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

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

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