<template>
    <div class="map-wrp">
        <div class="map-sum-head">
            <span class="title">车辆分布图</span>
            <div class="tipinfo">
                <div class="img-wrp">
                    <div class="img-item">
                        <img :src="using">
                        <p>使用中<br /><span>{{ usingNum }}</span></p>
                    </div>
                    <div class="img-item">
                        <img :src="unuse">
                        <p>未使用<br /><span>{{ unuseNum }}</span></p>
                    </div>
                    <div class="img-item">
                        <img :src="low">
                        <p>低电量<br /><span>{{ lowNum }}</span></p>
                    </div>
                </div>
            </div>
            <div class="filter-container">
                <span>电量状态：</span>
                <el-select v-model="listQuery.powerStatus" size="small" placeholder="请选择" class="filter-item">
                    <el-option v-for="item in powerOptions" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
                <span>使用状态：</span>
                <el-select v-model="listQuery.ifBikeUseing" size="small" placeholder="请选择" class="filter-item">
                    <el-option v-for="item in useOptions" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
                <!--<span>车辆状态：</span>-->
                <!--<el-select v-model="listQuery.troubleStatus" size="small" placeholder="请选择" class="filter-item">-->
                    <!--<el-option v-for="item in carOptions" :key="item.value" :label="item.label" :value="item.value"/>-->
                <!--</el-select>-->
                <span>未使用时长：</span>
                    <el-select v-model="listQuery.startDay" size="small" placeholder="请选择" class="filter-item">
                    <el-option v-for="item in dayOptions" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
                <span>区域：</span>
                <el-select v-model="listQuery.manageAreaId" size="small" placeholder="请选择" class="filter-item" style="width: 120px">
                    <el-option v-for="item in $root.regionOptions" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
                <el-input placeholder="车牌号/定位设备号" v-model="listQuery.keyword" size="small" class="input-item" />
                <el-button class="filter-item" size="small" type="primary" icon="el-icon-search" @click="getBike" style="width: 80px">搜索</el-button>
            </div>
        </div>
        <div class="aMap">
            <div id="allmap" ref="allmap"></div>

            <side-list ref="SideList"
                 :bikeList="bikeList" @showInfo="showBikeInfo"
                 :parkList="parkList" @isShowPart="isShowPart" @showPartInfo="showPartInfo" @isOpenPart="isOpenPart" @removePark="removePark">
            </side-list>

            <div class="draw-menu" v-show="showDrawTool">
                <el-button-group>
                    <el-button type="primary" icon="el-icon-delete" @click="clearDraw">清除围栏</el-button>
                    <el-button type="primary" icon="el-icon-close" @click="closeDraw">关闭工具</el-button>
                </el-button-group>
                <p style="color: red;text-align: right;">注意：双击结束绘画！</p>
            </div>
        </div>
    </div>
</template>

<script>
import SideList from "./components/sideList"
import api from  "@/api/bike"

export default {
    components: {SideList},
    name: "bike-map",
    data() {
        return {
            listQuery: {
                powerStatus: '',
                ifBikeUseing: '',
                troubleStatus: '',
                startDay: '',
                manageAreaId: '',
                keyword: undefined
            },
            parkQuery: {
                parkType: 'Permit',
                keyword: undefined,
            },
            powerOptions: [
                { label: '全部', value: '' },
                { label: '正常', value: '1' },
                { label: '低电量', value: '0' }
            ],
            useOptions: [
                { label: '全部', value: '' },
                { label: '使用中', value: '1' },
                { label: '未使用', value: '0' }
            ],
            carOptions: [
                { label: '全部', value: '' },
                { label: '正常', value: '0' },
                { label: '故障', value: '1' }
            ],
            dayOptions: [
                { label: '全部', value: '' },
                { label: '1天以上', value: '1' },
                { label: '3天以上', value: '3' },
                { label: '5天以上', value: '5' },
                { label: '7天以上', value: '7' }
            ],
            aMap: undefined,
            parkList: [],
            bikeList: [],
            pointArr: [],
            polygonArr: [],
            using: require('../../assets/status/using.png'),
            unuse: require('../../assets/status/unuse.png'),
            low: require('../../assets/status/low.png'),
            usingNum: 0,
            unuseNum: 0,
            lowNum: 0,
            drawTool: undefined,
            showDrawTool: false,
            overlays: []
        }
    },
    methods: {
        // 地图初始化
        initMap() {
            this.$refs.allmap.style.height = (document.documentElement.clientHeight || document.body.clientHeight) - 134 + 'px';
            this.aMap = new AMap.Map('allmap', {
                zoom: 15, // 地图缩放级别
                resizeEnable: true, // 获取当前位置坐标
            });
            // 异步加载插件
            this.aMap.plugin(["AMap.ToolBar"], () => {
                let toolBar = new AMap.ToolBar()
                this.aMap.addControl(toolBar)
            });

            this.getBike()
            this.getPark()
        },
        // 车辆相关
        getBike() { // 获取车辆信息
            this.removeBike()
            api.getBikeDistribution(this.listQuery).then(res => {
                console.log('Bike:', res)
                this.bikeList = res.results.resultList
                this.usingNum = res.results.countBikeUseing
                this.unuseNum = res.results.countBikeWait
                this.lowNum = res.results.countLowBatteryPowerBike
                if(this.bikeList) this.addBike()
            }).catch(err => {
                console.log(err)
            })
        },
        addBike() { // 添加车辆标记到地图上
            this.bikeList.forEach((item, i) => {
                let marker = new AMap.Marker({
                    icon: item.ifRiding ? this.using : Number(item.batteryPower)<30 ? this.low : this.unuse,
                    position: new AMap.LngLat(item.gcjLon, item.gcjLat),
                    title: 'bike-' + i
                })
                marker.on('click', (ev) => this.addBikeInfo(item))
                this.aMap.add(marker)
                this.pointArr.push(marker)
            })
        },
        removeBike() { // 移除车辆标记
            this.pointArr.forEach((item) => this.aMap.remove(item))
            this.pointArr = []
        },
        addBikeInfo(data) { // 添加车辆信息窗口
        console.log(data)
        api.orderRentMember({bikeMainId:data.id}).then(res => {
                console.log('Bike:', res)
                let info =
                `<div class="list-infoWindow">
                    <div class="title">车辆信息</div>
                    <p class="list-item">车牌号：<span>${data.plateNumber}</span></p>
                    <p class="list-item">设备号：<span>${data.boxCode}</span></p>
                    <p class="list-item">状态：<span>${data.troubleStatus ? '故障' : '正常'}</span></p>
                    <p class="list-item">电量：<span>${data.batteryPower}%</span></p>
                    <p class="list-item">地址：<span>${data.address}</span></p>
                    <p class="list-item">定位方式：<span>${data.lastLocationType}</span></p>
                    <p class="list-item">最新GPS定位时间：<span>${data.gpsTimeLast}</span></p>
                    <p class="list-item">最新定位时间：<span>${data.lastLocationTime}</span></p>
                    <p class="list-item">时长：<span>${data.ifRiding ? '使用中' : data.noUseTime + '未使用'}</span></p>
                    <p class="list-item">备注：<span>${data.remark}</span></p>
                    <p class="list-item">最近订单：<span></span></p>
                    <p class="list-item">用户昵称：<span>${res.results.truename}</span></p>
                    <p class="list-item">手机号：<span>${res.results.mobile}</span></p>
                    <p class="list-item">订单开始时间：<span>${res.results.orderStartTime}</span></p>
                    <p class="list-item">订单结束时间：<span>${res.results.OrderEndTime}</span></p>
                    <div class="live">
                        <img src='./static/${data.ifLink ? 'online':'offline'}.png' class="live-icon">
                        ${data.ifLink ? '在线' : '离线'}
                    </div>
                </div>`;
                let infoWindow = new AMap.InfoWindow({
                content: info,
                offset: new AMap.Pixel(3, -32)
            });
            infoWindow.open(this.aMap, new AMap.LngLat(data.gcjLon, data.gcjLat));
            })
        },
        showBikeInfo(data) { // 显示车辆信息窗口
            if(data.gcjLon && data.gcjLat) {
                this.aMap.setZoomAndCenter(19, [data.gcjLon, data.gcjLat]);
                this.addBikeInfo(data)
            } else {
                this.$message('该车辆无最新位置')
            }
        },
        // 还车点、骑行区、禁行区 相关
        getPark(show) { // 获取还车点/骑行区/禁行区
            api.getParkFenceList(this.parkQuery).then(res => {
                console.log('Park:', res)
                this.removePark()
                this.parkList = res.results.restultList
                this.parkList.forEach((item, i) => { this.parkList[i].ifDisenable = item.ifDisenable=='0' ? true : false })
                if(show) this.showPark()
            }).catch(err => {
                console.log(err)
            })
        },
        addPark(park) { // 添加还车点/骑行区/禁行区 多边形覆盖物
            let _park = park,
                parkArr = _park.content.split(';');
            parkArr.forEach((item, i) => {
                parkArr[i] = new AMap.LngLat(item.split(',')[0], item.split(',')[1])
            })
            // console.log(parkArr)
            let strokeColor = _park.parkType=='Permit' ? "#1E90FF" : _park.parkType=='Forbid' ? "red" : "#006AFF",
                fillColor = _park.parkType=='Permit' ? '#09f' : _park.parkType=='Forbid' ? "#F33" : "",
                fillOpacity = 0.3,
                strokeStyle = _park.parkType=='Forbid' ? "dashed" : "solid",
                strokeWeight = _park.parkType=='RidingCanton' ? 5 : 2,
                polygon = new AMap.Polygon({
                    path: parkArr,
                    fillColor, fillOpacity, strokeStyle, strokeColor, strokeWeight, strokeOpacity: 0.8
                });
            this.aMap.add(polygon);
            if(!_park.ifDisenable)  polygon.hide()

            let center = _park.center.split(','),
                circle = new AMap.Circle({
                    center: new AMap.LngLat(center[0], center[1]), radius: _park.radius,
                    fillColor, fillOpacity, strokeColor, strokeWeight: 1, strokeOpacity: 0.3
                }),
                info =
                    `<div class='list-infoWindow'>
                        <div class='title'>信息</div>
                        <p class='list-item'>还车点名称：<span>${park.name}</span></p>
                        <p class='list-item'>创建时间：<span>${park.createTime}</span></p>
                    </div>`;
            let infoWindow = new AMap.InfoWindow({ content: info });

            this.polygonArr.push({ id:_park.id, polygon, circle, infoWindow })
            if(_park.parkType!='RidingCanton') {
                this.aMap.add(circle);
                if(!_park.ifDisenable) circle.hide()
                circle.on('click', (ev) => { this.showPartInfo(park) })
            }
        },
        showPark() {
            this.parkList.forEach((park) => { this.addPark(park) })
        },
        removePark(i) {
            if(i!=undefined) {
                console.log(i, this.polygonArr[i])
                if(this.polygonArr[i]) {
                    if(this.polygonArr[i].polygon) {
                        this.polygonArr[i].polygon.hide()
                        this.polygonArr[i].circle.hide()
                        this.polygonArr[i].infoWindow.close()
                        this.aMap.remove([this.polygonArr[i].polygon, this.polygonArr[i].circle])
                    } else {
                        this.polygonArr[i].hide()
                        this.aMap.remove(this.polygonArr[i])
                    }
                }
            } else {
                this.polygonArr.forEach((item) => { this.aMap.remove([item.polygon, item.circle]) })
                this.polygonArr = []
            }
        },
        isShowPart(bol) {
            bol ? this.removePark() : this.showPark()
        },
        showPartInfo(park) {
            let center = park.center.split(',')
            let obj = this.polygonArr.filter((item) => item.id==park.id)[0]
            obj.infoWindow.open(this.aMap, new AMap.LngLat(center[0], center[1]));
            this.aMap.setFitView([obj.polygon, obj.circle], false)
        },
        isOpenPart(park) {
            let obj = this.polygonArr.filter((item)=> item.id==park.id)[0]
            park.ifDisenable ? obj.polygon.show() : obj.polygon.hide()
            if(park.parkType!='RidingCanton') {
                park.ifDisenable ? obj.circle.show() : obj.circle.hide()
            }
        },
        openDraw() {
            this.showDrawTool = true
            console.log("MouseTool")
            this.aMap.plugin(["AMap.MouseTool"], () => {
                this.drawTool = new AMap.MouseTool(this.aMap);
                this.drawTool.polygon({
                    strokeColor: "blue",
                    fillColor:'#09f',
                    strokeOpacity: 0.5,
                    fillOpacity: 0.1,
                    strokeWeight: 3,
                    strokeStyle: 'solid'
                });
            });
            this.drawTool.on('draw', (ev) => {
                // console.log(ev.obj.B.path, ev.obj.Je.path)
                this.overlays.push(ev.obj);
                let partStr = '',
                    pathArr = ev.obj.B.path
                pathArr.forEach((item, i) => {
                    partStr += pathArr[i].Q+','+pathArr[i].P+(i==pathArr.length-1 ? '' : ';')
                })
                this.$confirm('确定使用当前绘画的坐标吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this.$bus.$emit('ParkDotData', partStr)
                }).catch(() => {})
            })
        },
        closeDraw() {
            this.showDrawTool = false
            this.drawTool.close(true)
            this.$bus.$emit('ParkDotData', '')
        },
        clearDraw() {
            this.aMap.remove(this.overlays)
            this.overlays = [];
        }
    },
    created() {
        this.$bus.$on('showDraw', () => { this.openDraw() })

        this.$bus.$on('refreshPark', (parkQuery, bol) => {
            if(bol==1) this.closeDrawTool()
            this.parkQuery = parkQuery
            this.getPark(true)
        })
    },
    mounted() {
        // 同步加载插件
        // var url = 'https://webapi.aMap.com/maps?v=1.4.15&key=908147cba89a3a4f1bc9e3627699ed25&callback=onLoad&&plugin=AMap.ToolBar,AMap.ToolBar';
        var url = 'https://webapi.aMap.com/maps?v=1.4.15&key=908147cba89a3a4f1bc9e3627699ed25&callback=onLoad';
        var jsapi = document.createElement('script');
        jsapi.charset = 'utf-8';
        jsapi.src = url;
        document.head.appendChild(jsapi);
        window.onLoad  = () => {
            this.initMap()
        }
    }
}
</script>

<style rel="stylesheet/scss" lang="scss">
    .map-sum-head {
        padding: 15px 12px;
        border-bottom: 1px solid #ccc;
        position: relative;
        .title {
            color: #409EFF;
        }
        .filter-container {
            float: right;
            margin-top: -5px;
            .filter-item {
                width: 90px;
                margin-right: 10px;
            }
            .input-item {
                width: 200px;
                margin-right: 20px;
            }
        }
        .tipinfo {
            width: 260px;
            position: absolute;
            top: 60px;
            left: 80px;
            z-index: 1;
            padding: 5px 0 1px;
            background-color: #fff;
            border-radius: 5px;
            .img-wrp {
                font-size: .7rem;
                display: flex;
                align-items: center;
                .img-item {
                    flex: 1;
                    text-align: center;
                    margin-left: 10px;
                    display: flex;
                    align-items: center;
                    p {
                        margin: 0;
                        margin-left: 5px;
                        span {
                            color: #409EFF;
                        }
                    }
                }
            }
        }

    }
    .aMap {
        position: relative;
        .draw-menu {
            position: absolute;
            top: 10px;
            right: 360px;
        }
        #allmap {
            height: 500px;
            overflow: hidden;
            background-color: rgba(0,0,0,.2);
            .anchorBL {
                display: none;
            }
        }
    }

</style>
<style lang="scss">
    .list-infoWindow {
        width: 350px;
        margin-top: 10px;
        padding-left: 10px;
        .list-item {
            margin: 8px 10px 8px 20px;
            line-height: 1.3;
        }
        .live {
            position: absolute;
            right: 45px;
            top: 16px;
            display: flex;
            align-items: center;
            &-icon {
                width: 25px;
                height: 25px;
                margin-right: 5px;
            }
        }
    }
</style>
