<template>
    <van-popup v-model:show="visible" position="bottom" style="height: 60%">
        <div class="pt-4 h-full flex flex-col popup-checkbox">
            <div class="flex justify-between shrink-0 pb-2">
                <button class="van-picker__cancel van-haptics-feedback" @click="visible = false" >取消</button>
                <span class="text-16" >请选择设备（单选）</span>
                <button class="van-picker__confirm van-haptics-feedback" @click="onSubmit" >确认</button>
            </div>
            <div class="bottom-small-line"></div>
            <van-radio-group v-model="deviceNo" shape="square"
                class="px-4 pb-4 pt-2 grow overflow-y-auto"
                v-if="deviceList.length">
                <van-radio v-for="item in deviceList" :key="item.deviceNo" :name="item.deviceNo"
                    label-position="left"
                    class="justify-between radio-bt">
                    <div :class="['flex items-denter', {'text-primary': item.deviceNo === deviceNo}]">
                        <doc-icon type="doc-thermometer" style="font-size: .21rem;"/>
                        <span class="text-16 ml-2" >{{ item.deviceNo }}</span>
                    </div>
                </van-radio>
            </van-radio-group>
            <div v-else class="h-full flex items-center text-center"
                style="padding: 0 20%;line-height: 1.5;color: #595959;">
                本机构尚未绑定设备，请联系管理人员绑定设备
            </div>
        </div>
    </van-popup>
</template>

<script>
import { getPressureDevices, getPressureData, startPressureData } from '@/api/base.js'
import { useStore } from '@/doctor/store/index.js'
import { showToast } from 'vant'
import dayjs from 'dayjs'

export default {
    props: {
        pressureObj: {
            required: true,
            default: () => ({})
        }
    },
    data() {
        return {
            store: useStore(),
            visible: false,
            // 选中的设备编号
            deviceNo: undefined,
            // { deviceNo, id }
            deviceList: [],
            deviceInfo: null,
            // 最后一次测量值
            lastValue: null,
            // 点击测量时的时间
            valueTime: null,
            // 测量循环次数
            loopMark: 0
        }
    },
    computed: {
        activeDevice() {
            return this.deviceList.find(item => item.deviceNo === this.deviceNo) || {}
        },
        authInfo() {
            return this.store.authInfo
        }
    },                                                                   
    created() {
        this.init()
    },
    methods: {
        init() {
            // this.loadDevice()
            this.pressureObj.loadDevice = () => {
                this.loadDevice()
            }
            // 获取测量值
            this.pressureObj.getValue = async(cb) => {
                await startPressureData(this.deviceNo)
                this.valueTime = dayjs()
                this.loadValue(cb)
            }
            // 获取设备信息
            this.pressureObj.getDevice = () => {
                return this.deviceInfo || {}
            }
            // 选择设备
            this.pressureObj.deviceSelect = (cb) => {
                this.visible = true
            }
            // 是否在测量中
            this.pressureObj.getLoadMark = () => {
                return this.loopMark > 0
            }
        },
        loadDevice() {
            // 372 || 
            getPressureDevices(this.authInfo.unitId).then(res => {
                console.log('getPressureDevices', res)
                this.deviceList = res.data || []
                if (!this.deviceList.length) {
                    this.deviceCheck(1)
                } else {
                    this.deviceCheck(3)
                } 
            })
        },
        loadValue(cb) {
            if (!this.deviceNo) {
                showToast('未选择设备')
                console.warn('未选择设备')
                return
            }
            if (this.loopMark >= 8) {
                this.loopMark = 0
                this.deviceCheck(2)
                cb && cb(null)
                return
            }
            this.loopMark++
            // '06B32312010330' || 
            getPressureData(this.deviceNo).then(res => {
                const result = res.data || []
                if (result.length) {
                    result.sort((a, b) => {
                        return b.id - a.id
                    })
                    let val = result[0]
                    if (dayjs(val.created).isAfter(this.valueTime)) {
                        this.lastValue = val
                        this.loopMark = 0
                        this.deviceCheck(3)
                        showToast('测量成功')
                        cb && cb(val)
                        return
                    }
                }
                setTimeout(() => {
                    this.loadValue(cb)
                }, 8000)
            })
        },
        // 设备情况检查
        deviceCheck(type) {
            if (type == 1) {
                this.deviceInfo = {
                    type: 1,
                    data: '本机构尚未绑定设备，请联系管理人员绑定设备'
                }
            } else if (type == 2) {
                // this.deviceInfo = {
                //     type: 2,
                //     data: '设备异常，请检查设备重新测量'
                // }
                showToast('设备异常，请检查设备重新测量', )
            } else if (type == 3) {
                // 选择设备
                this.deviceInfo = {
                    type: 3,
                    data: this.activeDevice.deviceNo || null
                }
            }
        },
        onSubmit() {
            const device = this.activeDevice
            this.deviceInfo = { data: device.deviceNo, type: 3, }
            this.visible = false
        }
    }
}
</script>

<style lang="less" scoped>
.radio-bt {
    border: 1px solid #F0F0F0;
    padding: 12px 20px;
    border-radius: 40px;
    margin-bottom: 12px;
    &[aria-checked="true"] {
        border-color: var(--van-primary-color);
    }
}
</style>
