<template>
    <van-popup :show="show" position="bottom"
        :teleport="teleport"
        class="diagnose-picker">
        <van-picker
            title="请选择"
            :columns="array"
            :columns-field-names="fieldNames"
            v-model="innerValue"
            @confirm="onConfirm"
            @cancel="onCancel"
        >
            <template #columns-top>
                <div class="px-3">
                    <van-field v-model="searchValue" placeholder="请输入" clearable maxlength="100"/>
                </div>
            </template>
        </van-picker>
    </van-popup>
</template>

<script>
import  { queryDiseaseCode } from '@/api/doctor/disease.js'

export default {
    props: {
        show: Boolean,
        value: [String, Number],
        fieldNames: {
            type: Object,
            default: () => {
                return {text: 'name', value: 'icdCode'}
            }
        },
        // 疾病类型
        diseaseType: [String, Number],
        teleport: [String, Element]
    },
    emits: ['update:show', 'update:value', 'change'],
    data() {
        return {
            innerValue: undefined,
            searchValue: '',
            diagnoseNameList: []
        }
    },
    computed: {
        array() {
            const array = this.diagnoseNameList || []
            return array.filter(e => e.name.startsWith(this.searchValue))
        }
    },
    methods: {
        load() {
            queryDiseaseCode({ diseaseType: this.diseaseType }).then(res => {
                const result = []
                for (let item of res.data) {
                    item.name = item.diseaseName + '(' + item.icdCode + ')'
                    result.push(item)
                }
                this.diagnoseNameList = result
            })
        },
        onConfirm({ selectedValues, selectedOptions }) {
            this.$emit('update:value', selectedValues[0])
            this.$emit('change', selectedOptions[0] || {})
            this.$emit('update:show', false)
            this.searchValue = ''
        },
        onCancel() {
            this.$emit('update:show', false)
        }
    },
    watch: {
        value: {
            handler(value) {
                if (value == null) return
                this.innerValue = [value]
            },
            immediate: true
        },
        diseaseType: {
            handler() {
                this.load()
            },
            immediate: true
        }
    }
}
</script>

<style lang="less" scoped>

</style>
