<template>
    <div class="wrap">
        <div class="info-header">
            <el-descriptions>
                <template #title>
                    客户信息
                </template>
                <template #extra>
                    <el-button type="primary" :icon="Edit" circle @click="handleEditData(detail)" />
                    <el-button type="danger" :icon="Avatar" circle @click="joinBlacklist(detail)" />
                </template>
                <el-descriptions-item span="4">
                    <div class="cardInfo">
                        <div
                            style="margin-right: 15px; width: 40px; height: 40px; background-color: #ffffff; border-radius: 50%; margin-top: 11px; margin-left: 8px;">
                            <el-image class="headImage" :src="patientIcon" fit="fill" />
                        </div>
                        <div style="display: block;">
                            <div>
                                <span style="margin-right: 10px;">{{detail.name}}</span>
                                <span>{{sexMap[detail.sex] ? sexMap[detail.sex].title : '-'}} / {{
                                    detail.age?detail.age: '-'}} </span>
                                <!-- <el-button size="small" type="primary">普通</el-button> -->
                            </div>
                            <div>{{
                                detail.address?detail.address:getStrById(detail.nativePlace)?getStrById(detail.nativePlace):'-'
                                }}</div>

                                <div class="flex flex-wrap gap-2">
                                    <el-tooltip v-for="(tag, index) in customerTags" :key="index"
                                        :content="`${tag.createTime}`" effect="light" placement="top">
                                        <el-tag closable :color="tag.color || 'white'" effect="dark" size="small"
                                            class="opacity-90 !rounded-full" @close="tagClose($event, tag)">
                                            {{ tag.labelName }}
                                        </el-tag>
                                    </el-tooltip>
                                </div>
                        </div>

                    </div>
                </el-descriptions-item>

                <el-descriptions-item label="编号：" span="4">
                    <el-link class="title-text" style="margin-left: 0px;" :underline="false"
                        @click="handleCopy(patientId)">
                        {{ patientId && patientId.split('-')[0] }}
                    </el-link>
                </el-descriptions-item>
                <el-descriptions-item label="姓名：" span="4">{{ detail.name }}</el-descriptions-item>
                <el-descriptions-item label="年龄：" span="4">{{ detail.age }}</el-descriptions-item>
                <el-descriptions-item label="性别：" span="4">{{ sexMap[detail.sex] ? sexMap[detail.sex].title :
                    ''}}</el-descriptions-item>
                <!-- <el-descriptions-item label="出生日期">{{ detail.nation }}</el-descriptions-item> -->
                <el-descriptions-item label="民族：" span="4">{{ nationsMap[`${detail.nation}`] ?
                    nationsMap[`${detail.nation}`].title : ''
                    }}</el-descriptions-item>
                <el-descriptions-item label="籍贯：" span="4">{{ getStrById(detail.nativePlace) }}</el-descriptions-item>
                <el-descriptions-item label="手机号：" span="4">{{ detail.phoneNumber &&
                    userDecryptToAsterisk(detail.phoneNumber)}}</el-descriptions-item>
                <el-descriptions-item label="联系电话：" span="4">{{ detail.tel && userDecryptToAsterisk(detail.tel)
                    }}</el-descriptions-item>
                <el-descriptions-item label="备用号码：" span="4">{{ detail.secondPhone &&
                    userDecryptToAsterisk(detail.secondPhone)
                    }}</el-descriptions-item>
                <el-descriptions-item label="邮箱：" span="4">{{ detail.email }}</el-descriptions-item>
                <!-- <el-descriptions-item label="职业">{{ detail.work }}</el-descriptions-item> -->
                <!-- <el-descriptions-item label="身份证号：" span="4">{{ detail.idcard && userDecryptToAsterisk(detail.idcard)
                    }}</el-descriptions-item>
                <el-descriptions-item label="医保卡号：" span="4">{{ detail.ybkId }}</el-descriptions-item> -->
                <el-descriptions-item label="住址：" span="4">{{ detail.address }}</el-descriptions-item>

            </el-descriptions>


        </div>

        <page-modal :defaultInfo="defaultInfo" ref="pageModalRef" pageName="/patient/patient" @submit="submit"
            :modalConfig="modalConfigRef"></page-modal>

        <!-- 黑名单组件 -->
        <page-modal :defaultInfo="blackInfo" ref="blackModalRef" pageName="/patient/black"
            :modalConfig="blackModalConfig" :otherInfo="blackOtherInfo"></page-modal>
    </div>
</template>

<script setup>
    import { ref, onMounted, watch, toRaw } from "vue";
    import patientIcon from '@/assets/images/patientIcon.png'
    import { useRoute } from 'vue-router';
    import { getPatientInfo } from '@/api/patient/patient';
    import { userDecryptToAsterisk } from '@/utils/aes'
    import { nations, patientStatus, sex, patientSource, phoneStatus } from "@/utils/commonDic.js";
    import { getStrById, areaTrees } from "@/utils/area.js";
    import { ArrayToMap } from '@/utils/tools'
    import PageModal from '@/components/page-modal'
    import { usePageModal } from '@/hooks/use-page-modal'
    import { modalConfig } from '../../config/modal.config'
    import { useClipboard } from "@vueuse/core"
    import { ElMessage, ElMessageBox } from 'element-plus'
    import { modalConfig as blackModalConfig } from '@/views/main/patientFile/patientblack/config/modal.config'
    import { Avatar, Edit } from '@element-plus/icons-vue'
    import { getPageListData, deletePageData } from '@/api/main/system/system';

    const activeName = ref('first')
    function handleClick() {
    }

    const router = useRoute();

    let detail = ref({});

    const patientId = ref(router.query.patientId || router.query.id);

    // const descColumn = ref(4)

    const props = defineProps({
        descColumn: {
            type: Number,
            default: 4,
        },
        patientCallNumber: {
            type: String,
            default: ''
        }
    })
    watch(props, (nweProps) => {
        // initMethod(nweProps)
        if (nweProps.patientCallNumber) {
            customerDetail(nweProps.patientCallNumber)
        }
    });

    onUpdated(() => {
        patientId.value = router.query.patientId || router.query.id;
        console.log('patientId.value' ,patientId.value);
    });
    const getPatientId = computed(() => {
        return router.query.patientId || router.query.id;
    });
    watch(getPatientId, async (newValue) => {
        patientId.value = newValue;
        console.log('newValue',newValue)
        getDetail(newValue).then(() => { });
    })

    const stateLog = ref();
    async function customerDetail(customerno) {
        const resultData = await getPageListData('/patient/patient', { phoneNumber: customerno });
        // form.value.caller =  resultData.data[0].name
        
        detail.value = resultData.data[0]
        console.log(detail.value);
    }
    const getDetail = async () => {
        getLabels();
        const res = await getPatientInfo(patientId.value)
        if (res.data) {
            detail.value = res.data
        }
        
    }



    onBeforeMount(async () => {
        if (props.patientCallNumber) {
            customerDetail(props.patientCallNumber)
        } else {
            await getDetail(patientId.value);
        }



    })

    const statusMap = ArrayToMap(patientStatus, 'value');
    const sourceMap = ArrayToMap(patientSource, 'value');
    const phoneStatusMap = ArrayToMap(phoneStatus, 'value');
    const sexMap = ArrayToMap(sex, 'value');
    const nationsMap = ArrayToMap(nations, 'value');

    const getLogs = (logs) => {
        // 获取当前状态对应的数据
        if (phoneStatusMap[detail.value.phoneStatus] && phoneStatusMap[detail.value.phoneStatus].showLog) {
            console.log(logs, 'asdf')
            stateLog.value = logs.find((o) => {
                return o.type === '状态变更';
            })

            console.log(stateLog.value, 'stateLog.value');
        }

    }


    // 1.处理逻辑
    const newCallback = () => { }
    const editCallback = () => {
        console.log(defaultInfo.value)
    }

    const blackNewCallback = () => { }
    const blackEditCallback = () => {
        console.log(blackInfo.value)
    }

    // 2.动态添加部门和角色列表
    const modalConfigRef = computed(() => {

        // const nativePlace = modalConfig.formItems.find(
        //     (item) => item.field === 'nativePlace'
        // )
        // nativePlace.options = areaTrees()

        // const nation = modalConfig.formItems.find(
        //     (item) => item.field === 'nation'
        // )
        // nation.options = nations

        // const patientStatusConf = modalConfig.formItems.find(
        //     (item) => item.field === 'patientStatus'
        // )
        // patientStatusConf.options = patientStatus

        // const sexConf = modalConfig.formItems.find(
        //     (item) => item.field === 'sex'
        // )
        // sexConf.options = sex

        return modalConfig
    })

    // 加入黑名单
    const blackOtherInfo = ref({
        patientId: '',
    });
    const joinBlacklist = async (row) => {
        blackOtherInfo.value.patientId = row.patientId;
        blackNewData();
    }


    // 3.调用hook获取公共变量和函数
    const [pageModalRef, defaultInfo, handleNewData, handleEditData] =
        usePageModal(newCallback, editCallback)

    const [blackModalRef, blackInfo, blackNewData, blackEditData] =
        usePageModal(blackNewCallback, blackEditCallback)


    const submit = () => {
        getDetail(patientId.value);
    }


    const { copy, isSupported } = useClipboard();
    const handleCopy = (val) => {
        if (!isSupported) {
            ElMessage({
                message: '您的浏览器不支持Clipboard API',
                type: 'error',
            })
            return;
        }

        copy(val);
        ElMessage({
            message: '复制成功',
            type: 'success',
        })
    };

const customerTags = ref([]);

const getLabels = () => {

    if (!patientId.value) return;
    // TODO: 此处需要根据手机号获取标签列表
    getPageListData(`/common/getlabelbypatientid/${patientId.value}`).then(
        ({ data }) => {
            customerTags.value = data;
        }
    )
}

// 标签删除
const tagClose = (event, tag) => {
    console.log(event, tag);
    // 二次确认提醒
    ElMessageBox.confirm('确定删除该标签吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        // 确认删除
        deletePageData(`/patient/patientlabel`, {
            labelId: tag.tagId,
            patientids: [patientId.value]
        }).then(
            ({ data }) => {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                getLabels();
            }
        )
    })
}

</script>

<style lang="scss" scoped>
    :deep(.el-descriptions__label) {
        width: 80px;
        text-align: right;
        display: inline-block;
    }

    .cardInfo {
        width: 100%;
        line-height: 30px;
        background-color: #F3F9FF;
        display: flex;
        padding: 10px;
    }

    .wrap {
        .info-header {
            padding: 30px;
            padding-right: 0px;
            width: 100%;

            .title-text {
                margin-left: 10px;
                font-size: 16px;
                font-weight: bold;
            }

            .title-time {
                margin-left: 10px;
                font-size: 14px;
                font-weight: normal;
                color: #606266;
            }

            .title-reson {
                color: #F56C6C;
                font-size: 14px;
                font-weight: normal;
                margin-left: 5px;
            }

        }

        .info-card {
            margin: 0px 30px 30px 30px;
        }
    }
</style>