<template>
    <view class="box">
        <view class="search-box">
            <view class="dropdown-wrapper">
                <picker
                    @change="bindPickerChange"
                    :value="selectValue"
                    :range="option"
                >
                    <view class="picker-content">
                        <text>{{ option[selectValue] }}</text>
                    </view>
                </picker>
            </view>
            <view class="search-input">
                <input
                    type="text"
                    placeholder="输入设备全称或简称"
                    v-model="keyWord"
                    placeholder-class="placeholder-style"
                />
            </view>
            <view class="search-btn" @click="queryList"> 搜索 </view>
        </view>

        <view class="cardList">
            <view class="card" v-for="item in devs" :key="item.clientId">
                <view class="deviceName" @click="gotoPath(item)">
                    <text>{{ formatDevName(item.devName) }}</text>
                    <image src="../../static/arrTwo.png" mode="" />
                </view>
                <view v-if="item.online == 1">
                    <view class="online" v-if="item.existFlag == 1">
                        <view class="cardInfo">当前有人</view>
                        <view class="wcTimes" v-if="item.presenceChangeTime"
                            >进入时间{{
                                forMateTime(item.presenceChangeTime)
                            }}</view
                        >
                    </view>
                    <view class="cardTwo" v-else>
                        <view class="cardError" v-if="item.presenceChangeTime"
                            >当前无人</view
                        >
                        <view class="endTime" v-if="item.presenceChangeTime"
                            >离开时间
                            {{ forMateTime(item.presenceChangeTime) }}</view
                        >
                        <view class="cardError" v-else>当前无人</view>
                    </view>
                </view>
                <view v-else style="margin-top: 18rpx">
                    <text style="color: #8b939f; font-size: 24rpx"
                        >设备离线</text
                    >
                    <view
                        style="
                            margin-top: 18rpx;
                            color: chocolate;
                            font-size: 24rpx;
                        "
                        >离线时间 {{ forMateTime(item.onoffTime) }}</view
                    >
                </view>
                <view class="cardImage" v-if="item.online == 0">
                    <image src="../../static/offline_small.png" mode="" />
                </view>
                <view class="cardImage" v-else>
                    <image src="../../static/ln_small.png" mode="" />
                </view>
            </view>
        </view>

        <alarModel v-if="showModle" />
    </view>
</template>

<script>
import MqttService from "../../utils/globalMqtt.js";

export default {
    data() {
        return {
            keyWord: "",
            option: ["全部", "离线", "在线"],
            selectValue: 0,
            devs: [],
            isInitAlarm: false,
            showModle: false,
            devClientidList: [],
            unsubscribeFns: [],
        };
    },
    methods: {
        onClickLeft() {
            uni.navigateBack({
                delta: 0,
            });
        },
        bindPickerChange(e) {
            this.selectValue = e.detail.value;
            this.queryList();
        },
        gotoPath(item) {
            uni.setStorageSync("devIdDetail", item.devId);
            uni.setStorageSync("clientIDetail", item.clientId);
            uni.setStorageSync("northAngle", item.northAngle);
            uni.navigateTo({
                url:
                    "/pagesA/deviceDetail/deviceDetail?devItem=" +
                    JSON.stringify(item),
            });
        },
        forMateTime(inputTime) {
            if (!inputTime) return "";
            const [datePart, timePart] = inputTime.split(" ");
            const [year, month, day] = datePart.split("-");
            const [hours, minutes] = timePart.split(":");
            return `${parseInt(month)}月${parseInt(day)}日${hours}:${minutes}`;
        },
        // 查询列表
        queryList() {
            uni.showLoading({
                title: "查询中...",
            });
            let now = new Date();
            let status = "";
            if (this.selectValue == 0) {
                status = null;
            } else if (this.selectValue == 1) {
                status = "0";
            } else if (this.selectValue == 2) {
                status = "1";
            }
            this.$http
                .post("wap/device/deviceList", {
                    userId: uni.getStorageSync("userId"),
                    keyWord: this.keyWord,
                    status: status,
                })
                .then((res) => {
                    if (res.data.code == 200) {
                        let devs = res.data.data;
                        for (let i = 0; i < devs.length; i++) {
                            if (
                                devs[i].installPosition == "Toilet" &&
                                devs[i].stayTimes?.length > 0
                            ) {
                                devs[i].wcTimes = devs[i].stayTimes.length;
                            } else {
                                devs[i].wcTimes = 0;
                            }
                        }
                        this.devs = devs;
                        this.devClientidList = devs.map(
                            (item) => item.clientId
                        );
                        this.subscribePresenceChange(this.devClientidList);
                    }
                    uni.hideLoading();
                });
        },

        // 订阅列表中所有设备的presence_change主题
        subscribePresenceChange(clientIdList) {
            // 遍历订阅
            if (clientIdList.length == 0) return;

            clientIdList.forEach((clientId) => {
                const topic = `/dev/${clientId}/presence_change`;
                const unsubscribe = MqttService.subscribe(
                    "DATA",
                    topic,
                    (message, msgTopic) => {
                        const dataMatch = msgTopic.match(
                            /^\/dev\/(.+)\/presence_change$/
                        );
                        if (dataMatch) {
                            // console.log("presence_change", message, msgTopic);
                            const messageObj = JSON.parse(message);
                            const id = dataMatch[1];
                            const format = (date) => {
                                const Y = date.getFullYear();
                                const M = String(date.getMonth() + 1).padStart(
                                    2,
                                    "0"
                                );
                                const D = String(date.getDate()).padStart(
                                    2,
                                    "0"
                                );
                                const h = String(date.getHours()).padStart(
                                    2,
                                    "0"
                                );
                                const m = String(date.getMinutes()).padStart(
                                    2,
                                    "0"
                                );
                                const s = String(date.getSeconds()).padStart(
                                    2,
                                    "0"
                                );
                                return `${Y}-${M}-${D} ${h}:${m}:${s}`;
                            };

                            this.devs.forEach((item) => {
                                if (item.clientId == id) {
                                    item.existFlag = messageObj.presence;
                                    item.presenceChangeTime = format(
                                        new Date(messageObj.timestamp * 1000)
                                    );
                                }
                            });
                        }
                    }
                );
                this.unsubscribeFns.push(unsubscribe); // 保存取消订阅的方法
            });
        },

        formatDevName(name) {
            return typeof name === "string" && name.length > 6
                ? name.slice(0, 6) + "..."
                : name;
        },
    },
    onLoad() {},
    onShow() {
        this.queryList();
        this.showModle = true;
    },
    onHide() {
        this.showModle = false;
        if (this.unsubscribeFns) {
            this.unsubscribeFns.forEach((fn) => {
                if (fn) {
                    fn(); // 执行一次取消订阅
                }
            });
            this.unsubscribeFns = [];
        }
    },
    onUnload() {},
    onPullDownRefresh() {
        this.queryList();
        setTimeout(() => {
            uni.stopPullDownRefresh();
        }, 2000);
    },
};
</script>

<style lang="less" scoped>
.box {
    padding: 10rpx 18rpx;
    overflow: scroll;
    width: 100vw;
    height: 100vh;
    background: linear-gradient(180deg, #faede2 0%, #f4f4f4 100%);
    box-sizing: border-box;

    .search-box {
        display: flex;
        align-items: center;
        width: 100%;
        height: 80rpx;
        background: #fff;
        border-radius: 40rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);

        .dropdown-wrapper {
            padding: 0 10rpx;
            width: 160rpx;
            height: 100%;
            display: flex;
            align-items: center;

            .picker-content {
                display: flex;
                align-items: center;
                font-size: 28rpx;
                color: #333;
            }
        }

        .search-input {
            flex: 1;
            height: 100%;
            padding: 0 20rpx;

            input {
                width: 100%;
                height: 100%;
                font-size: 28rpx;
            }

            .placeholder-style {
                color: #999;
                font-size: 28rpx;
            }
        }

        .search-btn {
            width: 120rpx;
            height: 60rpx;
            background: chocolate;
            color: white;
            border-radius: 30rpx;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28rpx;
            margin-left: 10rpx;
        }
    }

    .list-box {
        margin-top: 30rpx;
    }

    .cardList {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: space-between;

        .card {
            position: relative;
            width: 350rpx;
            height: 305rpx;
            margin-top: 18rpx;
            background: #ffffff;
            border: 2.5rpx solid;
            border-color: #ffffff;
            border-radius: 37rpx;
            padding: 37rpx 25rpx;
            box-shadow: 0rpx 2.34rpx 14.06rpx rgba(12, 26, 52, 0.03);
            box-sizing: border-box;

            .deviceName {
                width: 300rpx;
                display: flex;
                align-items: center;
                overflow: hidden;

                text {
                    width: 300rpx;
                    color: #111111;
                    font-size: 32rpx;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                }

                image {
                    width: 10rpx;
                    height: 20rpx;
                    margin-left: 15rpx;
                }
            }

            .cardInfo {
                margin-top: 18rpx;
                color: #0db886;
                font-size: 24rpx;
            }

            .wcTimes {
                margin-top: 18rpx;
                color: chocolate;
                font-size: 24rpx;
            }

            .cardTwo {
                margin-top: 18rpx;

                .cardError {
                    color: #8b939f;
                    font-size: 24rpx;
                }

                .endTime {
                    margin-top: 18rpx;
                    color: chocolate;
                    font-size: 24rpx;
                }
            }

            .cardTime {
                margin-top: 18rpx;
                color: #999999;
                font-size: 24rpx;
            }

            .cardImage {
                position: absolute;
                bottom: 10rpx;
                left: 20rpx;

                image {
                    width: 86rpx;
                    height: 88rpx;
                }
            }
        }
    }
}
</style>
