<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-card>
            <a-form ref="formRef" :model="formData" :rules="formRules">
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-item label="所属服务站点" name="stationId">
                            <a-select v-model:value="formData.stationId" allowClear>
                                <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-form-item label="服务人员姓名" name="name">
                            <a-input v-model:value="formData.name" placeholder="请输入姓名" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="身份证号" name="idCard">
                            <a-input v-model:value="formData.idCard" placeholder="请输入证件号码"
                                @change="extractBirthDateFromIdCard" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="出生日期" name="birthDate2">
                            <a-input v-model:value="formData.birthDate2" placeholder="根据身份证号码自动识别" disabled />
                        </a-form-item>
                    </a-col>
                    <!-- 性别 -->
                    <a-col :span="12">
                        <a-form-item label="性别" name="gender">
                            <a-radio-group v-model:value="formData.gender">
                                <a-radio value="1">男</a-radio>
                                <a-radio value="2">女</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                                <a-col :span="12">
                        <a-form-item label="状态" name="status">
                            <a-radio-group v-model:value="formData.status">
                                <a-radio v-for="item in dicsStore.dictOptions.STAFF_STATUS" :key="item.dval" :value="item.dval">{{ item.introduction }}</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <!-- 证件号码 -->

                    <a-col :span="12">
                        <a-form-item label="电话" name="phone">
                            <a-input v-model:value="formData.phone" placeholder="请输入电话" />
                        </a-form-item>
                    </a-col>

                    <a-col :span="12">
                        <a-form-item label="护理人员类型" name="serviceType">
                            <a-select v-model:value="formData.serviceType" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.STAFF_TYPE" :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="qualificationName">
                            <a-input v-model:value="formData.qualificationName" placeholder="请输入资格证照名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="资格证照等级" name="qualificationLV">
                            <a-select v-model:value="formData.qualificationLV" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.QUA_LV" :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="insuranceStatus">
                            <a-select v-model:value="formData.insuranceStatus" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.INSURANCE_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="education">
                            <a-select v-model:value="formData.education" allowClear>
                                <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="12">
                        <a-form-item label="用工形式" name="workType">
                            <a-select v-model:value="formData.workType" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.USE_TYPE" :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="sAreaCodes">
                            <AreaCascader v-model:value="formData.sAreaCodes" @change="onAreaChange"
                                ref="areaCascaderRef" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="提成比例" name="commissionRate">
                            <a-input-number v-model:value="formData.commissionRate" placeholder="请输入提成比例">
                                <template #addonAfter>
                                    <span>%</span>
                                </template>
                            </a-input-number>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="入职日期" name="joinAt">
                            <a-date-picker v-model:value="formData.joinAt" placeholder="请选择入职日期" style="width: 100%;" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="资格证照注册号" name="qualificationNo">
                            <a-input v-model:value="formData.qualificationNo" placeholder="请输入资格证照注册号" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="劳动合同期限" name="laborContract">
                            <a-range-picker v-model:value="formData.laborContract" placeholder="请选择劳动合同期限" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="星级评价等级" name="starLv">
                            <a-select v-model:value="formData.starLv" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.START_LV" :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="bankName">
                            <a-input v-model:value="formData.bankName" placeholder="请输入开户行名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="银行卡号" name="bankNo">
                            <a-input v-model:value="formData.bankNo" placeholder="请输入银行卡号" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="补贴类型" name="subsidyType">
                            <a-select v-model:value="formData.subsidyType" allowClear>
                                <a-select-option v-for="item in dicsStore.dictOptions.SUBSIDY_TYPE" :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="areaCodes">
                            <AreaCascader v-model:value="formData.areaCodes" @change="onAreaChange2" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="家庭详细地址" name="address">
                            <a-input v-model:value="formData.address" placeholder="请输入家庭详细地址"></a-input>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="备注" name="remark">
                            <a-textarea v-model:value="formData.remark" placeholder="请输入备注" :rows="4"></a-textarea>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="证件照片" name="imgs">
                            <gx-upload v-model="formData.imgs" :fileNumber="1" accept-types=".jpg,.png,.webp" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item label="附件" name="attachments">
                            <UploadInput v-model="formData.attachments"/>
                        </a-form-item>
                    </a-col>

                </a-row>
            </a-form>
        </a-card>

    </a-modal>
</template>

<script setup>
import { cloneDeep } from 'lodash-es'
import { ref, nextTick } 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 NodeTree from '@/components/NodeTree/index.vue'
import dayjs from 'dayjs'
import { getBirthDate, spliceUrl } from '@/utils/util'
import { validatePhone, validateEmail, validateIdCard } from '@/utils/validate'
import storage from '@/utils/storage'
import UploadInput from '@/components/Upload/UploadInput.vue'
const emit = defineEmits(['ok'])
const { modal, showModal, hideModal, showLoading, hideLoading } = useModal()
const { formRecord, formData, formRef, formRules, resetForm } = useForm()
const cancelText = ref('取消')
const dicsStore = useDicsStore()
const stationList = ref([])
const areaCascaderRef = ref()
formRules.value = {
    stationId: [{ required: true, message: '请选择服务组织', trigger: ['blur', 'change'] }],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    idCard: [{ validator: validateIdCard, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: ['blur', 'input'] }, { required: true, message: '请输入联系方式', trigger: 'blur' }],
    serviceType: [{ required: true, message: '请选择护理人员类型', trigger: ['blur', 'change'] }],
    insuranceStatus: [{ required: true, message: '请选择参保情况', trigger: ['blur', 'change'] }],
}
/**
 * 新建
 */
function handleCreate() {
    formData.value.gender = '1'
    formData.value.status = '1'
    formData.value.companyId = storage.local.getItem('companyId')
    formData.value.stationId = storage.local.getItem('stationId')
    showModal({
        type: 'create',
        title: '新增服务人员',
    })
}
getStationList()
async function getStationList() {
    try {
        showLoading()
        const { success, data, total } = await apis.serviceMenu
            .getServiceSiteList({
                pageSize: 100,
                current: 1,
            })
            .catch(() => {
                throw new Error()
            })
        hideLoading()
        if (config('http.code.success') === success) {
            //筛选type的值80对应about
            stationList.value = data.map(item => ({ id: item.id, name: item.name }))
            console.log(stationList.value)
        }
    } catch (error) {
        hideLoading()
    }
}
/**
 * 编辑
 */
async function handleEdit(record = {}) {
    try {
        showModal({
            type: 'edit',
            title: '编辑项',
        })
        const { data, success } = await apis.serviceStaffList.getItem(record.id).catch()
        if (!success) {
            hideModal()
            return
        }
        formData.value = data
        if (formData.value.joinAt) {
            formData.value.joinAt = dayjs(formData.value.joinAt)
        }
        if (formData.value.laborContractStartAt && formData.value.laborContractEndAt) {
            formData.value.laborContract = [dayjs(formData.value.laborContractStartAt), dayjs(formData.value.laborContractEndAt)]
        }
        formData.value.imgs = (data.imgs && data.imgs.length > 0) ? data.imgs.map(item => config('http.apiUpload') + item) : []
        formData.value.attachments = (data.attachments && data.attachments.length > 0) ? data.attachments.map(item => config('http.apiUpload') + item) : []
        formData.value.commissionRate = formData.value.commissionRate ?? formData.value.commissionRate * 100
        formData.value.birthDate2 = dayjs(data.birthDay).format('YYYY-DD-MM')
        nextTick(() => {
            areaCascaderRef.value.initData(data.sAreaCodes||[])
        })
    } catch (error) {

    }

}


/**
 * 确定
 */
function handleOk() {
    formRef.value
        .validateFields()
        .then(async (values) => {
            try {
                showLoading()
                let params = {
                    ...formData.value,
                    birthDay: formData.value.birthDate2
                }

                if (formData.value.laborContract && formData.value.laborContract.length > 0) {
                    params.laborContractStartAt = formData.value.laborContract[0]
                    params.laborContractEndAt = formData.value.laborContract[1]
                }
                console.log(formData.value.imgs)
                params.imgs = (formData.value.imgs && formData.value.imgs.length) > 0 ? formData.value.imgs.map(item => spliceUrl(item)) : []
                params.attachments = (formData.value.attachments && formData.value.attachments.length) > 0 ? formData.value.attachments.map(item => spliceUrl(item)) : []
                params.commissionRate = formData.value.commissionRate ?? formData.value.commissionRate / 100
                console.log(params)
                let result = null
                switch (modal.value.type) {
                    case 'create':
                        result = await apis.serviceStaffList.createItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                    case 'edit':
                        result = await apis.serviceStaffList.updateItem(params).catch(() => {
                            throw new Error()
                        })
                        break
                }
                hideLoading()
                if (config('http.code.success') === true) {
                    hideModal()
                    emit('ok')
                }
            } catch (error) {
                console.log(error.message)
                hideLoading()
            }
        })
        .catch(() => {
            hideLoading()
        })
}
// 提取出生日期方法
const extractBirthDateFromIdCard = () => {
    console.log(111)
    const { idCard } = formData.value;
    if (!idCard) {
        formData.value.birthDate = '';
        return;
    }
    console.log(getBirthDate(idCard))
    formData.value.birthDate2 = getBirthDate(idCard)
    formData.value.birthDate = new Date(getBirthDate(idCard));
}
function onAreaChange(value, labels) {
    formData.value.sAreaLabels = [...labels]
}
function onAreaChange2(value, labels) {
    formData.value.areaLabels = [...labels]
}
/**
 * 取消
 */
function handleCancel() {
    hideModal()
}

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

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

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