<template>
    <div class="myMap">
        <mt-header title="药具领取">
            <div slot="left" @click="toRealHome">
                <mt-button icon="back"></mt-button>
            </div>
        </mt-header>
        <div id="map-container" class="containerMap"></div>
        <div class="scanCode">
            <mt-button icon="saoma" type="primary" @click="ScanCode" v-log="['h5摄像头调用', '开始']">扫码领取</mt-button>
        </div>
        <div class="right_item">
            <div class="item">
                <div class="img" @click="toCollectRecords">
                    <img src="../assets/img/personal.png"/>
                </div>
                <label>领取记录</label>
            </div>
           <!-- <div class="item">
                <div class="img">
                    <img src="../assets/img/artificial.png"/>
                </div>
                <label>人工网点</label>
            </div>-->
            <div class="item">
                <div class="img" @click="toRealHome">
                    <img src="../assets/img/homePage.png"/>
                </div>
                <label>返回首页</label>
            </div>
        </div>
    </div>
</template>

<script>
    import AMap from 'AMap';
    // import {location} from "../utils/mapUtils";
    import machinesImg from '../assets/img/machines.png';
    import closeImg from '../assets/img/close.png';
    import presonImg from '../assets/img/preson.png';
    import sharpImg from '../assets/img/sharp.png';
    import {getNetworkInfo, getUserReceiveNum} from '../utils/api';
    import {callMobile, getQueryVariable, isIOSWebKit} from "../utils/common";
    import {Toast} from 'mint-ui';
    import {GPS} from "../utils/mapCalculation";

    export default {
        name: "myMap",
        data() {
            return {
                recordNum: 0,
                jumpHref: {},
                lngLat: [],
                showMap: false,
                machines: [],
                locationInfo: undefined
            }
        },
        created() {
            this.urltext()
        },
        mounted() {
            this.createMap();
            // 将qrcodeContent方法绑定到window下面，提供给外部调用
            let vm = this
            window['qrcodeContent'] = (result) => {
                    vm.subscanQRCallBack(result)
                this.$nextTick(() => {
                    vm.$uweb.setCustomVar('医站到家扫码', '人数', 0)
                })
            }

        },
        methods: {
            // 接收url后的数据
            urltext() {
                let mobileToken = getQueryVariable('token')
                let userId = getQueryVariable('userId')
                let mobilePhone = getQueryVariable('mobile')
                let realName = getQueryVariable('realName')
                let mobileTokenIno = {
                    token: mobileToken,
                    userId: userId,
                    phone: mobilePhone,
                    realName,
                }
                window.sessionStorage.setItem('mobileTokenIno', JSON.stringify(mobileTokenIno))
            },
            ScanCode() {
                // let info = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
                // const {phone = '', userId = ''} = info
                // let par = {telephone: phone, residentId: userId}//居民id
                // getUserReceiveNum(par).then(({data}) => {
                //     if (data.data == true) {//true 该用户非首次领取需要填写随访
                //         this.$router.push(`/returnVisit`);
                //     } else {
                        callMobile("qrcode", {});
                //     }
                // })
               // this.subscanQRCallBack(111)
            },
            subscanQRCallBack(val) {
                let info = JSON.parse(window.sessionStorage.getItem('mobileTokenIno'))
                const {phone = '', userId = ''} = info
                let urlP = ''
                // let ios = isIOSWebKit()
                // if (ios) {
                // val = 'https://yaojuapp.yiboshi.com/resident/#/resident/manualDistribution?id=39&netType=2&netTypeName=人工发放网点&netName=祥云县沙龙卫生院&status=0'
                    urlP = val
                // } else {
                //     urlP = JSON.parse(val)
                // }
                let id = getQueryVariable('id',urlP)
                let netType = getQueryVariable('netType',urlP)
                let netTypeName = getQueryVariable('netTypeName',urlP)
                let netName = getQueryVariable('netName',urlP)
                let netStauts = getQueryVariable('status',urlP)
                let result = {
                    id,
                    netType,
                    netTypeName,
                    netName,
                    status: netStauts,
                    telephone: phone,
                    resource: '1'
                }
                if (!result.netType) {
                    return
                }
                if (result.status == 1) {
                    Toast({
                        message: '该网点目前非营业中...！',
                        duration: 2000
                    });
                    return;
                }
                if (result.netType == 2){
                    this.$router.push({path: `/manualCollection`, query: result});
                } else {
                    this.$router.push({path: `/choiceContraceptives`, query: result});
                }
            },
            toCollectRecords() {
/*                this.$router.push({
                    path: `/siteDetails`, query: {
                        info: JSON.stringify({
                            "id": 1,
                            "createUnitId": 16625,
                            "netName": "网点1",
                            "netType": 1,
                            "netTypeName": "自助发放网点",
                            "distance": 0.6326,
                            "areaCode": "530111002004",
                            "areaName": "前卫路社区居委会",
                            "netAddress": "云南省昆明动物园",
                            "netLongitude": "102.719907",
                            "netLatitude": "25.029347",
                            "netPerson": "yang",
                            "netPhone": "15845254852",
                            "status": 0,
                            "statusName": "启用",
                            "created": "2020-11-02 11:48:15",
                            "updated": "2020-11-02 17:05:14",
                            'nowLocal': this.lngLat
                        })
                    }
                });*/
                // this.$router.push({path: `/choiceContraceptives`,query:{info:1}});
                this.$router.push('/collectRecords');
            },
            toRealHome() {
                callMobile("goIndex", {});
                // let resultT = {id: 170, type: 2, netTypeName: '人工发放网点', netName: '刘厂镇东甸村委会',status: 0}
                // this.$router.push({path:'/resident/manualDistribution', query: resultT})
            },
            createMap() {
                let self = this
                // let geolocation = location.initMap("map-container"); //定位
                let mapObj;
                let geolocation;
                mapObj = new AMap.Map('map-container', {zoom: 15, mapStyle: "amap://styles/macaron"});
                mapObj.plugin('AMap.Geolocation', function () {
                    geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,//是否使用高精度定位，默认:true
                        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                        maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                        convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                        showButton: true,        //显示定位按钮，默认：true
                        buttonPosition: 'RT',    //定位按钮停靠位置，默认：'LB'，左下角
                        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                        showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                        showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                        panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                        zoomToAccuracy: false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    });
                    mapObj.addControl(geolocation);
                    geolocation.getCurrentPosition();
                    AMap.event.addListener(geolocation, 'complete', onComplete)
                    AMap.event.addListener(geolocation, 'error', onError)
                    self.locationInfo = mapObj
                    function onComplete(data) {
                        // data是具体的定位信息
                        console.log('定位成功信息：', data)
                       // let gpsPoint = GPS.gcj_encrypt(data.position.getLat(), data.position.getLng());
                       //  console.log(gpsPoint)
                        self.creatNetwork(data)
                    }

                    function onError(data) { //非安全域禁止定位（localhost不限制） 改为https即可
                        // 定位出错
                        console.log('定位失败错误：', data)
                    }
                })
            },

            creatNetwork(result) {
                let par = {}
                    this.lngLat = [result.position.lng, result.position.lat];
                    par = {latitude: result.position.lat, longitude: result.position.lng}
                getNetworkInfo(par).then(res => {
                    if (res.data.code === 'SUCCESS') {
                        this.machines = res.data.data;
                        this.createSign();
                    }
                })
            },
            createSign() {
                // 创建一个机器Icon
                let map = this.locationInfo;
                var machinesIcon = new AMap.Icon({
                    size: new AMap.Size(25, 50),
                    image: machinesImg,
                    imageSize: new AMap.Size(25, 50),
                    imageOffset: new AMap.Pixel(0, 0)
                });
                // 创建一个机器Icon
                var personIcon = new AMap.Icon({
                    size: new AMap.Size(40, 40),
                    image: presonImg,
                    imageSize: new AMap.Size(32, 32),
                    imageOffset: new AMap.Pixel(0, 0)
                });
                let markers = [];
                this.machines.forEach(x => {
                    if (x.netType == 2) {
                        let marker = new AMap.Marker({
                            map: map,
                            icon: personIcon,
                            position: [x.netLongitude, x.netLatitude]
                        });
                        this.createInfoWindow(map, marker, x);
                        markers.push(marker);
                    } else {
                        let marker = new AMap.Marker({
                            map: map,
                            icon: machinesIcon,
                            position: [x.netLongitude, x.netLatitude]
                        });
                        this.createInfoWindow(map, marker, x);
                        markers.push(marker);
                    }
                });
            }
            ,
            /*为标记绑定弹窗事件*/
            createInfoWindow(map, marker, info) {
                var infoWindow = new AMap.InfoWindow({ //创建信息窗体
                    isCustom: true,  //使用自定义窗体
                    content: this.windowStyle(marker, info), //信息窗体的内容可以是任意html片段
                    offset: new AMap.Pixel(16, -45)
                });
                var onMarkerClick = function (e) {
                    infoWindow.open(map, e.target.getPosition());//打开信息窗体
                    //e.target就是被点击的Marker
                }
                marker.on('click', onMarkerClick);//绑定click事件
            }
            ,
            /*弹窗样式*/
            windowStyle(marker, info) {
                let _that = this;
                let content = document.createElement("div");
                content.className = "custom-info input-card content-window-card";
                let top = document.createElement("div");
                let titleD = document.createElement("div");
                let closeX = document.createElement("img");
                top.className = "info-top";
                titleD.innerHTML = info.netName;
                closeX.src = closeImg;
                closeX.onclick = this.closeInfoWindow;
                top.appendChild(titleD);
                top.appendChild(closeX);
                content.appendChild(top);

                // 定义中部内容
                let middle = document.createElement("div");
                middle.className = "info-middle";
                middle.innerHTML = "管理员：" + info.netPerson + "</br>联系电话：" + info.netPhone + "</br>" + "地址：" + info.netAddress + "</br>";
                let infoButton = document.createElement("input");
                infoButton.type = "button";
                infoButton.className = "text-button";
                infoButton.value = "详情"
                infoButton.onclick = function () {
                    _that.jumpInfo(info)
                };
                let navigationButton = document.createElement("input");
                navigationButton.type = "button";
                navigationButton.className = "text-button button-right";
                navigationButton.value = "导航"
                navigationButton.onclick = function () {
                    _that.navigation(info)
                };
                middle.appendChild(infoButton);
                middle.appendChild(navigationButton);
                content.appendChild(middle);

                // 定义底部内容
                let bottom = document.createElement("div");
                bottom.className = "info-bottom";
                bottom.style.position = 'relative';
                bottom.style.top = '0px';
                bottom.style.margin = '0 auto';
                let sharp = document.createElement("img");
                sharp.src = sharpImg;
                bottom.appendChild(sharp);
                content.appendChild(bottom);
                return content;
            }
            ,
            /*关闭弹窗*/
            closeInfoWindow() {
                let map = this.locationInfo;
                map.clearInfoWindow();
            }
            ,
            navigation(info) {
                /*           if (this.lngLat.length > 0) {
                               window.location.href = `https://uri.amap.com/navigation?from=${this.lngLat[0]},${this.lngLat[1]},我的位置&to=${info.netLongitude},${info.netLatitude},${info.netAddress}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`
                           } else {*/
                window.location.href = `https://uri.amap.com/navigation?to=${info.netLongitude},${info.netLatitude},${info.netAddress}&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=0`
                /* }*/
            }
            ,
            jumpInfo(info) {
                info['nowLocal'] = this.lngLat
                this.$router.push({path: `/siteDetails`, query: {info: JSON.stringify(info)}});
            }
            ,
        },
    }
</script>

<style>
    .right_item {
        position: absolute;
        z-index: 2;
        right: 15px;
        top: 60%
    }

    .right_item .item .img {
        padding: 9px;
        width: 36px;
        height: 36px;
        margin: 0 auto;
        border-radius: 1.5rem;
        background: white;
    }

    .right_item .item {
        color: #00CA9D;
        margin-top: 20px;
    }

    .myMap {
        height: 100%;
        margin: 0px;
        padding: 0px;
    }

    .containerMap {
        width: 100%;
        height: calc(100% - 40px);
        margin: 0px;
        font-size: 13px;
        position: relative;
        z-index: 1;
    }

    .scanCode {
        position: fixed;
        z-index: 2;
        left: calc(50% - 155px);
        bottom: 20px;
    }

    .scanCode .mint-button {
        width: 311px;
        height: 44px;
        background: linear-gradient(242deg, #dff9b9 -27%, #1bd09f 85%);
        border-radius: 22px;
        box-shadow: 0px 5px 10px 0px rgba(0, 0, 0, 0.1);
    }

    .content-window-card {
        position: relative;
        box-shadow: none;
        bottom: 0;
        left: 0;
        width: auto;
        padding: 0;
    }

    .content-window-card p {
        height: 2rem;
    }

    .custom-info {
        border: solid 1px silver;
    }

    div.info-top {
        position: relative;
        background: none repeat scroll 0 0 #F9F9F9;
        border-bottom: 1px solid #CCC;
        border-radius: 5px 5px 0 0;
    }

    div.info-top div {
        display: inline-block;
        color: #333333;
        font-size: 14px;
        font-weight: bold;
        line-height: 31px;
        padding: 0 10px;
    }

    div.info-top img {
        position: absolute;
        top: 10px;
        right: 10px;
        transition-duration: 0.25s;
    }

    div.info-top img:hover {
        box-shadow: 0px 0px 5px #000;
    }

    div.info-middle {
        padding: 5px;
        width: 196px;
        height: 118px;
        color: #ffffff;
        line-height: 17px;
        background: rgba(0, 0, 0, 0.7);;
        border-radius: 2px;
    }

    .input-card {
        background-color: transparent !important;
    }

    div.info-top div {
        color: #ffffff;
        background: #000000;
        margin-right: 20px;
    }

    div.info-top {
        width: 196px;
        background: #000000;
    }

    div.info-bottom {
        height: 0px;
        width: 100%;
        clear: both;
        text-align: center;
    }

    div.info-bottom img {
        position: relative;
        z-index: 104;
    }

    span {
        margin-left: 5px;
        font-size: 11px;
    }

    .info-middle img {
        float: left;
        margin-right: 6px;
    }

    /*弹窗内按钮样式预留*/
    .text-button {
        border: 0px;
        height: 24px;
        width: 60px;
        margin-left: 20px;
        color: white;
        background: #00CA9D;
        margin-top: 10px;
        opacity: 1;
        border-radius: 12px;
    }

    .button-right {
        margin-right: 20px;
        float: right;
    }

    #container {
        width: 100%;
        height: 100%;
    }

    #panel {
        position: fixed;
        background-color: white;
        max-height: 90%;
        overflow-y: auto;
        top: 10px;
        right: 10px;
        width: 280px;
    }

    #panel .amap-call {
        background-color: #009cf9;
        border-top-left-radius: 4px;
        border-top-right-radius: 4px;
    }

    #panel .amap-lib-walking {
        border-bottom-left-radius: 4px;
        border-bottom-right-radius: 4px;
        overflow: hidden;
    }

    .showMap {
        width: 100%;
        height: 100%;
    }

    div.info-top img {
        width: 15px;
    }

    .myMap >>> .pg-navigation .nearby_top_goback {
        margin-left: 10px;
        width: 0px !important;
        height: 0px !important;
    }
</style>
