<template>
    <view class="container">
        <view :class="'space-height ' + (showSelectBtn ? 'add-height' : '')"></view>

        <van-popup :show="isShowShopContainer" position="left" @close="handleCloseShopContainer">
            <view class="shop-container">
                <view style="background: #f8f8f8">
                    <view class="shop-info-container">
                        <view>
                            <image class="shop-head-icon" :src="userInfo.info.headimg ? userInfo.info.headimg : '/static/resource/images/logo.png'"></image>
                        </view>
                        <view class="shop-head-name">{{ userInfo.info.name }}</view>
                    </view>
                    <view class="group-item flex-row" v-for="(item, index) in groupTreeList" :key="index">
                        <view class="flex-row">
                            <view :style="'width: ' + item.Level * 44 + 'rpx;'"></view>
                            <view v-if="item.leaf" style="width: 44rpx"></view>
                            <image
                                v-else
                                class="group-leaf-icon"
                                src="/static/resource/images/shouqi.png"
                                :style="item.Leaf ? 'transform: rotate(90deg);' : ''"
                                :data-index="index"
                                @tap="groupTreeLeaf"
                            ></image>
                            <image
                                class="group-select-icon"
                                :src="
                                    selectedShopInfo.id == item.id || (!selectedShopInfo.id && item.id == userInfo.info.id)
                                        ? '/static/resource/images/xuanzhong.png'
                                        : '/static/resource/images/weixuanzhong.png'
                                "
                                @tap="loadChildrenDevice"
                                :data-data="item"
                            ></image>
                        </view>

                        <button
                            :data-index="index"
                            @tap="loadChildrenDevice"
                            @longpress="groupTreeLeaf"
                            :data-data="item"
                            class="group-text"
                            :style="'width: calc(100% - ' + ((item.Level + 1) * 44 + 50) + 'rpx);'"
                        >
                            {{ item.name + '[' + item.own_device_cnt + '/' + item.all_device_cnt + ']' }}
                        </button>
                    </view>
                </view>
            </view>
        </van-popup>

        <view class="batterylist-container">
            <!-- <view wx:for="{{deviceList}}" wx:key="unique" class="battery-item {{(item.deviceHighlight && item.deviceHighlight==1) || (item.mac_id == macid)?'battery-highlight-item':''}}"> -->
            <view :class="'battery-item ' + (item.isSelect == 1 ? 'battery-highlight-item' : '')" v-for="(item, index) in deviceList" :key="index">
                <view class="batter-info-group flex-row" @tap="bindSelect" :data-index="index">
                    <view class="battery-icon">
                        <image class="battery-icon-img" :src="iconList[item.icon].normal"></image>
                    </view>
                    <view style="width: calc(100% - 145rpx); padding-left: 23rpx">
                        <view class="battery-text flex-row flex-between">
                            <view>名称：{{ item.name }}</view>
                        </view>
                        <view class="battery-text">编号：{{ item.mac_id }}</view>
                        <view class="battery-text">状态：{{ item.expire == 1 ? '到期' : item.online == 1 ? '在线' : '离线' }}</view>
                        <view class="battery-text">时间：{{ tools.formatTime(item.gps_time) }}</view>
                    </view>
                </view>

                <image
                    v-if="item.btid != ''"
                    class="bt-icon ble-info"
                    :src="bt_loading ? '/static/resource/images/lanyad.gif' : item.isConnect ? '/static/resource/images/lanya.png' : '/static/resource/images/lanyad.png'"
                    @tap.stop.prevent="bindBTState"
                    :data-id="index"
                ></image>

                <view class="battery-text battery-info" style="color: #0ec193" @tap.stop.prevent="bindToInfo" :data-index="index">
                    详情
                    <image class="battery-info-img" src="/static/resource/images/fanhui.png"></image>
                </view>

                <view class="battery-text battery-credit flex-row" @tap.stop.prevent="bindCredit" :data-index="index">续费</view>

                <view class="op-group flex-row flex-around">
                    <view v-if="item.bms == 1" class="op-item" @tap.stop.prevent="bindToBMS" :data-index="index">
                        <image class="op-icon" src="/static/resource/images/BMS.png"></image>
                        <view class="op-des">BMS</view>
                    </view>
                    <view class="op-item" @tap.stop.prevent="bindLocal" :data-index="index">
                        <image class="op-icon" src="/static/resource/images/dingwei2.png"></image>
                        <view class="op-des">定位</view>
                    </view>
                    <view class="op-item" @tap.stop.prevent="bindAlarm" :data-index="index">
                        <image class="op-icon" src="/static/resource/images/baojing.png"></image>
                        <view class="op-des">报警</view>
                    </view>
                    <view class="op-item" @tap.stop.prevent="bindToSet" :data-index="index">
                        <image class="op-icon" src="/static/resource/images/set.png"></image>
                        <view class="op-des">设置</view>
                    </view>
                </view>
            </view>
        </view>

        <i-load-more :tip="isLoading ? '正在加载 ...' : '没有更多信息啦'" :loading="isLoading" />

        <view class="top-bar-container">
            <view class="system-stauts-bar"></view>
            <view class="system-navigator">
                <image @tap="handleReturn" class="return-icon" src="/static/resource/images/fanhui2.png"></image>
                <image v-if="userInfo.type == 'group'" @tap="handleShowShopContainer" class="bar-shop-icon" src="/static/resource/images/liebiao.png"></image>
                <image v-if="userInfo.type == 'user'" @tap="handleAddDevice" class="bar-shop-icon" src="/static/resource/images/jia.png"></image>
                <view v-if="userInfo.type == 'group'" class="top-title">
                    {{ selectedShopInfo ? selectedShopInfo.name : userInfo.info.name }}
                </view>
            </view>
            <view class="search-container flex-row flex-between">
                <view class="search-btn flex-row" style="margin-right: 20rpx" @tap="scanCode">
                    <image style="width: 40rpx; height: 40rpx" src="/static/resource/images/scan-i.png"></image>
                </view>
                <view class="search-control flex-row flex-between">
                    <input
                        type="text"
                        class="input-search"
                        :value="seach_value"
                        confirm-type="搜索"
                        placeholder="请输入"
                        placeholder-style="font-size: 12px;"
                        @input="bindInputSearch"
                    />
                </view>
                <view class="search-btn flex-row">
                    <view class="btn-search" @tap="bindHandleSearch">搜索</view>
                    <image v-if="userInfo.type == 'group'" @tap="bindGroupSearch" style="width: 40rpx; height: 40rpx" src="/static/resource/images/youjiantou.png"></image>
                </view>
            </view>
            <view class="def-nav-container">
                <view class="order-type-container flex-row flex-around">
                    <view :class="'order-type-item ' + (search_type == 0 ? 'order-type-selected' : '')" data-searchtype="0" @tap="bindSearchType">
                        全部
                        <text class="l-tmp">({{ all_count }})</text>
                    </view>
                    <view :class="'order-type-item ' + (search_type == 1 ? 'order-type-selected' : '')" data-searchtype="1" @tap="bindSearchType">
                        在线
                        <text class="l-tmp">({{ online_count }})</text>
                    </view>
                    <view :class="'order-type-item ' + (search_type == 2 ? 'order-type-selected' : '')" data-searchtype="2" @tap="bindSearchType">
                        离线
                        <text class="l-tmp">({{ offline_count }})</text>
                    </view>
                    <view :class="'order-type-item ' + (search_type == 3 ? 'order-type-selected' : '')" data-searchtype="3" @tap="bindSearchType">
                        到期
                        <text class="l-tmp">({{ expire_count }})</text>
                    </view>
                </view>
                <!--view wx:if="{{showSelectBtn}}" class="bath-op flex-row flex-end">
        <view class="batch-transfer-btn" type="primary" size="mini" bindtap="bindBatchTransfer">批量转移</view>
        <view class="batch-alter-btn" type="warn" size="mini" bindtap="bindBatchAlter">批量修改</view>
        <view class="batch-cancel-btn" type="warn" size="mini" bindtap="bindCancelSelectAllBattery">取消</view>
      </view-->
            </view>
        </view>
    </view>
</template>
<script module="tools" lang="wxs" src="@/pages/common/wxs/tools.wxs"></script>
<script>
import noMore from '@/component/nomore/nomore';
import iDrawer from '@/component/iview/drawer/index';
import iCollapse from '@/component/iview/collapse/index';
import iCollapseItem from '@/component/iview/collapse-item/index';
import iLoadMore from '@/component/iview/load-more/index';
import comEleQuantity from '@/component/comEleQuantity/comEleQuantity';
// pages/device/device.js
var config = require('../../common/config.js');
var http = require('../../common/http.js');
var common = require('../../common/common.js');
var storage = require('../../common/storage.js');
var bluetooth = require('../../common/bluetooth.js');
const LIMT_PAGE = 5;
export default {
    components: {
        noMore,
        iDrawer,
        iCollapse,
        iCollapseItem,
        iLoadMore,
        comEleQuantity
    },
    data() {
        return {
            isLoading: false,
            isShowShopContainer: false,
            iconList: [],

            userInfo: {
                info: {
                    headimg: false,
                    name: '',
                    id: ''
                },

                type: ''
            },

            selectedShopInfo: {
                id: '',
                name: ''
            },

            deviceList: [],
            start_page: 1,
            limit_page: LIMT_PAGE,
            search_type: 0,
            showSelectBtn: false,
            selectedAll: false,
            selectedNum: 0,
            all_count: 0,
            online_count: 0,
            offline_count: 0,
            expire_count: 0,
            groupTreeList: [],
            groupList: [],
            seach_value: '',
            search: '',
            macid: '',
            deviceSearchList: [],
            btmacid: '',
            btInfo: {},
            baud: '',
            bt_loading: false,
            normal: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const selectedShopInfo = storage.getSelectedShopInfo();
        const macid = options.macid;
        if (selectedShopInfo) {
            this.setData({
                selectedShopInfo: selectedShopInfo
            });
        }
        if (macid) {
            this.setData({
                macid: macid
            });
        }
        this.loadIconList();
        this.loadUserInfo();
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        const is_fresh = storage.getRefreshDeviceoPage();
        if (is_fresh) {
            this.loadUserInfo();
            storage.setRefreshDeviceoPage(false);
        }
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        console.log('dd');
        this.refreshLoadDeviceList();
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        if (this.isLoading) {
            return;
        }
        this.setData({
            isLoading: true
        });
        this.start_page++;
        this.loadDeviceList();
    },
    methods: {
        /**
         * 获取首页带设备号数据
         */
        loadDeviceSearchList: function () {
            const macid = this.macid;
            const start_page = this.start_page;
            this.setData({
                deviceSearchList: []
            });
            console.log(macid);
            console.log(start_page);
            //console.log(macid+'==='+start_page)
            if (!macid || start_page != 1) {
                return false;
            }
            const that = this;
            const pData = {
                size: that.limit_page,
                page: 1,
                type: that.search_type == 1 ? 'ONLINE' : that.search_type == 2 ? 'OFFLINE' : that.search_type == 3 ? 'EXPIRE' : 'ALL',
                id: that.selectedShopInfo.id,
                search: that.macid
            };
            http.postApi(config.API_BATTERY_LIST, pData, (resp) => {
                if (resp.data.code === 200) {
                    var reponseList = resp.data.data.list;
                    for (var i = 0; reponseList.length > i; i++) {
                        reponseList[i].display_bms = reponseList[i].display_bms - 0;
                        if (that.userInfo.type != 'group') {
                            if (reponseList[i].display_bms - 0 === 0) {
                                reponseList[i].isBms = 0;
                            } else {
                                reponseList[i].isBms = 1;
                            }
                        } else {
                            reponseList[i].isBms = 1;
                        }
                    }
                    that.setData({
                        deviceSearchList: reponseList
                    });
                    console.log('zzzxxx');
                    that.handleMergeData(that.deviceSearchList, 2);
                } else {
                    common.simpleToast(resp.data.msg);
                }
            });
        },

        handleCloseShopContainer: function () {
            this.setData({
                isShowShopContainer: false
            });
        },

        handleShowShopContainer: function () {
            this.setData({
                isShowShopContainer: true
            });
        },

        bindClickMainShop: function () {
            if (this.selectedShopInfo == {}) {
                return;
            }
            this.setData({
                search: '',
                seach_value: '',
                selectedShopInfo: {}
            });
            this.refreshLoadDeviceList();
        },

        loadIconList: function () {
            this.iconList = storage.getIconList();
            if (!this.iconList) {
                http.postApi(config.API_BATTERY_ICON_LIST, {}, (resp) => {
                    if (resp.data.code === 200) {
                        storage.setIconList(resp.data.data.list);
                        this.setData({
                            iconList: resp.data.data.list
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            } else {
                this.setData({
                    iconList: this.iconList
                });
            }
        },

        loadUserInfo: function () {
            const userInfo = storage.getUserInfo();
            if (!userInfo) {
                http.postApi(config.API_USER_INFO, {}, (resp) => {
                    if (resp.data.code === 200) {
                        storage.setUserInfo(resp.data.data);
                        this.setData({
                            userInfo: resp.data.data
                        });
                        this.refreshLoadDeviceList();
                        this.loadGroupTree();
                        /*this.setData({
              shopList: common.shopListToTree(storage.getTotalStatisList(), me.data.userInfo.shop_id)
            })*/
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            } else {
                this.setData({
                    userInfo: userInfo
                });
                this.refreshLoadDeviceList();
                this.loadGroupTree();
            }
        },

        loadChildrenDevice: function (e) {
            this.setData({
                search: '',
                seach_value: '',
                selectedShopInfo: e.currentTarget.dataset.data
            });
            storage.setSelectedShopInfo(e.currentTarget.dataset.data);
            this.refreshLoadDeviceList();
        },

        refreshLoadDeviceList: function () {
            if (this.isLoading) {
                return;
            }
            this.setData({
                deviceList: [],
                isLoading: true
            });
            common.loading();
            this.limit_page = LIMT_PAGE;
            this.start_page = 1;
            this.loadDeviceList();
            console.log('this.data.seach_value', this.seach_value);
            if (this.seach_value.length !== 0) {
                this.loadDeviceSearchList();
            }
        },

        loadDeviceList: function () {
            const that = this;
            const pData = {
                size: that.limit_page,
                page: that.start_page,
                type: that.search_type == 1 ? 'ONLINE' : that.search_type == 2 ? 'OFFLINE' : that.search_type == 3 ? 'EXPIRE' : 'ALL',
                id: that.selectedShopInfo.id,
                search: that.search
            };
            http.postApi(config.API_BATTERY_LIST, pData, (resp) => {
                uni.hideLoading();
                uni.stopPullDownRefresh();
                if (resp.data.code === 200) {
                    let deviceList = that.deviceList;
                    var reponseList = resp.data.data.list;
                    var s_index = -1;
                    const _deviceInfo = storage.getSelectedDeviceInfo();
                    //修改接口异步为同步
                    if (_deviceInfo && that.userInfo.type == 'group') {
                        that.asyncRefhDeviceInfo(_deviceInfo).then((test) => {
                            const deviceInfo = storage.getSelectedDeviceInfo();
                            for (var i = 0; reponseList.length > i; i++) {
                                if (deviceInfo && deviceInfo.mac_id === reponseList[i].mac_id) {
                                    s_index = i;
                                }
                                reponseList[i].isSelect = 0;
                                reponseList[i].display_bms = reponseList[i].display_bms - 0;
                                if (that.userInfo.type != 'group') {
                                    if (reponseList[i].display_bms - 0 === 0) {
                                        reponseList[i].isBms = 0;
                                    } else {
                                        reponseList[i].isBms = 1;
                                    }
                                } else {
                                    reponseList[i].isBms = 1;
                                }
                            }
                            if (s_index !== -1 && this.search_type == 0) {
                                reponseList.splice(s_index, 1);
                            }
                            if (deviceInfo && that.start_page == 1 && this.search_type == 0) {
                                deviceInfo.isSelect = 1;
                                reponseList.unshift(deviceInfo);
                            }
                            deviceList.push.apply(deviceList, reponseList);
                            that.setData({
                                deviceList: deviceList,
                                isLoading: false,
                                all_count: resp.data.data.all_count,
                                online_count: resp.data.data.online_count,
                                offline_count: resp.data.data.offline_count,
                                expire_count: resp.data.data.expire_count
                            });
                        });
                    } else {
                        const deviceInfo = storage.getSelectedDeviceInfo();
                        for (var i = 0; reponseList.length > i; i++) {
                            if (deviceInfo && deviceInfo.mac_id === reponseList[i].mac_id) {
                                s_index = i;
                            }
                            reponseList[i].isSelect = 0;
                            reponseList[i].display_bms = reponseList[i].display_bms - 0;
                            if (that.userInfo.type != 'group') {
                                if (reponseList[i].display_bms - 0 === 0) {
                                    reponseList[i].isBms = 0;
                                } else {
                                    reponseList[i].isBms = 1;
                                }
                            } else {
                                reponseList[i].isBms = 1;
                            }
                        }
                        if (s_index !== -1 && this.search_type == 0) {
                            reponseList.splice(s_index, 1);
                        }
                        if (deviceInfo && that.start_page == 1 && this.search_type == 0) {
                            deviceInfo.isSelect = 1;
                            reponseList.unshift(deviceInfo);
                        }
                        deviceList.push.apply(deviceList, reponseList);
                        that.setData({
                            deviceList: deviceList,
                            isLoading: false,
                            all_count: resp.data.data.all_count,
                            online_count: resp.data.data.online_count,
                            offline_count: resp.data.data.offline_count,
                            expire_count: resp.data.data.expire_count
                        });
                    }

                    // me.handleMergeData(me.data.deviceList, 1)
                    // if (me.data.start_page ==1 && deviceInfo != null) {
                    //   deviceInfo.isSelect = 1
                    //   me.setData({
                    //     deviceList: me.data.deviceList.unshift(deviceInfo)
                    //   })
                    // }
                    // console.log("deviceList",me.data.deviceList)
                } else {
                    common.simpleToast(resp.data.msg);
                }
            });
        },

        asyncRefhDeviceInfo(_deviceInfo) {
            return new Promise((reslove) => {
                const searchData = {
                    search: _deviceInfo.mac_id,
                    page: 1,
                    size: 5
                };
                http.postApi(config.API_BATTERY_SEARCH, searchData, function (resp) {
                    if (resp.data.code === 200) {
                        const deviceInfo = resp.data.data.list[0];
                        console.log(deviceInfo, 'deviceInfo2222');
                        storage.setSelectedDeviceInfo(deviceInfo);
                        reslove(deviceInfo);
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            });
        },

        bindSearchType: function (e) {
            const search_type = e.currentTarget.dataset.searchtype;
            this.setData({
                search_type: search_type
            });
            common.loading();
            this.refreshLoadDeviceList();
        },

        navigatorToPage: function (e) {
            const page = e.currentTarget.dataset.page;
            if (!page) {
                return;
            }
            uni.navigateTo({
                url: page
            });
        },

        bindLocal: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            if (
                common.isEmpty(deviceInfo.longitude + '') ||
                deviceInfo.longitude == '-' ||
                common.isEmpty(deviceInfo.latitude + '') ||
                deviceInfo.latitude == '-' ||
                deviceInfo.longitude == 0 ||
                deviceInfo.latitude == 0
            ) {
                common.simpleToast('该设备暂无位置信息');
                return;
            }
            storage.setSelectedDeviceInfo(deviceInfo);
            uni.navigateTo({
                url: '/pages/deviceLocal/deviceLocal'
            });
        },

        bindToBMS: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            if (deviceInfo.bms == 1) {
                uni.navigateTo({
                    url:
                        '/pages/bms/bms?macid=' +
                        deviceInfo.mac_id +
                        '&deviceType=' +
                        deviceInfo.device_type +
                        '&bt_type=' +
                        deviceInfo.bt_type +
                        '&bms=' +
                        deviceInfo.bms +
                        '&btid=' +
                        deviceInfo.btid +
                        '&btkey=' +
                        deviceInfo.btkey,
                    success: function (res) {},
                    fail: function (res) {},
                    complete: function (res) {}
                });
            } else {
                common.alert('该设备暂未配置BMS数据');
                return;
            }
        },

        bindToInfo: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            // storage.setSelectedDeviceInfo(deviceInfo)
            const _deviceInfo = encodeURIComponent(JSON.stringify(deviceInfo));
            uni.navigateTo({
                url: '/pages/deviceInfo/deviceInfo?deviceInfo=' + _deviceInfo
            });
        },

        loadGroupTree: function () {
            if (this.userInfo.type != 'group') {
                return;
            }
            const groupTreeList = storage.getGroupTreeList();
            const groupList = storage.getGroupList();
            if (!groupTreeList || !groupList || groupTreeList.constructor != Array) {
                const me = this;
                http.postApi(config.API_USER_GROUP_LIST, {}, function (resp) {
                    if (resp.data.code === 200) {
                        var groupList = common.groupTreeLeaf(common.groupListToTree(resp.data.data.list, me.userInfo.info.id));
                        var groupTreeList = [
                            groupList.find((x) => {
                                return parseInt(x.id) === parseInt(me.userInfo.info.id);
                            })
                        ];
                        groupTreeList[0].Level = 0;
                        groupTreeList[0].Leaf = false;
                        me.setData({
                            groupTreeList: groupTreeList,
                            groupList: groupList
                        });
                        storage.setGroupTreeList(groupTreeList);
                        storage.setGroupList(groupList);
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            } else {
                this.setData({
                    groupTreeList: groupTreeList,
                    groupList: groupList
                });
            }
        },

        bindInputSearch: function (e) {
            this.seach_value = e.detail.value;
        },

        bindHandleSearch: function () {
            this.search = this.seach_value;
            this.macid = '';
            this.refreshLoadDeviceList();
        },

        scanCode: function (e) {
            uni.scanCode({
                onlyFromCamera: true,
                scanType: [],
                success: (res) => {
                    //console.log(res)
                    if (res.result) {
                        this.setData({
                            search: res.result,
                            seach_value: res.result
                        });
                        this.refreshLoadDeviceList();
                    }
                },
                fail: function (res) {},
                complete: function (res) {}
            });
        },

        bindSelect: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            storage.setSelectedDeviceInfo(deviceInfo);
            uni.reLaunch({
                url: '/pages/home/home'
            });
        },

        bindAlarm: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            uni.navigateTo({
                url: '/pages/warnList/warnList?macid=' + deviceInfo.mac_id
            });
        },

        bindToSet: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            if (deviceInfo.expire == 1) {
                common.simpleToast('设备到期');
                return;
            }
            uni.navigateTo({
                url: '/pages/deviceCommand/deviceCommand?macid=' + deviceInfo.mac_id + '&type=' + deviceInfo.device_type + '&bt_type=' + deviceInfo.bt_type
            });
        },

        handleReturn: function () {
            uni.navigateBack({
                delta: 1
            });
        },

        bindCredit: function (e) {
            const index = e.currentTarget.dataset.index;
            const deviceInfo = this.deviceList[index];
            uni.navigateTo({
                url: '/pages/credit/credit?macid=' + deviceInfo.mac_id,
                success: function (res) {},
                fail: function (res) {},
                complete: function (res) {}
            });
        },

        handleAddDevice() {
            uni.navigateTo({
                url: '/pages/addDevice/addDevice'
            });
        },

        groupTreeLeaf(e) {
            const index = e.currentTarget.dataset.index;
            var groupTreeList = this.groupTreeList;
            if (groupTreeList[index].Leaf) {
                var i = 0;
                for (; index + i + 1 < groupTreeList.length; i++) {
                    if (groupTreeList[index + i + 1].Level <= groupTreeList[index].Level) {
                        break;
                    }
                }
                groupTreeList.splice(index + 1, i);
                groupTreeList[index].Leaf = false;
            } else if (groupTreeList[index].children_cnt != 0) {
                var i = 0;
                this.groupList.forEach((p) => {
                    if (parseInt(p.parent_id) === parseInt(groupTreeList[index].id)) {
                        groupTreeList.splice(index + i + 1, 0, p);
                        groupTreeList[index + i + 1].Level = groupTreeList[index].Level + 1;
                        groupTreeList[index + i + 1].Leaf = false;
                        i++;
                    }
                });
                groupTreeList[index].Leaf = true;
            }
            this.setData({
                groupTreeList: groupTreeList
            });
            storage.setGroupTreeList(groupTreeList);
        },

        bindGroupSearch(e) {
            uni.navigateTo({
                url: '/pages/searchDevice/searchDevice?search=' + this.seach_value
            });
        },

        handleMergeData: function (e, type) {
            //数据比对去重操作
            const that = this;
            if (type == 1) {
                that.deviceList = e;
            }
            if (type == 2) {
                that.deviceSearchList = e;
            }
            let deviceList = that.deviceList;
            let deviceSearchList = that.deviceSearchList;
            // console.log(deviceList)
            // console.log(deviceSearchList)
            let list = [];
            let againDeviceList = [];
            if (deviceList.length >= 1 && deviceSearchList.length >= 1) {
                for (let i = 0, len = deviceSearchList.length; i < len; i++) {
                    deviceSearchList[i].deviceHighlight = 1;
                    list.push(deviceSearchList[i]);
                    for (let j = 0; j < deviceList.length; j++) {
                        if (deviceSearchList[i].mac_id != deviceList[j].mac_id) {
                            deviceList[j].deviceHighlight = 2;
                            againDeviceList.push(deviceList[j]);
                        }
                    }
                    break;
                }
                this.setData({
                    deviceList: list.concat(againDeviceList)
                });
                this.loadReponseDealData(this.deviceList);
            } else {
                if (deviceList.length >= 1) {
                    for (let j = 0; j < deviceList.length; j++) {
                        deviceList[j].deviceHighlight = 2;
                        againDeviceList.push(deviceList[j]);
                    }
                    this.setData({
                        deviceList: againDeviceList
                    });
                    this.loadReponseDealData(this.deviceList);
                }
            }
        },

        loadReponseDealData(dev_list) {
            dev_list.forEach((p, i) => {
                var device = p;
                dev_list[i].btaccept = bluetooth.acceptDevice(device);
                dev_list[i].isConnect = false;
                const deviceInfo = storage.getSelectedDeviceInfo();
                if (deviceInfo != null && deviceInfo.mac_id === device.mac_id) {
                    dev_list[i].isConnect = bluetooth.isConnected(device.mac_id);
                    if (bluetooth.isConnected(device.mac_id)) {
                        this.setData({
                            btmacid: device.mac_id,
                            btInfo: {}
                        });
                        bluetooth.onCharacteristicStateChange(device.mac_id, 'home', (data) => {
                            this.processBluetoothReceiveData(device, dev_list, data, i);
                        });
                        bluetooth.onConnectionStateChange(device.mac_id, 'list', (res) => {
                            if (this.btmacid == device.mac_id && !res.connected) {
                                this.setData({
                                    btmacid: ''
                                });
                            }
                        });
                        bluetooth.stateUpdate(device.mac_id);
                    }
                }
            });
            dev_list.map((item, index) => {
                if (dev_list[index].isConnect === true) {
                    dev_list.unshift(dev_list.splice(index, 1)[0]);
                }
            });
            this.setData({
                deviceList: dev_list
            });
            // var dataList = this.data.list
            // for (var i = 0; dataList.length > i; i++) {
            //   dataList[i].isConnect = false
            // }
        },

        bindBTState(e) {
            let id = e.currentTarget.dataset.id;
            var batteryList = this.deviceList;
            if (batteryList[id].isConnect) {
                bluetooth.closeDevice(
                    batteryList[id].mac_id,
                    () => {
                        batteryList[id].isConnect = false;
                        this.setData({
                            deviceList: batteryList
                        });
                    },
                    () => {}
                );
            } else {
                if (!this.bt_loading) {
                    this.setData({
                        bt_loading: true
                    });
                    this.btConnect(id);
                }
            }
        },

        processBluetoothReceiveData(device, dev_list, data, i) {
            if ('baud' in data) {
                common.bluetoothSetBaud(device, data.baud, this.baud, bluetooth);
                return;
            }
            this.setData({
                bt_loading: false
            });
            if (this.btmacid == device.mac_id) {
                this.setData({
                    btInfo: data
                });
                var dataList = dev_list;
                for (var j = 0; dataList.length > j; j++) {
                    if (dataList[j].mac_id === this.btmacid) {
                        dataList[j].isConnect = true;
                        dataList[j].voltage = data.voltage;
                    }
                }
                if (dataList[i].bms === 0) {
                    this.loadQuantityReponse(device.mac_id, data.voltage, i);
                } else {
                    dataList[i].electric_quantity = data.quantity.toFixed(2);
                    this.setData({
                        deviceList: dataList
                    });
                }
                this.setData({
                    deviceList: dataList
                });
            }

            // this.setData({
            //   bt_loading: false
            // })
            // batteryList[id].isConnect = true
            // if (batteryList[id].btInfo) {
            //   batteryList[id].btInfo = Object.assign(batteryList[id].btInfo, data)
            // } else {
            //   batteryList[id].btInfo = data
            // }
            // this.setData({
            //   batteryList: batteryList
            // })
        },

        btConnect(id) {
            var batteryList = this.deviceList;
            var device = batteryList[id];
            bluetooth.openBluetoothAdapter(
                (res) => {
                    console.log(res);
                    bluetooth.connectDevice(
                        device,
                        () => {
                            batteryList[id].isConnect = true;
                            bluetooth.onCharacteristicStateChange(device.mac_id, 'list', (data) => {
                                this.processBluetoothReceiveData(device, batteryList, data, id);
                            });
                            bluetooth.onConnectionStateChange(device.mac_id, 'list', (res) => {
                                batteryList[id].isConnect = res.connected;
                                this.setData({
                                    deviceList: batteryList
                                });
                            });
                            common.bluetoothBaud(device, bluetooth, (res) => {
                                this.setData({
                                    baud: res
                                });
                            });
                            bluetooth.stateUpdate(
                                device.mac_id,
                                (res) => {
                                    this.setData({
                                        bt_loading: false
                                    });
                                },
                                (res) => {
                                    this.setData({
                                        bt_loading: false
                                    });
                                }
                            );
                            this.setData({
                                deviceList: batteryList
                            });
                        },
                        (res) => {
                            console.log(res);
                            uni.showModal({
                                content: '连接设备失败，请靠近设备重试',
                                confirmText: '重试',
                                success: (res) => {
                                    if (res.confirm) {
                                        this.btConnect(id);
                                    } else {
                                        this.setData({
                                            bt_loading: false
                                        });
                                    }
                                },
                                fail: (res) => {
                                    console.log(res);
                                    this.setData({
                                        bt_loading: false
                                    });
                                }
                            });
                        }
                    );
                },
                (res) => {
                    console.log(res);
                    uni.showModal({
                        content: '需使用手机蓝牙功能，请打开蓝牙',
                        confirmText: '重试',
                        success: (res) => {
                            if (res.confirm) {
                                this.btConnect(id);
                            } else {
                                this.setData({
                                    bt_loading: false
                                });
                            }
                        },
                        fail: (res) => {
                            console.log(res);
                            this.setData({
                                bt_loading: false
                            });
                        }
                    });
                }
            );
        }
    }
};
</script>
<style>
@import './device.css';
</style>
