<template>
    <div>
        <van-form ref='form'>
            <div class='title'>居民信息</div>
            <!--            <div class='label-title'>证件类型</div>
                        <van-field
                            v-model='form.certificateTypeName'
                            is-link
                            readonly
                            placeholder='证件类型'
                            class='input-back mt-2 form-input'
                            :rules='rules.certificateTypeName'
                        />-->
            <!--            <div class='label-title mt-5'>证件号码</div>
                        <van-field
                            v-model='form.idCard'
                            readonly
                            placeholder='证件号码'
                            class='input-back mt-2 form-input'
                            :rules='rules.idCard'
                        />-->
            <div class='label-title mt-5'>姓名</div>
            <van-field
                v-model='form.residentName'
                clearable
                placeholder='姓名'
                class='input-back mt-2 form-input'
                :rules='rules.residentName'
            />
            <!--            <div class='label-title mt-5'>性别</div>
                        <van-field
                            v-model='form.genderName'
                            is-link
                            readonly
                            placeholder='性别'
                            class='input-back mt-2 form-input'
                            :rules='rules.genderName'
                        />-->
            <!--            <div class='label-title mt-5'>出生日期</div>
                        <van-field
                            v-model='form.dataBirth'
                            is-link
                            readonly
                            placeholder='出生日期'
                            class='input-back mt-2 form-input'
                            :rules='rules.dataBirth'
                        />-->
            <div class='label-title mt-5'>本人电话</div>
            <van-field
                v-model='form.telephone'
                clearable
                placeholder='本人电话'
                class='input-back mt-2 form-input'
                :rules='rules.telephone'
            />
            <div class='label-title mt-5'>民族</div>
            <van-field
                v-model='form.nationalName'
                is-link
                readonly
                name='national'
                placeholder='请选择'
                class='input-back mt-2 form-input'
                :rules='rules.nationalName'
                @click='showNational = true' />
            <van-popup v-model:show='showNational' position='bottom'>
                <van-picker
                    :columns-field-names="{ text: 'name', value: 'value' }"
                    :columns="store.getDict('DC00006')"
                    @confirm='nationalConfirm'
                    @cancel='showNational = false'
                />
            </van-popup>
            <!--            <div class='label-title mt-5'>年龄</div>
                        <van-field
                            v-model='form.currentAge'
                            readonly
                            placeholder='年龄'
                            class='input-back mt-2 form-input'
                            :rules='rules.currentAge'
                        />-->
            <div class='label-title mt-5'>现住址</div>
            <van-field
                v-model='form.presentCodeName'
                is-link
                readonly
                style='min-height: 26px!important;'
                placeholder='请选择所在地区'
                class='input-back mt-2 form-input'
                :rules='rules.presentCodeName'
                @click='showPresent = true'
            >
                <template #input>
                    <span class='text-end'>{{ form.presentCodeName }}</span>
                </template>
            </van-field>
            <van-popup v-model:show='showPresent' :close-on-click-overlay='false' position='bottom'>
                <DocAddress v-model:value='form.presentCode' @close='showPresent = false'
                            :viewData='addressRecord.presentCode'
                            @change='presentChange' />
            </van-popup>
            <div class='no-req-label mt-5'>详细地址</div>
            <van-field
                v-model='form.nowAddress'
                clearable
                class='input-back mt-2 form-input'
                placeholder='请填写详细地址'
                maxlength='50'
            />
            <div class='flex items-center justify-between mt-5'>
                <div class='label-title '>户口地址</div>
                <van-button size='mini' plain type='primary'
                            @click='setRegisteredAddress'>同步现住址
                </van-button>
            </div>

            <van-field
                v-model='form.registeredCodeName'
                is-link
                readonly
                placeholder='请选择所在地区'
                class='input-back mt-2 form-input'
                :rules='rules.registeredCode'
                @click='showRegistered = true'
            >
                <template #input>
                    <span class='text-end'>{{ form.registeredCodeName }}</span>
                </template>
            </van-field>
            <van-popup v-model:show='showRegistered' :close-on-click-overlay='false' position='bottom'>
                <DocAddress v-model:value='form.registeredCode' @close='showRegistered = false'
                            :viewData='addressRecord.registeredCode'
                            @change='registeredChange' />
            </van-popup>
            <div class='no-req-label mt-5'>详细地址</div>
            <van-field
                v-model='form.permanentAddress'
                clearable
                class='input-back mt-2 form-input'
                placeholder='请填写详细地址'
                maxlength='50'
            />
            <div class='title mt-5'>联系人信息</div>
            <div class='no-req-label mt-5'>联系人姓名</div>
            <van-field
                v-model='form.contactName'
                clearable
                placeholder='联系人姓名'
                class='input-back mt-2 form-input'
                :rules='rules.contactName'
            />
            <div class='no-req-label mt-5'>与居民关系</div>
            <van-field
                v-model='form.relationName'
                readonly
                is-link
                placeholder='与居民关系'
                class='input-back mt-2 form-input'
                @click='showRelation= true'
            />
            <van-popup v-model:show='showRelation' position='bottom'>
                <van-picker
                    :columns-field-names="{ text: 'name', value: 'value' }"
                    :columns="store.getDict('DC00023')"
                    @confirm='relationlConfirm'
                    @cancel='showRelation = false'
                />
            </van-popup>
            <van-field
                v-if='form.relation == 99'
                v-model='form.relationOther'
                clearable
                placeholder='其他关系'
                class='input-back mt-2 form-input'
            />
            <div class='no-req-label mt-5'>联系电话</div>
            <van-field
                v-model='form.contactPhone'
                clearable
                placeholder='联系电话'
                class='input-back mt-2 form-input'
                :rules='rules.contactPhone'
            />
            <div class='title mt-5'>随访信息</div>
            <div class='label-title mt-5'>随访人群</div>
            <van-field
                v-model='form.groupsArraysName'
                readonly
                is-link
                placeholder='请选择'
                class='input-back mt-2 form-input'
                :rules='rules.groupsArraysName'
                @click='showGroupsArrays= true'
            >
                <template #input>
                    <span class='text-end' v-if='form.groupsArraysName'>{{form.groupsArraysName}}</span>
                    <span class='text-end' v-if='!form.groupsArraysName' style='color: #dfdfe1'>请选择</span>
                </template>
            </van-field>
            <van-popup v-model:show='showGroupsArrays' position='bottom'>
                <div class='p-4'>
                    <div class='flex justify-between items-center mb-4 pop-title'>
                        <div class='greyColor' @click='showGroupsArrays = false' style='font-weight: 400'>取消</div>
                        <div>随访人群（可多选）</div>
                        <div class='blueColor' @click='groupsArraysConfirm'>确定</div>
                    </div>
                    <CheckBtn multiple :options='groupArrList' v-model:value='checkGroupsArrays' :fieldNames="{text: 'name', value: 'value'}"/>
                </div>
            </van-popup>

            <div class='label-title mt-5'>随访方式</div>
            <van-field
                v-model='form.visitWayName'
                readonly
                is-link
                placeholder='请选择'
                class='input-back mt-2 form-input'
                :style="{borderRadius: form.visitWayName ? '8px 8px 0px 0px ': '8px'}"
                :rules='rules.visitWay'
                @click='showVisitWay= true'
            />
            <div class='tel-back' v-if='form.visitWayName'>
                <div class='tel flex items-center justify-between'>
                    <div>
                        <span>居民电话： </span><span>{{ form.telephone }}</span>
                    </div>
                    <div @click='toTel' class='tel-label'>点击拨打</div>
                </div>
            </div>
            <van-popup v-model:show='showVisitWay' position='bottom'>
                <div class='p-4'>
                    <div class='flex justify-between mb-4 items-center pop-title'>
                        <div class='greyColor' @click='showVisitWay = false' style='font-weight: 400'>取消</div>
                        <div>随访方式（仅单选）</div>
<!--                        <div class='blueColor' @click='visitWayConfirm'>确定</div>-->
                        <div></div>
                    </div>
                    <CheckBtn column-1
                              @change="visitWayConfirm"
                              :options="store.getDict('CP00179')"
                              v-model:value='checkVisitWay'
                              :fieldNames="{text: 'name', value: 'value'}"
                    />
                </div>
            </van-popup>

            <div class='label-title mt-5'>随访类型</div>
            <van-field
                v-model='form.visitWayRulesName'
                readonly
                is-link
                placeholder='请选择'
                class='input-back mt-2 form-input'
                :rules='rules.visitWayRulesName'
                @click='showVisitWayRules= true'
            />
            <van-popup v-model:show='showVisitWayRules' position='bottom'>
                <div class='p-4'>
                    <div class='flex justify-between mb-4 items-center pop-title'>
                        <div class='greyColor' @click='showVisitWayRules = false' style='font-weight: 400'>取消</div>
                        <div>随访类型（可多选）</div>
                        <div class='blueColor' @click='visitWayRulesConfirm'>确定</div>
                    </div>
                    <CheckBtn multiple column-2 :options='visitWayRulesList' v-model:value='checkVisitWayRules' :fieldNames="{text: 'name', value: 'value'}"/>
                </div>
            </van-popup>

        </van-form>
    </div>
</template>

<script>
import { addToArr, callMobile, fetchDataHandle, isIOSWebKit } from '@/utils/common'
import { useStore } from '@/doctor/store'
import DocAddress from '@/components/docAddress/DocAddress'
import dayjs from 'dayjs'
import CheckBtn from '@/doctor/components/checkBtn/CheckBtn'

const defaultForm = (info = {}) => {
    const form = {
        id: undefined,
        personId: undefined,
        residentInfoId: undefined,
        // 年龄
        currentAge: undefined,
        // 证件类型,[DC00004]
        certificateType: 1,
        certificateTypeName: '身份证',
        // 联系人姓名
        contactName: undefined,
        // 联系人电话
        contactPhone: undefined,
        // 出生日期
        dataBirth: undefined,
        // 性别,[DC00005]
        gender: undefined,
        genderName: undefined,
        // 身份证号
        idCard: undefined,
        // 民族,[DC00006]
        national: undefined,
        nationalName: undefined,
        // 现住址
        nowAddress: undefined,
        // 户籍地址
        permanentAddress: undefined,
        // 现住址编码
        presentCode: undefined,
        presentCodeName: undefined,
        // 户籍地编码
        registeredCode: undefined,
        registeredCodeName: undefined,
        // 居民档案id
        residentId: undefined,
        // 姓名
        residentName: undefined,
        // 本人电话
        telephone: undefined,
        // 与居民关系
        relation: undefined,
        relationName: undefined,
        relationOther: undefined,
        //随访人群
        groupsArrays: undefined,
        groupsArraysName: undefined,

        //慢病标签


        //随访方式
        visitWay: undefined,
        visitWayName: undefined,
        //随访类型
        visitWayRules: undefined,
        visitWayRulesName: undefined,
        sendNumber: undefined,
    }
    Reflect.ownKeys(form).forEach(key => {
        if (info[key] != undefined) {
            form[key] = info[key]
        }
    })
    return form
}
export default {
    name: 'BaseInfo',
    components: { CheckBtn, DocAddress },
    props: {
        info: {
            default: () => {
                return {}
            }
        },
        modeEnumList: {
            default: () => {
                return {}
            }
        },
    },
    data() {
        return {
            store: useStore(),
            // 民族
            showNational: false,
            showRelation: false,
            // 现住址
            showPresent: false,
            // 户籍地址
            showRegistered: false,
            // 地址回显使用
            addressRecord: {},
            showTime1: false,
            showTime2: false,
            showGroupsArrays: false,
            showVisitWay: false,
            showVisitWayRules: false,
            //随访人群组件双向绑定变量
            checkGroupsArrays: [],
            //随访方式组件双向绑定变量
            checkVisitWay: [],
            //随访类型组件双向绑定变量
            checkVisitWayRules: [],
            form: {},
            rules: {
                certificateTypeName: [{ required: true, message: '请选择证件类型' }],
                idCard: [{ required: true, message: '请填写证件号码' }],
                residentName: [{ required: true, message: '请填写姓名' }],
                genderName: [{ required: true, message: '请选择性别' }],
                dataBirth: [{ required: true, message: '请选择出生日期' }],
                nationalName: [{ required: true, message: '请选择民族' }],
                currentAge: [{ required: true, message: '请填写年龄' }],
                telephone: [{ required: true, message: '请填写本人电话' }],
                contactName: [{ required: false, message: '请填写联系人姓名' }],
                contactPhone: [{ required: false, message: '请填写联系电话' }],
                presentCodeName: [{ required: true, message: '请选择所在地区' }],
                registeredCode: [{ required: true, message: '请选择所在地区' }],
                groupsArraysName: [{ required: true, message: '请选择' }],
                visitWay: [{ required: true, message: '请选择' }],
                visitWayRulesName: [{ required: true, message: '请选择' }],
            }
        }
    },
    computed: {
        authInfo() {
            return this.store.$state.authInfo
        },
        //随访人群
        groupArrList() {
            let res = []
            res = this.store.getDict('CP00181')
            if (this.info?.groupsArrays) {
                let list = this.info.groupsArrays.split(',').map(item => Number(item))
                res.forEach(item => {
                    item.disabled = true
                    if (list.includes(item.value)) {
                        item.disabled = false
                    }
                })
            } else {
                res.forEach(item => {
                    item.disabled = true
                })
            }
            return res
        },
        //随访类型
        visitWayRulesList() {
            let res = []
            const {visitWay} = this.form
            if (visitWay) {
                res = this.modeEnumList.mode1.filter(item => item.value == visitWay)[0].children
            }
            return res
        },
    },
    watch: {
        'info': {
            handler() {
                this.form = defaultForm(this.info)
                if (this.form.presentCode) {
                    this.addressRecord.presentCode = addToArr(this.form.presentCode)
                }
                if (this.form.registeredCode) {
                    this.addressRecord.registeredCode = addToArr(this.form.registeredCode)
                }
            },
            immediate: true
        },
        'form.visitWay': {
            handler() {
                this.form.visitWayRulesName = ''
                this.form.visitWayRules = ''
                this.checkVisitWayRules = []
            }
        }
    },
    methods: {
        // 民族
        nationalConfirm({ selectedValues, selectedOptions }) {
            this.form.national = selectedValues[0]
            this.form.nationalName = selectedOptions[0].name
            this.showNational = false
        },
        //与居民关系
        relationlConfirm({ selectedValues, selectedOptions }) {
            this.form.relation = selectedValues[0]
            this.form.relationName = selectedOptions[0].name
            this.showRelation = false
        },
        // 现住址
        presentChange(val) {
            const selectedOptions = val.selectedOptions
            this.form.presentCodeName = selectedOptions.map(e => e.text).join('/')
        },
        // 户口地址
        registeredChange(val) {
            const selectedOptions = val.selectedOptions
            this.form.registeredCodeName = selectedOptions.map(e => e.text).join('/')
            if (!this.form.presentCode && selectedOptions.length >= 5) {
                this.form.presentCode = val.value
                this.form.presentCodeName = this.form.registeredCodeName
            }
        },
        // 同步现住址
        setRegisteredAddress() {
            this.$refs.form.validate(['presentCode']).then(res => {
                this.form.registeredCode = this.form.presentCode
                this.form.registeredCodeName = this.form.presentCodeName
                this.form.permanentAddress = this.form.nowAddress
                this.addressRecord.registeredCode = addToArr(this.form.presentCode)
            }).catch(err => console.warn(err))
        },
        toTel() {
            // 创建一个电话号码的URL
            let phoneNumber = this.form.telephone // 替换为需要拨打的号码
            //判断是否是iOS环境
            if (isIOSWebKit) {
                console.log('tel:', phoneNumber)
                callMobile('startCallUpActivity', phoneNumber)
            } else {
                let url = 'tel://' + encodeURIComponent(phoneNumber)
                // 创建一个a标签
                let a = document.createElement('a')
                a.href = url
                // 触发a标签的点击事件
                a.click()
            }

        },
        //随访人群
        groupsArraysConfirm() {
            let res = []
            this.groupArrList.forEach(item => {
               let selected = this.checkGroupsArrays.filter(i => i == item.value)
                if (selected && selected.length) {
                    res.push(item.name)
                }
            })
            if (this.checkGroupsArrays && this.checkGroupsArrays.length) {
                this.form.groupsArrays = this.checkGroupsArrays.join()
                this.form.groupsArraysName = res.join()
            } else {
                this.form.groupsArrays = ''
                this.form.groupsArraysName = ''
            }
            this.showGroupsArrays = false
        },
        //随访方式
        visitWayConfirm() {
            if (this.checkVisitWay) {
                this.store.getDict('CP00179').forEach(item => {
                    if (item.value == this.checkVisitWay) {
                        this.form.visitWay = item.value
                        this.form.visitWayName = item.name
                    }
                })
            } else {
                this.form.visitWay = ''
                this.form.visitWayName = ''
            }
            this.showVisitWay = false
        },
        //随访类型
        visitWayRulesConfirm() {
            let res = []
            this.visitWayRulesList.forEach(item => {
                let selected = this.checkVisitWayRules.filter(i => i == item.value)
                if (selected && selected.length) {
                    res.push(item.name)
                }
            })
            if (this.checkVisitWayRules && this.checkVisitWayRules.length) {
                this.form.visitWayRules = this.checkVisitWayRules.join()
                this.form.visitWayRulesName = res.join()
            } else {
                this.form.visitWayRules = ''
                this.form.visitWayRulesName = ''
            }
            this.showVisitWayRules = false
        },
        onSubmit() {
            return new Promise((resolve, reject) => {
                this.$refs.form.validate().then(() => {
                    const {
                        personId,
                        visitWay,
                        visitWayRules ,
                        groupsArrays,
                        sendNumber,
                        ...others
                    } = this.form
                    let par = {
                        visitWay,
                        visitWayRules,
                        groupsArrays,
                        sendNumber,
                        residentInfoId: this.form.residentInfoId,
                        residentsRecord: {
                            ...this.info,
                            ...others,
                            groupsArrays: this.info.groupsArrays,
                            id: this.form.personId
                        }
                    }
                    resolve(par)
                }).catch((e) => {
                    console.warn('baseInfo error', e)
                })
            })
        }
    }
}
</script>

<style scoped lang='less'>
.title {
    font-weight: bold;
    margin-bottom: 20px;
}

.label-title {
    font-size: 13px;
    color: #595959;
    font-weight: 500;

    &::after {
        content: "*";
        color: red;
        font-weight: bold;
        margin-left: 4px;
    }
}

.no-req-label {
    font-size: 13px;
    color: #595959;
    font-weight: 500;
}

.form-input {
    padding: 8px 12px;
    border-radius: 8px;
}

.input-back {
    background: #FAFAFA;
}

.input-white {
    background: #FFFFFF;
}

.tel-back {
    background: #F5F5F5;
    padding: 8px;
    border-radius: 0px 0px 8px 8px;
}

.death-r {
    background: #F5F5F5;
    border-radius: 0px 0px 8px 8px;
    padding: 8px 12px;
}

.tel {
    background: #FFFFFF;
    padding: 8px;
    border-radius: 8px;
}

.tel-label {
    color: #607FF0;
    font-weight: bold;
}

.p-12-0 {
    padding: 12px 0px;
}

//灰色
.greyColor {
    color: var(--van-text-color-2);
}

//确定按钮颜色
.blueColor {
    color: var(--van-primary-color)
}

.pop-title {
    color: #262626;
    font-size: 16px;
    line-height: 24px;
    font-weight: bold;
}
:deep(.van-cell-group--inset) {
    overflow: visible;
}

:deep(.van-cell) {
    overflow: visible;
}

/*:deep(.van-field__error-message) {
    position: absolute;
    margin-top: 3px;
}*/

:deep(.van-cell:after) {
    border-bottom: 0px;
}

:deep(.van-radio__icon--checked.van-radio__icon--dot .van-radio__icon--dot__icon) {
    background: #FFFFFF;
}

:deep(.van-radio__icon--checked.van-radio__icon--dot) {
    background: var(--van-button-primary-background)
}

:deep(.van-popup) {
    min-height: 30%!important;
}

</style>