<template>
    <view class="container">
        <map
            id="myMap"
            :longitude="longitude"
            :latitude="latitude"
            :scale="scale"
            :markers="marker"
            :polyline="polylines"
            :circles="circles"
            @markertap="bindMarkertap"
            show-location
            enable-3D
            show-compass
            enable-overlooking
            :enable-satellite="mapParams.enableSatellite"
            :enable-traffic="mapParams.enableTraffic"
            style="width: 100%; height: 100vh"
            @tap="bindTapMap"
        ></map>
        <map-control :mapParams="mapParams" @changeParams="mapChange"></map-control>
        <view v-if="showInfo" class="battery-group">
            <view class="battery-item">
                <view class="map-top">
                    <view class="map-cross">
                        <view class="map-top-box">
                            <view class="map-top-text">GPS</view>
                            <view :class="gps > 0 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gps > 1 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gps > 2 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gps > 3 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gps > 4 ? 'map-top-i' : 'map-top-n'" />
                        </view>
                        <view class="map-top-box gsm-view">
                            <view class="map-top-text">GSM</view>
                            <view :class="gsm > 0 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gsm > 1 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gsm > 2 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gsm > 3 ? 'map-top-i' : 'map-top-n'" />
                            <view :class="gsm > 4 ? 'map-top-i' : 'map-top-n'" />
                        </view>
                    </view>
                    <view class="map-top-box-1">
                        <view class="map-top-text-1">{{ deviceInfo.quantity }}%</view>
                        <image src="/static/resource/images/battery.png" class="bottom-img"></image>
                    </view>

                    <view v-if="deviceInfo.quantity >= 20" :style="'width: ' + batteryWidth + 'rpx;right:' + (71 + (37 - batteryWidth)) + 'rpx'" class="battery_num_view"></view>
                    <view v-if="deviceInfo.quantity < 20" :style="'width: ' + batteryWidth + 'rpx;right:' + (71 + (37 - batteryWidth)) + 'rpx'" class="battery_num_view_red"></view>
                </view>
                <view class="batter-info-group">
                    <view class="battery-desc flex-row flex-between">
                        <view>名称：{{ deviceInfo.name }}</view>
                        <view>状态：{{ status }}</view>
                    </view>
                    <view class="battery-desc flex-row flex-between">
                        <view>编号：{{ macid }}</view>
                        <view>设防状态：{{ deviceInfo.protectState ? (deviceInfo.protectState == 1 ? '设防' : '撤防') : '未知' }}</view>
                    </view>
                    <view class="battery-desc flex-row flex-between">
                        <view>控制：{{ deviceInfo.oilState == 1 ? '已通电' : '已断电' }}</view>
                        <view>定位类型：{{ deviceInfo.signalType == 0 ? 'GPS+北斗' : deviceInfo.signalType == 1 ? 'WIFI' : deviceInfo.signalType == 16 ? 'LBS' : '未知' }}</view>
                    </view>
                    <view class="battery-desc flex-row flex-between">
                        <view>当日里程：{{ deviceInfo.day_mil }}</view>
                        <view>总里程：{{ deviceInfo.mil }}</view>
                    </view>
                    <view class="battery-desc flex-row flex-between">
                        <view>
                            电压：{{
                                (deviceInfo.voltage ? deviceInfo.voltage + 'V' : '未知') +
                                (deviceInfo.elecState ? (deviceInfo.elecState == 1 ? '（主电接通）' : '（主电断开）') : '')
                            }}
                        </view>
                        <view v-if="deviceInfo && deviceInfo.temp && deviceInfo.temp != ''">温度: {{ deviceInfo.temp + '℃' }}</view>
                    </view>
                    <view class="battery-desc">通信：{{ deviceInfo.heart_time ? tools.formatTime(deviceInfo.heart_time) : '未知' }}</view>
                    <view class="battery-desc">定位：{{ deviceInfo.gps_time ? tools.formatTime(deviceInfo.gps_time) : '未知' }}</view>
                    <view v-if="address != ''" class="battery-desc">地址：{{ address }}</view>
                    <!-- <view wx:if="{{ address != '' }}" class="battery-desc">GPS最近地址：{{ address }}</view> -->
                </view>
            </view>
        </view>
        <view class="bottom-view">
            <view class="bottom-center">
                <image :src="trace ? '/static/resource/images/zhuizong.png' : '/static/resource/images/zhuizong1.png'" class="bottom-img"></image>
            </view>
            <view class="bottom-centent">
                <view class="bottom-item" @tap="bindTrackDialogOpen">
                    <image :src="trackPoints.length == 0 ? '/static/resource/images/guiji2.png' : '/static/resource/images/guiji1.png'" class="bottom-img"></image>
                    <view class="bottom-text">轨迹</view>
                </view>
                <view class="bottom-item" @tap="bindAlarmPopupOpen">
                    <image :src="alarmList.length == 0 ? '/static/resource/images/tongzhi.png' : '/static/resource/images/tongzhi1.png'" class="bottom-img"></image>
                    <view class="bottom-text">报警</view>
                </view>
                <!--<view class="bottom-item" bindtap="bindTrace">
        <image class="bottom-img"></image>
        <view class="bottom-text">追踪</view>
      </view>-->
                <view class="bottom-item" @tap="bindNavigate">
                    <image class="bottom-img"></image>
                    <view class="bottom-text">导航</view>
                </view>
                <view class="bottom-item" @tap="bindSendCommand" data-cmd="CLOSERELAY">
                    <image src="/static/resource/images/duandian1.png" class="bottom-img"></image>
                    <view class="bottom-text">断电</view>
                </view>
                <view class="bottom-item" @tap="bindSendCommand" data-cmd="OPENRELAY">
                    <image src="/static/resource/images/tongdian1.png" class="bottom-img"></image>
                    <view class="bottom-text">通电</view>
                </view>
            </view>
            <image v-if="trackPoints.length != 0" :src="inPlay ? '/static/resource/images/zhanting.png' : '/static/resource/images/bofang.png'" class="play-img" @tap="bindPlay"></image>
            <image v-if="trackPoints.length != 0" src="/static/resource/images/tingliu.png" class="stop-img" @tap="bindStopPopupOpen"></image>
            <view v-if="trackStopList.length != 0" class="stop-img" @tap="bindStopPopupOpen">
                <view class="tip-top">{{ trackStopList.length }}</view>
            </view>
            <image v-if="trackPoints.length != 0" src="/static/resource/images/guanbi1.png" class="close-img" @tap="bindCloseTrack"></image>
            <view @tap="loadLastGpsInfo" class="gps_last">
                <view class="text_view">最新</view>
                <view class="text_view">GPS</view>
            </view>
            <image src="/static/resource/images/weilan2.png" class="fence-img" @tap="bindFencePopupOpen"></image>
            <view v-if="trace" class="trace-box">追踪时间：{{ tools.formatHourSeconds(traceTime) }}</view>
            <!--<van-grid>
      <van-grid-item text="轨迹" bind:click="bindTrackDialogOpen">
        <van-icon slot="icon" name="map-marked" color="#409EFF" />
      </van-grid-item>
      <van-grid-item text="报警" bind:click="bindAlarmPopupOpen">
        <van-icon slot="icon" name="bell" color="#F56C6C" info="{{ alarmList.length }}"/>
      </van-grid-item>
      <van-grid-item wx:if="{{trackPoints.length!=0}}" text="播放" bind:click="bindPlay">
        <van-icon wx:if="{{!inPlay}}" slot="icon" name="play" color="#67C23A" />
        <van-icon wx:if="{{inPlay}}" slot="icon" name="pause" color="#67C23A" />
      </van-grid-item>
      <van-grid-item wx:if="{{trackPoints.length!=0}}" text="停留" bind:click="bindStopPopupOpen">
        <van-icon slot="icon" name="location" color="#E6A23C" info="{{ trackStopList.length }}"/>
      </van-grid-item>
    </van-grid>-->
        </view>
        <view class="left-group">
            <view class="left-group-i">
                <image class="btn-ctr" src="/static/resource/images/position.png" @tap="moveToLocation"></image>
            </view>
        </view>

        <view v-if="trackPoints.length != 0" class="track_bottom">
            <view class="track_total_time">
                时间:{{ tools.formatTimeNoSecond(trackDialogFrom.startTime / 1000) }} 至 {{ tools.formatTimeNoSecond(trackDialogFrom.endTime / 1000) }} 共{{ mileage_total }}公里
            </view>
            <view class="track_slide flex-row flex-between">
                <slider @change="trackPlayChangeAdress" @changing="trackPlayChange" :value="nowPlayIndex" min="1" :max="totalTrackValue" style="width: 70%" />
                <view @tap="bindFastForward" class="flex-row fastForward">
                    <image class="fastForward_img" src="/static/resource/images/fastForward.png"></image>
                    <text v-if="adjustSpeed == 0" class="fastForward_text">慢</text>
                    <text v-if="adjustSpeed == 1" class="fastForward_text">中</text>
                    <text v-if="adjustSpeed == 2" class="fastForward_text">快</text>
                </view>
            </view>
        </view>

        <van-dialog use-slot title="轨迹" :show="trackDialogShow" show-cancel-button confirm-button-text="查询" @close="bindTrackDialogClose" @confirm="bindTrackDialogConfirm">
            <van-cell-group>
                <view style="height: 20rpx"></view>
                <view style="margin-left: 36rpx" class="flex-row">
                    <view class="location_mark">定位类型：</view>
                    <view @tap="bindLocationType" data-index="1" :class="isLocationType == 1 ? 'sel_location_view' : 'un_location_view'">GPS</view>
                    <view @tap="bindLocationType" data-index="2" :class="isLocationType == 2 ? 'sel_location_view' : 'un_location_view'">LBS</view>
                    <view @tap="bindLocationType" data-index="3" :class="isLocationType == 3 ? 'sel_location_view' : 'un_location_view'">GPS+LBS</view>
                </view>
                <van-field :value="trackDialogFrom.formatStartTime" label="开始时间" left-icon="clock-o" disabled :border="false" @tap.native="bindTrackStartTimeSelect" />
                <van-field :value="trackDialogFrom.formatEndTime" label="结束时间" left-icon="clock-o" disabled :border="false" @tap.native="bindTrackEndTimeSelect" />
                <van-row gutter="2">
                    <van-col span="7" offset="1">
                        <van-button type="default" custom-style="border: 0;width:100%;" @click="bindTrackTimeSelectToday">当天</van-button>
                    </van-col>
                    <van-col span="8">
                        <van-button type="default" custom-style="border: 0;width:100%;" @click="bindTrackTimeSelectYesterday">昨天</van-button>
                    </van-col>
                    <van-col span="7">
                        <van-button type="default" custom-style="border: 0;width:100%;" @click="bindTrackTimeSelectLastday">前天</van-button>
                    </van-col>
                </van-row>
            </van-cell-group>
        </van-dialog>
        <van-popup
            :show="alarmPopupShow"
            :z-index="9999"
            round
            closeable
            :overlay="flase"
            custom-style="height: 45%"
            safe-area-inset-top
            position="bottom"
            @close="bindAlarmPopupClose"
        >
            <van-cell-group>
                <van-cell title="报警" />
                <van-cell :value="item.address" @click="MoveToAlarm($event, { p: item })" :data-p="item" v-for="(item, index) in alarmList" :key="index">
                    <view slot="title">
                        <view class="van-cell-text">
                            <van-tag type="danger">{{ item.alarm_desc }}</van-tag>
                            \t
                            <van-tag type="primary">{{ item.speed }}公里/小时</van-tag>
                        </view>
                        <view class="van-cell-text">
                            {{ item.formatTime }}
                        </view>
                    </view>
                </van-cell>
            </van-cell-group>
        </van-popup>
        <van-popup
            :show="trackStopPopupShow"
            :z-index="9999"
            round
            closeable
            :overlay="flase"
            custom-style="height: 45%"
            safe-area-inset-top
            position="bottom"
            @close="bindStopPopupClose"
        >
            <van-cell-group>
                <van-cell title="停留点" />
                <van-cell :value="item.address" @click="MoveToStop($event, { p: item })" :data-p="item" v-for="(item, index) in trackStopList" :key="index">
                    <view slot="title">
                        <view class="van-cell-text">
                            {{ item.name }}\t
                            <van-tag type="warning">{{ item.format_stop_time }}</van-tag>
                        </view>
                        <view class="van-cell-text">{{ item.time }} - {{ item.end_time }}</view>
                    </view>
                </van-cell>
            </van-cell-group>
        </van-popup>
        <van-popup :show="timeSelectShow" :z-index="9999" position="bottom" @close="bindTimeSelectClose">
            <van-datetime-picker type="datetime" :value="selectTime" @confirm="bindTimeSelectConfirm" @cancel="bindTimeSelectClose" />
        </van-popup>
        <van-popup
            :show="fencePopupShow"
            :z-index="9999"
            round
            closeable
            :overlay="flase"
            custom-style="height: 45%"
            safe-area-inset-top
            position="bottom"
            @close="bindFencePopupClose"
        >
            <van-cell-group>
                <van-cell>
                    <view slot="title">
                        <view class="van-cell-text">
                            围栏
                            <van-button icon="plus" type="info" size="small" @tap.native="addFence" style="margin-left: 30rpx">添加</van-button>
                        </view>
                    </view>
                </van-cell>
                <van-cell :value="item.radius + '米'" @click="MoveToFence($event, { p: item })" :data-p="item" v-for="(item, index) in fenceList" :key="index">
                    <view slot="title">
                        <view class="van-cell-text">
                            {{ item.name }}
                        </view>
                        <view class="van-cell-text">报警类型: {{ item.type == 1 ? '进' : item.type == 2 ? '出' : item.type == 3 ? '双向' : '关闭' }}</view>
                    </view>
                </van-cell>
            </van-cell-group>
        </van-popup>
        <van-popup
            :show="selectFence != null"
            :z-index="9999"
            round
            closeable
            :overlay="flase"
            custom-style="height: 45%"
            safe-area-inset-top
            position="bottom"
            @close="bindFenceClose"
        >
            <van-cell-group>
                <van-cell>
                    <view slot="title">
                        <view class="van-cell-text">
                            围栏设置
                            <van-button v-if="selectFence.id" icon="cross" type="danger" size="small" @tap.native="delFence" style="margin-left: 30rpx">删除</van-button>
                        </view>
                    </view>
                </van-cell>
                <van-cell title="围栏名称" title-width="90px">
                    <input placeholder="请输入围栏名称" @blur="onFenceNameChange" :value="selectFence.name" style="color: rgba(0, 0, 0, 1)" />
                </van-cell>
                <!-- van-field value="{{ selectFence.name }}" label="围栏名称" placeholder="请输入围栏名称" border="{{ false }}" bind:change="onFenceNameChange"/ -->
                <van-cell title="报警类型" title-width="90px">
                    <van-radio-group :value="selectFence.type" class="flex-row flex-around" @change="onFenceTypeChange">
                        <van-radio name="1">进</van-radio>
                        <van-radio name="2">出</van-radio>
                        <van-radio name="3">双向</van-radio>
                        <van-radio name="0">关闭</van-radio>
                    </van-radio-group>
                </van-cell>
                <van-cell title="围栏半径" title-width="90px">
                    <view class="flex-row flex-around" style="width: 100%; height: 100%">
                        <image src="/static/resource/images/-.png" style="width: 40rpx; height: 40rpx" @tap="onFenceRadiusMinus"></image>
                        <slider :value="selectFence.radius" @change="onFenceRadiusChange" @changing="onFenceRadiusChange" min="1" max="10000" show-value style="width: 75%" />
                        <!--van-slider value="{{ selectFence.radius }}" min="1" max="10000" use-button-slot bind:change="onFenceRadiusChange" style="width: 75%;">
            <view class="custom-button" slot="button">
              {{ selectFence.radius }}米
            </view>
          </van-slider-->
                        <image src="/static/resource/images/+.png" style="width: 40rpx; height: 40rpx" @tap="onFenceRadiusPlus"></image>
                    </view>
                </van-cell>
            </van-cell-group>
            <view style="padding: 0 16px; margin-top: 50rpx">
                <button class="save-btn" @tap="bindFenceSave">保存</button>
            </view>
        </van-popup>
    </view>
</template>
<script module="tools" lang="wxs" src="@/pages/common/wxs/tools.wxs"></script>
<script>
import mapControl from '@/component/mapControl/mapControl';
// pages/deviceLocal/deviceLocal.js
const config = require('../../common/config.js');
const common = require('../../common/common.js');
var http = require('../../common/http.js');
var storage = require('../../common/storage.js');
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
export default {
    components: {
        mapControl
    },
    data() {
        return {
            deviceInfo: {
                quantity: '',
                name: '',
                protectState: false,
                oilState: 0,
                signalType: 0,
                day_mil: '',
                mil: '',
                voltage: false,
                elecState: false,
                temp: '',
                heart_time: false,
                gps_time: false
            },

            marker: [],
            mileage_total: 0,
            deviceMarker: [],
            trackMarker: [],
            alarmMarker: [],
            playMarker: [],
            endSlide: 0,
            polylines: [],
            trackPoints: [],
            trackStopList: [],
            batteryWidth: 37,
            alarmList: [],
            adjustSpeed: 1,
            scale: 8,
            speedTime: 200,

            trackDialogFrom: {
                startTime: new Date(new Date().getTime() - 3600000).getTime(),
                formatStartTime: common.formatDateTime(new Date(new Date().getTime() - 3600000).getTime()),
                endTime: new Date().getTime(),
                formatEndTime: common.formatDateTime(new Date().getTime())
            },

            latitude_my: null,
            longitude_my: null,
            trackDialogShow: false,
            selectTime: new Date().getTime(),
            selectTimeType: '',
            alarmPopupShow: false,
            trackStopPopupShow: false,
            timeSelectShow: false,
            inPlay: false,
            playTimer: null,
            nowPlayIndex: 0,
            totalTrackValue: 0,
            currentTrackValue: 0,
            macid: '',
            gps: 0,
            gsm: 0,
            status: '',
            address: '',
            showInfo: true,
            iconList: [],
            locationTimer: null,
            longitude: null,
            latitude: null,
            trace: false,
            tracePoints: [],
            traceTime: 0,
            traceTimer: null,
            fencePopupShow: false,
            fenceList: [],
            isLocationType: 1,
            circles: [],
            selectFence: null,

            mapParams: {
                enableSatellite: false,
                // 是否开启卫星图
                enableTraffic: false // 是否开启实时路况
            },

            isShowGPS: false,

            // locationInfo:{}
            locationType: '',

            locationAdress: '',
            locationGpsType: '',
            locationGpsAdress: '',
            gpsMarker: [],
            flase: ''
        };
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.loadIconList();
        this.readyDeviceInfo();
        this.loadAlarmList();
        this.loadFenceList();
        this.locationLoop(true);
        //this.loadLastGpsInfo()
        this.locationTimer = setInterval(this.locationLoop, 10000);

        //获取当前位置
        uni.getLocation({
            type: 'gcj02',
            success: (res) => {
                //console.log(res)
                this.setData({
                    latitude_my: res.latitude,
                    longitude_my: res.longitude
                });
            }
        });
        this.mapCtx = uni.createMapContext('myMap');
    },
    onHide: function () {},
    onShow: function () {},
    onUnload: function () {
        clearInterval(this.locationTimer);
        clearInterval(this.traceTimer);
        clearInterval(this.playTimer);
    },
    methods: {
        loadIconList: function () {
            this.iconList = storage.getIconList();
            if (!this.iconList) {
                http.postApi(config.API_BATTERY_ICON_LIST, {}, (resp) => {
                    if (resp.data.code === 200) {
                        this.iconList = resp.data.data.list;
                        storage.setIconList(resp.data.data.list);
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                });
            }
        },

        trackPlayChange(e) {
            var index = e.detail.value;
            this.setData({
                nowPlayIndex: index
            });
            this.playLoop();
        },

        bindLocationType(e) {
            const index = e.currentTarget.dataset.index;
            console.log(index);
            this.setData({
                isLocationType: index
            });
        },

        trackPlayChangeAdress(e) {
            console.log('22222');
            var index = e.detail.value;
            this.setData({
                nowPlayIndex: index
            });
            const me = this;
            this.playLoop();
            console.log(me.playMarker.length);
            if (me.playMarker.length > 0) {
                console.log('22222333333');
                // qqmapsdk.reverseGeocoder({
                //   location: {
                //     latitude: me.data.playMarker[0].latitude,
                //     longitude: me.data.playMarker[0].longitude
                //   },
                //   success: function (res) {
                //     const formatted_addresses = res.result.formatted_addresses
                //     const address = res.result.address
                //     let ps = '';
                //     let tmp_addr = '地址: ' + address
                //     while (tmp_addr.length > 15) {
                //       ps += tmp_addr.substring(0, 15) + "\n";
                //       tmp_addr = tmp_addr.substring(15);
                //     }
                //     ps += tmp_addr
                //     var playMark = me.data.playMarker
                //     playMark[0].callout.content += ps
                //     me.setData({
                //       playMarker: playMark
                //     })
                //     console.log("1111111")
                //     me.setMarkers()
                //   }
                // })

                const me = this;
                const pData = {
                    lng: me.playMarker[0].longitude,
                    lat: me.playMarker[0].latitude,
                    pi: 'wx_deviceLocal'
                };
                http.postApi(config.API_MAP_REGEO, pData, function (resp) {
                    if (resp.data.code === 200) {
                        var jsonData = resp.data.data.data;
                        if (jsonData.code === 0) {
                            const address = jsonData.address;
                            let ps = '';
                            let tmp_addr = '地址: ' + address;
                            while (tmp_addr.length > 15) {
                                ps += tmp_addr.substring(0, 15) + '\n';
                                tmp_addr = tmp_addr.substring(15);
                            }
                            ps += tmp_addr;
                            var playMark = me.playMarker;
                            playMark[0].callout.content += ps;
                            me.setData({
                                playMarker: playMark
                            });
                        }
                    }
                });
            }
        },

        bindFastForward() {
            if (this.adjustSpeed === 0) {
                this.setData({
                    adjustSpeed: 1,
                    speedTime: 400
                });
                clearInterval(this.playTimer);
                this.playTimer = setInterval(this.playLoop, this.speedTime);
            } else if (this.adjustSpeed === 1) {
                this.setData({
                    adjustSpeed: 2,
                    speedTime: 200
                });
                clearInterval(this.playTimer);
                this.playTimer = setInterval(this.playLoop, this.speedTime);
            } else if (this.adjustSpeed === 2) {
                this.setData({
                    adjustSpeed: 0,
                    speedTime: 600
                });
                clearInterval(this.playTimer);
                this.playTimer = setInterval(this.playLoop, this.speedTime);
            }
        },

        loadAlarmList() {
            common.loading();
            const deviceInfo = storage.getSelectedDeviceInfo();
            http.postApi(
                config.API_GPS_ALARM,
                {
                    macid: deviceInfo.mac_id
                },
                (resp) => {
                    uni.hideLoading();
                    if (resp.data.code === 200) {
                        var alarmList = resp.data.data.list;
                        alarmList.forEach((p, i) => {
                            alarmList[i].formatTime = common.formatDateTime(p.send_time * 1000);
                            qqmapsdk.reverseGeocoder({
                                location: {
                                    latitude: p.latitude,
                                    longitude: p.longitude
                                },
                                success: (res) => {
                                    const formatted_addresses = res.result.formatted_addresses;
                                    const address = res.result.address; //+ formatted_addresses.recommend
                                    let ps = '';
                                    let tmp_addr = '地址: ' + address;
                                    while (tmp_addr.length > 15) {
                                        ps += tmp_addr.substring(0, 15) + '\n';
                                        tmp_addr = tmp_addr.substring(15);
                                    }
                                    ps += tmp_addr;
                                    alarmList[i].address = address;
                                    alarmList[i].ps = ps;
                                    this.setData({
                                        alarmList: alarmList
                                    });
                                }
                            });
                        });
                        this.setData({
                            alarmList: alarmList
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        readyDeviceInfo() {
            const me = this;
            // 实例化API核心类
            qqmapsdk = new QQMapWX({
                key: config.QQ_MAP_KEY
            });
            const deviceInfo = storage.getSelectedDeviceInfo();
            if (deviceInfo) {
                console.log('1111');
                console.log(deviceInfo);
                // this.batteryWidth = deviceInfo.quantity/100*37
                // console.log(deviceInfo.quantity)
                uni.setNavigationBarTitle({
                    title: deviceInfo.mac_id
                });
                if (parseInt(deviceInfo.expire) === 1) {
                    common.simpleToast('设备到期');
                    setTimeout(function () {
                        uni.navigateBack({
                            delta: 1
                        });
                    }, 1500);
                }
            } else {
                clearInterval(this.locationTimer);
                setTimeout(function () {
                    uni.navigateBack({
                        delta: 1
                    });
                }, 1500);
            }
        },

        setMarkers() {
            this.setData({
                marker: this.deviceMarker.concat(this.trackMarker, this.alarmMarker, this.playMarker, this.gpsMarker)
            });
        },

        setPolylines() {
            var polylines = [
                {
                    points: this.trackPoints,
                    color: '#1989FADD',
                    width: 5,
                    arrowLine: true
                }
            ]; /*, {
            points: this.data.trackPoints.slice(0,this.data.nowPlayIndex+1),
            color: '#F56C6CDD',
            width: 3,
          }]*/
            if (this.trace) {
                polylines.push({
                    points: this.tracePoints,
                    color: '#DD4C4CDD',
                    width: 3,
                    arrowLine: true
                });
            }
            this.setData({
                polylines: polylines
            });
        },

        bindTrackDialogOpen() {
            this.setData({
                trackDialogShow: true
            });
        },

        // 计算里程数
        calculateMileage(history) {
            let mileage = 0;
            for (let i = 0; i < history.length - 1; i++) {
                mileage += parseInt(common.getFlatternDistance(history[i].longitude, history[i].latitude, history[i + 1].longitude, history[i + 1].latitude));
            }
            var mileage_total = mileage == 0 ? 0 : (mileage / 1000).toFixed(2);
            console.log('公里');
            console.log(mileage_total);
            this.setData({
                mileage_total: mileage_total
            });
        },

        getCurrentMil(mileage, i, history) {
            //var mileage = mileage_current
            mileage += parseInt(common.getFlatternDistance(history[i].longitude, history[i].latitude, history[i + 1].longitude, history[i + 1].latitude));
            console.log(mileage);
            return mileage;
        },

        loadTotalMil() {
            const deviceInfo = storage.getSelectedDeviceInfo();
            http.postApi(
                config.API_SHOW_MIL,
                {
                    macid: deviceInfo.mac_id,
                    location_type: this.isLocationType,
                    from: parseInt(this.trackDialogFrom.startTime / 1000),
                    to: parseInt(this.trackDialogFrom.endTime / 1000)
                },
                (resp) => {
                    if (resp.data.code === 200) {
                        this.setData({
                            mileage_total: resp.data.data.distance
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        bindTrackDialogConfirm() {
            this.bindTrackDialogClose();
            this.setData({
                inPlay: false
            });
            clearInterval(this.playTimer);
            common.loading();
            const deviceInfo = storage.getSelectedDeviceInfo();
            http.postApi(
                config.API_GPS_TRACK,
                {
                    macid: deviceInfo.mac_id,
                    location_type: this.isLocationType,
                    from: parseInt(this.trackDialogFrom.startTime / 1000),
                    to: parseInt(this.trackDialogFrom.endTime / 1000)
                },
                (resp) => {
                    this.loadTotalMil();
                    uni.hideLoading();
                    if (resp.data.code === 200) {
                        if (!resp.data.data.points || resp.data.data.points.length === 0) {
                            common.simpleToast('当前未有轨迹');
                            return;
                        }
                        // this.calculateMileage(resp.data.data.points)
                        var points = [];
                        var trackMarker = [];
                        var trackStopList = [];
                        var n = 1;
                        this.setData({
                            totalTrackValue: resp.data.data.points.length
                        });
                        var mileage = 0;
                        resp.data.data.points.forEach((p, i) => {
                            //移动坐标点
                            if (resp.data.data.points.length - 1 > i) {
                                mileage = this.getCurrentMil(mileage, i, resp.data.data.points);
                            }
                            points.push({
                                latitude: parseFloat(p.latitude),
                                longitude: parseFloat(p.longitude),
                                time: p.time,
                                speed: p.speed,
                                voltage: p.voltage,
                                time: p.time,
                                mileage: (mileage / 1000).toFixed(2),
                                stop_time: p.stop_time
                            });
                            //起点
                            if (i === 0) {
                                trackStopList.push({
                                    name: '起点',
                                    latitude: parseFloat(p.latitude),
                                    longitude: parseFloat(p.longitude),
                                    time: p.time,
                                    end_time: common.formatDateTime(new Date(p.time).getTime() + p.stop_time * 1000),
                                    stop_time: p.stop_time,
                                    format_stop_time: common.formatSeconds(p.stop_time),
                                    address: ''
                                });
                                //mark弹出框坐标
                                trackMarker.push({
                                    id: 0,
                                    latitude: p.latitude,
                                    longitude: p.longitude,
                                    name: '',
                                    iconPath: '/static/resource/images/start_point.png',
                                    width: 28,
                                    height: 35,
                                    zIndex: 2,
                                    callout: {
                                        content:
                                            '\u8D77\u70B9\n\u505C\u7559: ' +
                                            common.formatSeconds(p.stop_time) +
                                            '\n' +
                                            '开始: ' +
                                            p.time +
                                            '\n' +
                                            '结束: ' +
                                            common.formatDateTime(new Date(p.time).getTime() + p.stop_time * 1000) +
                                            '\n',
                                        padding: 10,
                                        borderRadius: 4,
                                        boxShadow: '4px 8px 16px 0 rgba(0,0,0,0.3)',
                                        display: 'BYCLICK'
                                    }
                                });
                                const me = this;
                                const pData = {
                                    lng: parseFloat(p.longitude),
                                    lat: parseFloat(p.latitude),
                                    pi: 'wx_deviceLocal'
                                };
                                http.postApi(config.API_MAP_REGEO, pData, function (resp) {
                                    if (resp.data.code === 200) {
                                        var jsonData = resp.data.data.data;
                                        if (jsonData.code === 0) {
                                            const address = jsonData.address;
                                            let ps = '';
                                            let tmp_addr = '地址: ' + address;
                                            while (tmp_addr.length > 15) {
                                                ps += tmp_addr.substring(0, 15) + '\n';
                                                tmp_addr = tmp_addr.substring(15);
                                            }
                                            ps += tmp_addr;
                                            trackMarker[0].callout.content += ps;
                                            trackStopList[0].address = address;
                                            me.setData({
                                                trackMarker: trackMarker,
                                                trackStopList: trackStopList
                                            });
                                            me.setMarkers();
                                        }
                                    }
                                });

                                // qqmapsdk.reverseGeocoder({
                                //   location: {
                                //     latitude: parseFloat(p.latitude),
                                //     longitude: parseFloat(p.longitude)
                                //   },
                                //   success: (res) => {
                                //     console.log(res)
                                //     const formatted_addresses = res.result.formatted_addresses
                                //     const address = res.result.address + formatted_addresses.recommend
                                //     let ps = '';
                                //     let tmp_addr = '地址: ' + address
                                //     while (tmp_addr.length > 15) {
                                //       ps += tmp_addr.substring(0, 15) + "\n";
                                //       tmp_addr = tmp_addr.substring(15);
                                //     }
                                //     ps += tmp_addr
                                //     trackMarker[0].callout.content += ps
                                //     trackStopList[0].address = address
                                //     this.setData({
                                //       trackMarker: trackMarker,
                                //       trackStopList: trackStopList,
                                //     })
                                //     this.setMarkers()
                                //   }
                                // })
                            } else if (p.stop_time > 300 && i !== resp.data.data.points.length - 1) {
                                //地图设置mark停留点
                                trackStopList.push({
                                    name: 'P' + n,
                                    latitude: parseFloat(p.latitude),
                                    longitude: parseFloat(p.longitude),
                                    time: p.time,
                                    end_time: common.formatDateTime(new Date(p.time).getTime() + p.stop_time * 1000),
                                    stop_time: p.stop_time,
                                    format_stop_time: common.formatSeconds(p.stop_time),
                                    address: ''
                                });
                                //mark弹出框
                                trackMarker.push({
                                    id: i,
                                    latitude: parseFloat(p.latitude),
                                    longitude: parseFloat(p.longitude),
                                    name: '',
                                    iconPath: '/static/resource/images/p-stop.png',
                                    width: 28,
                                    height: 35,
                                    zIndex: 1,
                                    callout: {
                                        content:
                                            'P' +
                                            n +
                                            '\n' +
                                            '停留: ' +
                                            common.formatSeconds(p.stop_time) +
                                            '\n' +
                                            '开始: ' +
                                            p.time +
                                            '\n' +
                                            '结束: ' +
                                            common.formatDateTime(new Date(p.time).getTime() + p.stop_time * 1000) +
                                            '\n',
                                        padding: 10,
                                        borderRadius: 4,
                                        boxShadow: '4px 8px 16px 0 rgba(0,0,0,0.3)',
                                        display: 'BYCLICK'
                                    }
                                });
                                var i = n;
                                qqmapsdk.reverseGeocoder({
                                    location: {
                                        latitude: parseFloat(p.latitude),
                                        longitude: parseFloat(p.longitude)
                                    },
                                    success: (res) => {
                                        console.log(res);
                                        const formatted_addresses = res.result.formatted_addresses;
                                        const address = res.result.address + formatted_addresses.recommend;
                                        let ps = '';
                                        let tmp_addr = '地址: ' + address;
                                        while (tmp_addr.length > 15) {
                                            ps += tmp_addr.substring(0, 15) + '\n';
                                            tmp_addr = tmp_addr.substring(15);
                                        }
                                        ps += tmp_addr;
                                        trackMarker[i].callout.content += ps;
                                        trackStopList[i].address = address;
                                        this.setData({
                                            trackMarker: trackMarker,
                                            trackStopList: trackStopList
                                        });
                                        this.setMarkers();
                                    }
                                });
                                n++;
                            }
                        });
                        //设置终点
                        trackStopList.push({
                            name: '终点',
                            latitude: parseFloat(points[points.length - 1].latitude),
                            longitude: parseFloat(points[points.length - 1].longitude),
                            time: points[points.length - 1].time,
                            end_time: common.formatDateTime(new Date(points[points.length - 1].time).getTime() + points[points.length - 1].stop_time * 1000),
                            stop_time: points[points.length - 1].stop_time,
                            format_stop_time: common.formatSeconds(points[points.length - 1].stop_time),
                            address: ''
                        });
                        trackMarker.push({
                            id: points.length - 1,
                            latitude: points[points.length - 1].latitude,
                            longitude: points[points.length - 1].longitude,
                            name: '',
                            iconPath: '/static/resource/images/end_point.png',
                            width: 28,
                            height: 35,
                            zIndex: 2,
                            callout: {
                                content:
                                    '\u7EC8\u70B9\n\u505C\u7559: ' +
                                    common.formatSeconds(points[points.length - 1].stop_time) +
                                    '\n' +
                                    '开始: ' +
                                    points[points.length - 1].time +
                                    '\n' +
                                    '结束: ' +
                                    common.formatDateTime(new Date(points[points.length - 1].time).getTime() + points[points.length - 1].stop_time * 1000) +
                                    '\n',
                                padding: 10,
                                borderRadius: 4,
                                boxShadow: '4px 8px 16px 0 rgba(0,0,0,0.3)',
                                display: 'BYCLICK'
                            }
                        });
                        qqmapsdk.reverseGeocoder({
                            location: {
                                latitude: parseFloat(points[points.length - 1].latitude),
                                longitude: parseFloat(points[points.length - 1].longitude)
                            },
                            success: (res) => {
                                console.log(res);
                                const formatted_addresses = res.result.formatted_addresses;
                                const address = res.result.address + formatted_addresses.recommend;
                                let ps = '';
                                let tmp_addr = '地址: ' + address;
                                while (tmp_addr.length > 15) {
                                    ps += tmp_addr.substring(0, 15) + '\n';
                                    tmp_addr = tmp_addr.substring(15);
                                }
                                ps += tmp_addr;
                                trackMarker[n].callout.content += ps;
                                trackStopList[n].address = address;
                                this.setData({
                                    trackMarker: trackMarker,
                                    trackStopList: trackStopList
                                });
                                this.setMarkers();
                            }
                        });
                        var deviceMarker = this.deviceMarker;
                        //deviceMarker[0].callout.display = 'BYCLICK'
                        this.setData({
                            trackPoints: points,
                            trackMarker: trackMarker,
                            deviceMarker: deviceMarker,
                            trackStopList: trackStopList,
                            nowPlayIndex: 0,
                            playMarker: []
                        });
                        this.setMarkers();
                        this.setPolylines();
                        // this.mapCtx.scale = 8
                        var map = uni.createMapContext('myMap');
                        map.includePoints({
                            points: points,
                            padding: [10, 10, 10, 10]
                        });
                        this.setData({
                            scale: 13
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        bindTrackDialogClose() {
            this.setData({
                trackDialogShow: false
            });
        },

        bindTrackStartTimeSelect() {
            this.setData({
                selectTime: this.trackDialogFrom.startTime,
                selectTimeType: 'track_start'
            });
            this.bindTimeSelectOpen();
        },

        bindTrackEndTimeSelect() {
            this.setData({
                selectTime: this.trackDialogFrom.endTime,
                selectTimeType: 'track_end'
            });
            this.bindTimeSelectOpen();
        },

        bindTrackTimeSelectToday() {
            this.setData({
                trackDialogFrom: Object.assign(this.trackDialogFrom, {
                    startTime: new Date(new Date().toLocaleDateString()).getTime(),
                    formatStartTime: common.formatDateTime(new Date(new Date().toLocaleDateString()).getTime()),
                    endTime: new Date().getTime(),
                    formatEndTime: common.formatDateTime(new Date().getTime())
                })
            });
            this.bindTrackDialogConfirm();
        },

        bindTrackTimeSelectYesterday() {
            this.setData({
                trackDialogFrom: Object.assign(this.trackDialogFrom, {
                    startTime: new Date(new Date().toLocaleDateString()).getTime() - 86400 * 1000,
                    formatStartTime: common.formatDateTime(new Date(new Date().toLocaleDateString()).getTime() - 86400 * 1000),
                    endTime: new Date(new Date().toLocaleDateString()).getTime() - 1,
                    formatEndTime: common.formatDateTime(new Date(new Date().toLocaleDateString()).getTime() - 1)
                })
            });
            this.bindTrackDialogConfirm();
        },

        bindTrackTimeSelectLastday() {
            this.setData({
                trackDialogFrom: Object.assign(this.trackDialogFrom, {
                    startTime: new Date(new Date().toLocaleDateString()).getTime() - 2880 * 60 * 1000,
                    formatStartTime: common.formatDateTime(new Date(new Date().toLocaleDateString()).getTime() - 2880 * 60 * 1000),
                    endTime: new Date(new Date().toLocaleDateString()).getTime() - 86400 * 1000 - 1,
                    formatEndTime: common.formatDateTime(new Date(new Date().toLocaleDateString()).getTime() - 86400 * 1000 - 1)
                })
            });
            this.bindTrackDialogConfirm();
        },

        bindTimeSelectConfirm(event) {
            switch (this.selectTimeType) {
                case 'track_start':
                    this.setData({
                        trackDialogFrom: Object.assign(this.trackDialogFrom, {
                            startTime: event.detail,
                            formatStartTime: common.formatDateTime(event.detail)
                        }),
                        selectTimeType: ''
                    });
                    break;
                case 'track_end':
                    this.setData({
                        trackDialogFrom: Object.assign(this.trackDialogFrom, {
                            endTime: event.detail,
                            formatEndTime: common.formatDateTime(event.detail)
                        }),
                        selectTimeType: ''
                    });
                    break;
            }
            this.bindTimeSelectClose();
        },

        bindTimeSelectOpen() {
            this.setData({
                timeSelectShow: true
            });
        },

        bindTimeSelectClose() {
            this.setData({
                timeSelectShow: false
            });
        },

        bindStopPopupOpen() {
            this.setData({
                trackStopPopupShow: true
            });
        },

        bindStopPopupClose() {
            this.setData({
                trackStopPopupShow: false
            });
        },

        MoveToStop(event, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(event, _dataset);
            /* ---处理dataset end--- */
            var map = uni.createMapContext('myMap');
            this.setData({
                latitude: event.currentTarget.dataset.p.latitude,
                longitude: event.currentTarget.dataset.p.longitude
            });
            /*map.moveToLocation({
        latitude: event.currentTarget.dataset.p.latitude,
        longitude: event.currentTarget.dataset.p.longitude
      })*/
        },

        bindAlarmPopupOpen() {
            this.setData({
                alarmPopupShow: true
            });
        },

        bindAlarmPopupClose() {
            this.setData({
                alarmPopupShow: false
            });
            this.setData({
                alarmMarker: []
            });
            this.setMarkers();
        },

        MoveToAlarm(event, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(event, _dataset);
            /* ---处理dataset end--- */
            var map = uni.createMapContext('myMap');
            var alarmMarker = [
                {
                    id: 0,
                    latitude: event.currentTarget.dataset.p.latitude,
                    longitude: event.currentTarget.dataset.p.longitude,
                    name: '',
                    iconPath: '/static/resource/images/alarm.png',
                    width: 28,
                    height: 35,
                    zIndex: 10,
                    callout: {
                        content:
                            event.currentTarget.dataset.p.alarm_desc +
                            '\n' +
                            '时间: ' +
                            event.currentTarget.dataset.p.formatTime +
                            '\n' +
                            '速度: ' +
                            event.currentTarget.dataset.p.speed +
                            '公里/小时\n' +
                            event.currentTarget.dataset.p.ps +
                            '\n',
                        padding: 10,
                        borderRadius: 4,
                        boxShadow: '4px 8px 16px 0 rgba(0,0,0,0.3)',
                        display: 'ALWAYS'
                    }
                }
            ];
            this.setData({
                alarmMarker: alarmMarker,
                latitude: event.currentTarget.dataset.p.latitude,
                longitude: event.currentTarget.dataset.p.longitude
            });
            this.setMarkers();
        },

        playLoop() {
            if (this.nowPlayIndex >= this.trackPoints.length - 1) {
                this.setData({
                    inPlay: false
                });
                clearInterval(this.playTimer);
                return;
            }
            this.setData({
                showInfo: false
            });
            var map = uni.createMapContext('myMap');
            var leng = Math.sqrt(
                Math.pow(Math.abs(this.trackPoints[this.nowPlayIndex + 1].longitude - this.trackPoints[this.nowPlayIndex].longitude) * 111, 2) +
                    Math.pow(
                        Math.abs(this.trackPoints[this.nowPlayIndex + 1].latitude - this.trackPoints[this.nowPlayIndex].latitude) *
                            111 *
                            Math.cos(((2 * Math.PI) / 360) * this.trackPoints[this.nowPlayIndex].latitude),
                        2
                    )
            );
            while (leng < 0.1 && this.nowPlayIndex < this.trackPoints.length - 1) {
                leng += Math.sqrt(
                    Math.pow(Math.abs(this.trackPoints[this.nowPlayIndex + 1].longitude - this.trackPoints[this.nowPlayIndex].longitude) * 111, 2) +
                        Math.pow(
                            Math.abs(this.trackPoints[this.nowPlayIndex + 1].latitude - this.trackPoints[this.nowPlayIndex].latitude) *
                                111 *
                                Math.cos(((2 * Math.PI) / 360) * this.trackPoints[this.nowPlayIndex].latitude),
                            2
                        )
                );
                this.nowPlayIndex = this.nowPlayIndex + 1;
            }
            var rotate =
                (Math.atan(
                    (this.trackPoints[this.nowPlayIndex + 1].longitude - this.trackPoints[this.nowPlayIndex].longitude) /
                        (this.trackPoints[this.nowPlayIndex + 1].latitude - this.trackPoints[this.nowPlayIndex].latitude) /
                        Math.cos(((2 * Math.PI) / 360) * this.trackPoints[this.nowPlayIndex].latitude)
                ) *
                    180) /
                Math.PI;
            if (rotate === NaN) {
                if (this.trackPoints[this.nowPlayIndex + 1].longitude - this.trackPoints[this.nowPlayIndex].longitude > 0) {
                    rotate = 90;
                } else {
                    rotate = 270;
                }
            } else if (this.trackPoints[this.nowPlayIndex + 1].latitude - this.trackPoints[this.nowPlayIndex].latitude < 0) {
                rotate = 180 + rotate;
            } else if (this.trackPoints[this.nowPlayIndex + 1].longitude - this.trackPoints[this.nowPlayIndex].longitude < 0) {
                rotate = 360 + rotate;
            }
            var playMarker = [
                {
                    id: -1,
                    latitude: this.trackPoints[this.nowPlayIndex].latitude,
                    longitude: this.trackPoints[this.nowPlayIndex].longitude,
                    name: '',
                    iconPath: '/static/resource/images/1.gif',
                    width: 35,
                    height: 35,
                    zIndex: 20,
                    callout: {
                        content:
                            '电压: ' +
                            this.trackPoints[this.nowPlayIndex].voltage +
                            '\n' +
                            '速度: ' +
                            this.trackPoints[this.nowPlayIndex].speed +
                            'km/小时\n' +
                            '时间: ' +
                            this.trackPoints[this.nowPlayIndex].time +
                            '\n' +
                            '里程: ' +
                            this.trackPoints[this.nowPlayIndex].mileage +
                            '公里\n',
                        padding: 10,
                        borderRadius: 4,
                        boxShadow: '4px 8px 16px 0 rgba(0,0,0,0.3)',
                        display: 'ALWAYS'
                    }
                }
            ];
            this.playMarker = playMarker;
            this.setMarkers();
            this.setData({
                latitude: this.trackPoints[this.nowPlayIndex].latitude,
                longitude: this.trackPoints[this.nowPlayIndex].longitude,
                nowPlayIndex: this.nowPlayIndex + 1
            });
        },

        bindPlay() {
            if (this.inPlay) {
                this.setData({
                    inPlay: false
                });
                const me = this;
                clearInterval(this.playTimer);
                if (me.playMarker.length > 0) {
                    const pData = {
                        lng: me.playMarker[0].longitude,
                        lat: me.playMarker[0].latitude,
                        pi: 'wx_deviceLocal'
                    };
                    const me = this;
                    http.postApi(config.API_MAP_REGEO, pData, function (resp) {
                        if (resp.data.code === 200) {
                            var jsonData = resp.data.data.data;
                            if (jsonData.code === 0) {
                                const address = jsonData.address;
                                var ps = '';
                                let tmp_addr = '地址: ' + address;
                                while (tmp_addr.length > 15) {
                                    ps += tmp_addr.substring(0, 15) + '\n';
                                    tmp_addr = tmp_addr.substring(15);
                                }
                                ps += tmp_addr;
                                var playMark = me.playMarker;
                                playMark[0].callout.content += ps;
                                me.setData({
                                    playMarker: playMark
                                });
                                me.setMarkers();
                            }
                        }
                    });

                    // qqmapsdk.reverseGeocoder({
                    //   location: {
                    //     latitude: me.data.playMarker[0].latitude,
                    //     longitude: me.data.playMarker[0].longitude
                    //   },
                    //   success: function (res) {
                    //     const formatted_addresses = res.result.formatted_addresses
                    //     const address = res.result.address
                    //     let ps = '';
                    //     let tmp_addr = '地址: ' + address
                    //     while (tmp_addr.length > 15) {
                    //       ps += tmp_addr.substring(0, 15) + "\n";
                    //       tmp_addr = tmp_addr.substring(15);
                    //     }
                    //     ps += tmp_addr
                    //     var playMark = me.data.playMarker
                    //     playMark[0].callout.content += ps
                    //     me.setData({
                    //       playMarker: playMark
                    //     })
                    //     me.setMarkers()
                    //   }
                    // })
                }
            } else {
                if (this.nowPlayIndex >= this.trackPoints.length - 1) {
                    this.setData({
                        nowPlayIndex: 0
                    });
                }
                this.setData({
                    inPlay: true
                });
                this.playTimer = setInterval(this.playLoop, this.speedTime);
            }
        },

        // bindGPSLocation(){
        //   this.setData({
        //     isShowGPS:true
        //   })
        //   this.locationLoop(true)
        // },

        locationLoop(init = false) {
            const me = this;
            const deviceInfo = storage.getSelectedDeviceInfo();
            if (deviceInfo) {
                //common.loading()
                http.postApi(
                    config.API_GPS_INFO,
                    {
                        macid: deviceInfo.mac_id
                    },
                    (resp) => {
                        //wx.hideLoading()
                        if (resp.data.code === 200) {
                            let status;
                            let stat = '';
                            if (parseInt(resp.data.data.info.online) === 1) {
                                if (parseInt(resp.data.data.info.speed) === 0) {
                                    status = '静止(' + common.formatSeconds(resp.data.data.info.heart_time - resp.data.data.info.gps_time, false) + ')';
                                    stat = 'static';
                                } else {
                                    status = '行驶(' + resp.data.data.info.speed + 'Km/h)';
                                    stat = 'running';
                                }
                            } else {
                                status =
                                    '离线(' +
                                    common.formatSeconds(
                                        new Date().getTime() / 1000 -
                                            (resp.data.data.info.heart_time === undefined ? resp.data.data.info.gps_time : resp.data.data.info.heart_time),
                                        false
                                    ) +
                                    ')';
                                stat = 'offline';
                            }
                            if (init) {
                                this.setData({
                                    longitude: resp.data.data.info.longitude,
                                    latitude: resp.data.data.info.latitude
                                });
                            }
                            var device_info = resp.data.data.info;
                            this.setData({
                                locationType: device_info.signalType
                            });
                            this.setData({
                                macid: deviceInfo.mac_id,
                                deviceInfo: resp.data.data.info,
                                gps: resp.data.data.info.gpscount,
                                gsm: parseInt(resp.data.data.info.online) === 0 ? 0 : resp.data.data.info.gsmlevel <= 15 ? 3 : resp.data.data.info.gsmlevel > 18 ? 5 : 4,
                                status: status,
                                deviceMarker: [
                                    {
                                        id: 1,
                                        latitude: resp.data.data.info.latitude,
                                        longitude: resp.data.data.info.longitude,
                                        name: '',
                                        iconPath: this.iconList[resp.data.data.info.icon] ? this.iconList[resp.data.data.info.icon][stat] : '/static/resource/images/weizhi2.png',
                                        width: 35,
                                        height: 35,
                                        zIndex: 10
                                    }
                                ],
                                circles: [
                                    {
                                        latitude: resp.data.data.info.latitude,
                                        longitude: resp.data.data.info.longitude,
                                        color: '#6495ED1F',
                                        fillColor: '#6495ED1F',
                                        radius: 1000,
                                        strokeWidth: 1
                                    }
                                ]
                            });
                            this.setMarkers();
                            if (
                                this.trace &&
                                (this.tracePoints.length == 0 ||
                                    this.tracePoints[this.tracePoints.length - 1].latitude != resp.data.data.info.latitude ||
                                    this.tracePoints[this.tracePoints.length - 1].longitude != resp.data.data.info.longitude)
                            ) {
                                this.tracePoints.push({
                                    latitude: resp.data.data.info.latitude,
                                    longitude: resp.data.data.info.longitude
                                });
                                this.setPolylines();
                                this.setData({
                                    latitude: resp.data.data.info.latitude,
                                    longitude: resp.data.data.info.longitude
                                });
                            }
                            console.log(resp.data.data.info);
                            console.log(this.batteryWidth);
                            const pData = {
                                lng: resp.data.data.info.longitude,
                                lat: resp.data.data.info.latitude,
                                pi: 'wx_deviceLocal'
                            };
                            const me = this;
                            http.postApi(config.API_MAP_REGEO, pData, function (resp) {
                                if (resp.data.code === 200) {
                                    var jsonData = resp.data.data.data;
                                    if (jsonData.code === 0) {
                                        me.setData({
                                            address: jsonData.address,
                                            locationAdress: jsonData.address
                                        });
                                    }
                                }
                            });

                            // qqmapsdk.reverseGeocoder({
                            //   location: {
                            //     latitude: resp.data.data.info.latitude,
                            //     longitude: resp.data.data.info.longitude
                            //   },
                            //   success: function (res) {
                            //     console.log(res)
                            //     const formatted_addresses = res.result.formatted_addresses
                            //     const address = res.result.address //+ formatted_addresses.recommend
                            //     me.setData({
                            //       address: address,
                            //       locationAdress: address
                            //     })
                            //   }
                            // })
                        } else {
                            common.simpleToast(resp.data.msg);
                            clearInterval(this.locationTimer);
                            setTimeout(function () {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }, 1500);
                        }
                    }
                );
            }
        },

        isEmptyObject(obj) {
            for (var key in obj) {
                return false;
            }
            return true;
        },

        loadLastGpsInfo() {
            var init = true;
            const me = this;
            const deviceInfo = storage.getSelectedDeviceInfo();
            if (deviceInfo) {
                http.postApi(
                    config.API_GPS_INFO,
                    {
                        macid: deviceInfo.mac_id
                    },
                    (resp) => {
                        if (resp.data.code === 200) {
                            console.log('11111');
                            if (this.isEmptyObject(resp.data.data.info.last_location)) {
                                common.simpleToast('当前设备没有GPS坐标');
                                return;
                            }
                            // var last_location = resp.data.data.info.last_location
                            // last_location.lng = 121.19023414159073
                            // last_location.lat = 31.390001627411883
                            // resp.data.data.info.last_location = last_location
                            let status;
                            let stat = '';
                            if (parseInt(resp.data.data.info.online) === 1) {
                                if (parseInt(resp.data.data.info.speed) === 0) {
                                    status = '静止(' + common.formatSeconds(resp.data.data.info.heart_time - resp.data.data.info.gps_time, false) + ')';
                                    stat = 'static';
                                } else {
                                    status = '行驶(' + resp.data.data.info.speed + 'Km/h)';
                                    stat = 'running';
                                }
                            } else {
                                status =
                                    '离线(' +
                                    common.formatSeconds(
                                        new Date().getTime() / 1000 -
                                            (resp.data.data.info.heart_time === undefined ? resp.data.data.info.gps_time : resp.data.data.info.heart_time),
                                        false
                                    ) +
                                    ')';
                                stat = 'offline';
                            }
                            if (init) {
                                this.setData({
                                    longitude: resp.data.data.info.last_location.lng,
                                    latitude: resp.data.data.info.last_location.lat
                                });
                            }
                            var device_info = resp.data.data.info;
                            device_info.signalType = '0';
                            this.setData({
                                locationGpsType: device_info.signalType
                            });
                            var device_marker = {
                                id: 2,
                                latitude: resp.data.data.info.last_location.lat,
                                longitude: resp.data.data.info.last_location.lng,
                                name: '',
                                iconPath: this.iconList[resp.data.data.info.icon] ? this.iconList[resp.data.data.info.icon][stat] : '/static/resource/images/weizhi2.png',
                                width: 35,
                                height: 35,
                                zIndex: 10
                            };
                            // this.setData({
                            //   marker: this.data.marker.concat(device_marker)
                            // })
                            this.setData({
                                gpsMarker: [device_marker]
                            });
                            this.setData({
                                marker: this.gpsMarker.concat(this.trackMarker, this.alarmMarker, this.playMarker, this.deviceMarker)
                            });
                            // this.setData({
                            //   marker: this.data.deviceMarker.concat(this.data.trackMarker, this.data.alarmMarker, this.data.playMarker)
                            // })

                            console.log('marker');
                            console.log(this.marker);
                            //this.data.deviceMarker.concat(this.data.trackMarker, this.data.alarmMarker, this.data.playMarker)

                            this.setData({
                                macid: deviceInfo.mac_id,
                                deviceInfo: device_info,
                                gps: resp.data.data.info.gpscount,
                                gsm: parseInt(resp.data.data.info.online) === 0 ? 0 : resp.data.data.info.gsmlevel <= 15 ? 3 : resp.data.data.info.gsmlevel > 18 ? 5 : 4,
                                status: status,
                                deviceMarker: [device_marker],
                                circles: [
                                    {
                                        latitude: resp.data.data.info.last_location.lat,
                                        longitude: resp.data.data.info.last_location.lng,
                                        color: '#6495ED1F',
                                        fillColor: '#6495ED1F',
                                        radius: 1000,
                                        strokeWidth: 1
                                    }
                                ]
                            });
                            //this.setMarkers()

                            // this.setData({
                            //   marker: this.data.deviceMarker.concat(this.data.deviceMarker)
                            // })
                            console.log(resp.data.data.info);
                            this.setData({
                                batteryWidth: parseInt((this.deviceInfo.quantity / 100) * 37)
                            });
                            console.log(this.batteryWidth);
                            const me = this;
                            const pData = {
                                lng: resp.data.data.info.last_location.lng,
                                lat: resp.data.data.info.last_location.lat,
                                pi: 'wx_deviceLocal'
                            };
                            http.postApi(config.API_MAP_REGEO, pData, function (resp) {
                                if (resp.data.code === 200) {
                                    var jsonData = resp.data.data.data;
                                    if (jsonData.code === 0) {
                                        const address = jsonData.address;
                                        me.setData({
                                            address: address,
                                            locationGpsAdress: address
                                        });
                                    }
                                }
                            });

                            // qqmapsdk.reverseGeocoder({
                            //   location: {
                            //     latitude: resp.data.data.info.last_location.latitude,
                            //     longitude: resp.data.data.info.last_location.longitude
                            //   },
                            //   success: function (res) {
                            //     console.log(res)
                            //     const formatted_addresses = res.result.formatted_addresses
                            //     const address = res.result.address //+ formatted_addresses.recommend
                            //     me.setData({
                            //       address: address,
                            //       locationGpsAdress: address
                            //     })
                            //   }
                            // })
                        } else {
                            common.simpleToast(resp.data.msg);
                            clearInterval(this.locationTimer);
                            setTimeout(function () {
                                uni.navigateBack({
                                    delta: 1
                                });
                            }, 1500);
                        }
                    }
                );
            }
        },

        bindMarkertap(e) {
            if (e.markerId == 1 || e.markerId == 2) {
                if (e.markerId == 1) {
                    var deviceInfo = this.deviceInfo;
                    deviceInfo.signalType = this.locationType;
                    this.setData({
                        deviceInfo: deviceInfo,
                        address: this.locationAdress
                    });
                }
                if (e.markerId == 2) {
                    var deviceInfo = this.deviceInfo;
                    deviceInfo.signalType = this.locationGpsType;
                    this.setData({
                        deviceInfo: deviceInfo,
                        address: this.locationGpsAdress
                    });
                }
                this.setData({
                    showInfo: !this.showInfo
                });
            }
        },

        bindTapMap(e) {
            this.setData({
                showInfo: false
            });
            if (this.selectFence != null) {
                var fence = this.selectFence;
                fence.latitude = e.detail.latitude;
                fence.longitude = e.detail.longitude;
                this.setData({
                    selectFence: fence,
                    circles: [
                        {
                            latitude: fence.latitude,
                            longitude: fence.longitude,
                            radius: parseInt(fence.radius),
                            color: '#6495ED1F',
                            fillColor: '#6495ED1F',
                            strokeWidth: 1
                        }
                    ]
                });
            }
        },

        bindSendCommand: function (e) {
            this.sendCommand(e.currentTarget.dataset.cmd);
        },

        sendCommand: function (cmd) {
            uni.showModal({
                content: '确定发送指令吗？',
                showCancel: true,
                cancelText: '取消',
                confirmText: '确定',
                success: (res) => {
                    console.log(res);
                    if (res.confirm) {
                        common.loading();
                        http.postApi(
                            config.API_BATTERY_SEND_COMMAND,
                            {
                                macid: this.macid,
                                cmd: cmd
                            },
                            function (resp) {
                                if (resp.data.code === 200) {
                                    uni.hideLoading();
                                    common.simpleToast('操作成功');
                                } else {
                                    common.simpleToast(resp.data.msg);
                                }
                            }
                        );
                    }
                },
                fail: function (res) {},
                complete: function (res) {}
            });
        },

        bindTrace() {
            if (this.trace) {
                this.setData({
                    trace: false,
                    tracePoints: []
                });
                this.setPolylines();
                clearInterval(this.traceTimer);
            } else {
                this.setData({
                    trace: true
                });
                this.traceTimer = setInterval(() => {
                    this.setData({
                        traceTime: this.traceTime + 1
                    });
                }, 1000);
            }
        },

        bindNavigate() {
            //使用微信内置地图查看标记点位置，并进行导航
            /*
      console.log(this.data.longitude);
      console.log(this.data.latitude);
      console.log(this.data.longitude_my);
      console.log(this.data.latitude_my);
      */
            const latitude = this.latitude;
            const longitude = this.longitude;
            uni.openLocation({
                latitude,
                //要去的纬度-地址
                longitude,
                //要去的经度-地址
                scale: 11
            });
        },

        bindCloseTrack() {
            this.setData({
                trackPoints: [],
                trackMarker: [],
                trackStopList: [],
                nowPlayIndex: 0,
                playMarker: []
            });
            this.setMarkers();
            this.setPolylines();
        },

        bindFencePopupOpen() {
            this.setData({
                fencePopupShow: true
            });
        },

        bindFencePopupClose() {
            this.setData({
                fencePopupShow: false
            });
        },

        MoveToFence(event, _dataset) {
            /* ---处理dataset begin--- */
            this.handleDataset(event, _dataset);
            /* ---处理dataset end--- */
            var map = uni.createMapContext('myMap');
            const fence = Object.assign({}, event.currentTarget.dataset.p);
            this.setData({
                selectFence: fence,
                circles: [
                    {
                        latitude: fence.latitude,
                        longitude: fence.longitude,
                        radius: parseInt(fence.radius),
                        color: '#6495ED1F',
                        fillColor: '#6495ED1F',
                        strokeWidth: 1
                    }
                ],
                fencePopupShow: false,
                latitude: fence.latitude,
                longitude: fence.longitude
            });
            /*map.moveToLocation({
        latitude: event.currentTarget.dataset.p.latitude,
        longitude: event.currentTarget.dataset.p.longitude
      })*/
        },

        addFence() {
            var map = uni.createMapContext('myMap');
            map.getCenterLocation({
                success: (res) => {
                    const fence = {
                        name: '',
                        type: '0',
                        latitude: res.latitude,
                        longitude: res.longitude,
                        radius: 100
                    };
                    this.setData({
                        selectFence: fence,
                        circles: [
                            {
                                latitude: fence.latitude,
                                longitude: fence.longitude,
                                radius: parseInt(fence.radius),
                                color: '#6495ED1F',
                                fillColor: '#6495ED1F',
                                strokeWidth: 1
                            }
                        ],
                        fencePopupShow: false
                    });
                }
            });
        },

        loadFenceList() {
            common.loading();
            const deviceInfo = storage.getSelectedDeviceInfo();
            http.postApi(
                config.API_FENCE_LIST,
                {
                    macid: deviceInfo.mac_id
                },
                (resp) => {
                    uni.hideLoading();
                    if (resp.data.code === 200) {
                        var fenceList = resp.data.data.list;
                        this.setData({
                            fenceList: fenceList
                        });
                    } else {
                        common.simpleToast(resp.data.msg);
                    }
                }
            );
        },

        bindFenceClose() {
            this.setData({
                selectFence: null,
                circles: [],
                fencePopupShow: true
            });
        },

        onFenceNameChange(e) {
            var fence = this.selectFence;
            fence.name = e.detail.value;
            this.setData({
                selectFence: fence
            });
        },

        onFenceTypeChange(e) {
            var fence = this.selectFence;
            fence.type = e.detail;
            this.setData({
                selectFence: fence
            });
        },

        onFenceRadiusDrag(e) {
            var fence = this.selectFence;
            fence.radius = e.detail.value;
            this.setData({
                selectFence: fence
                /*circles: [{
          latitude: fence.latitude,
          longitude: fence.longitude,
          radius: parseInt(fence.radius),
          color: '#6495EDBB',
          fillColor: '#6495ED1F',
          strokeWidth: 1
        }],*/
            });
        },

        onFenceRadiusChange(e) {
            var fence = this.selectFence;
            fence.radius = e.detail.value;
            // this.setData({circles:[]})
            var startSlide = new Date().getTime();
            if (startSlide - this.endSlide > 100) {
                this.setData({
                    endSlide: startSlide
                });
                this.setData({
                    selectFence: fence,
                    circles: [
                        {
                            latitude: fence.latitude,
                            longitude: fence.longitude,
                            radius: parseInt(fence.radius),
                            color: '#6495ED1F',
                            fillColor: '#6495ED1F',
                            strokeWidth: 1
                        }
                    ]
                });
            }
        },

        onFenceRadiusMinus() {
            var fence = this.selectFence;
            if (fence.radius > 1) {
                fence.radius = parseInt(fence.radius) - 100;
                this.setData({
                    selectFence: fence,
                    circles: [
                        {
                            latitude: fence.latitude,
                            longitude: fence.longitude,
                            radius: parseInt(fence.radius),
                            color: '#6495ED1F',
                            fillColor: '#6495ED1F',
                            strokeWidth: 1
                        }
                    ]
                });
            }
        },

        onFenceRadiusPlus() {
            var fence = this.selectFence;
            if (fence.radius < 10000) {
                fence.radius = parseInt(fence.radius) + 100;
                this.setData({
                    selectFence: fence,
                    circles: [
                        {
                            latitude: fence.latitude,
                            longitude: fence.longitude,
                            radius: parseInt(fence.radius),
                            color: '#6495ED1F',
                            fillColor: '#6495ED1F',
                            strokeWidth: 1
                        }
                    ]
                });
            }
        },

        bindFenceSave() {
            var fence = this.selectFence;
            if (!fence.name) {
                common.simpleToast('请输入围栏名称');
                return;
            }
            if (fence != null) {
                common.loading();
                const deviceInfo = storage.getSelectedDeviceInfo();
                if (fence.id) {
                    http.postApi(
                        config.API_FENCE_EDIT,
                        Object.assign(
                            {
                                macid: deviceInfo.mac_id
                            },
                            fence
                        ),
                        (resp) => {
                            uni.hideLoading();
                            if (resp.data.code === 200) {
                                this.loadFenceList();
                            } else {
                                common.simpleToast(resp.data.msg);
                            }
                            this.setData({
                                selectFence: null,
                                circles: [],
                                fencePopupShow: true
                            });
                        }
                    );
                } else {
                    http.postApi(
                        config.API_FENCE_ADD,
                        Object.assign(
                            {
                                macid: deviceInfo.mac_id
                            },
                            fence
                        ),
                        (resp) => {
                            uni.hideLoading();
                            if (resp.data.code === 200) {
                                this.loadFenceList();
                            } else {
                                common.simpleToast(resp.data.msg);
                            }
                            this.setData({
                                selectFence: null,
                                circles: [],
                                fencePopupShow: true
                            });
                        }
                    );
                }
            }
        },

        delFence() {
            var fence = this.selectFence;
            if (fence != null && fence.id) {
                common.loading();
                const deviceInfo = storage.getSelectedDeviceInfo();
                http.postApi(
                    config.API_FENCE_DEL,
                    {
                        macid: deviceInfo.mac_id,
                        id: fence.id
                    },
                    (resp) => {
                        uni.hideLoading();
                        if (resp.data.code === 200) {
                            this.loadFenceList();
                        } else {
                            common.simpleToast(resp.data.msg);
                        }
                        this.setData({
                            selectFence: null,
                            circles: [],
                            fencePopupShow: true
                        });
                    }
                );
            }
        },

        moveToLocation: function () {
            //console.log('move to')
            this.mapCtx.moveToLocation();
            //this.setData({ showShopInfo: false, scale: 14 })
        },

        mapChange: function (e) {
            this.setData({
                mapParams: e.detail.mapParams
            });
        }
    }
};
</script>
<style>
@import './deviceLocal.css';
</style>
