<template>
    <div class="alarm-container" v-show="isPageShow">
        <van-nav-bar :title="title" :left-arrow="false" :border="true" @click-left="onNavBack"></van-nav-bar>
        <div id="details_map" class="details_map" style="width: 100%;height: 100vh"></div>
        <div class="notice">{{ alarm.message + '' }}</div>
        <div class="refresh" @click="onRefresh">
            <van-icon name="replay" size="25"/>
            <span>刷新</span>
        </div>
        <div class="bottom">
            <div class="address">
                <div class="title">
                    <p>{{ params.address }}</p>
                </div>
                <div class="time">
                    <span>{{ params.time }}</span>
                </div>
            </div>
            <div class="action">
                <van-button
                    v-for="(item, index) in buttonList"
                    :key="index"
                    :type="item.type"
                    :icon="item.icon"
                    v-show="item.show"
                    @click="onErrorReport(item.name)"
                >{{ item.text }}</van-button>
            </div>
        </div>
        <!-- 外部地图app选择弹窗 -->
        <van-action-sheet
            class="actionSheet"
            v-model="actionSheetShow"
            title="即将打开以下外部APP进行导航"
            :actions="mapAppList"
            :closeable="false"
            cancel-text="取消"
            @select="onSelect"
        />
    </div>
</template>

<script>
import MapLoader from "@/config/amap.js";
import APICore from "@/api/core";
import { isNotNull } from "@/utils/index";
export default {
  name: 'alarm-details',
  inject: ["reload"],
  data(){
   return {
       alarm: {
           message: '你的孩子靠近水域危险区',
           address: '',
           time: '2023-03-14 14:16:55',
           glng: '113.175203274874',
           glat: '23.0261293630648'
       },
       currentAddress: {
           address: '',
           lng: '',
           lat: ''
       },
       buttonList: [
        { name: 'goHere', text: '去这里', type: 'primary', icon: 'guide-o', show: true},
        { name: 'errorReport', text: '免告警', type: 'primary', icon: 'warn-o', show: true },
       ],
       map: {
           geocoder: null,
           instance: null,
           resizeEnable: true,
           zoom: 18,
           centerMarker: null,
           center: [113.175203274874, 23.0261293630648],
       },
       markers: null,
       actionSheetShow: false,
       mapAppList: [
           { name: "高德地图", wakeUpUrl: "https://uri.amap.com/marker?", number: 0 },
           { name: "腾讯地图", wakeUpUrl: "https://apis.map.qq.com/tools/poimarker?", number: 1 }
       ],
       params: {
           imei: '',
           poiId: '',
           title: '',
           lng: '',
           lat: '',
           address: '',
           status: true,
           time: ''
       },
       isPageShow: null,
       status: 1
   }
  },
  computed: {
    title() {
        return this.status === "1" ? '进入涉水区域警报' : '离开涉水区域警报';
    }
  },
  created() {
    this.getAuth();
    this.getParams();
    //this.initAmap();
  },
  methods: {
    // 获取b端接口的token
    getAuth() {
        let manufactorId = "5bf13062-a41e-4d00-ba14-1101aad12650";
        APICore.getAuth({ manufactorId: manufactorId }).then(res => {
            this.$store.commit("gatewayToken", res.data.data);
        });
    },
    // 获取路由参数
    getParams() {
        let params = this.$route.query;
        if (isNotNull(params)) {
            console.log("params", params);
            this.params = {...params};
            this.buttonList[1].show = params.status === "1";
            this.status = params.status;
            this.alarm.message = params.status === "1" ? '你的孩子靠近水域危险区': '你的孩子离开水域危险区';
            this.isPageShow = true;
            this.initAmap();
            console.log("this.params", this.params);
        } else {
            this.$dialog.confirm({
                message: '跳转参数错误,请联系管理员',
                showCancelButton: false
            })
            this.isPageShow = false;
        }
    },
    onNavBack() {},
    // 初始化地图
    initAmap() {
        this.$toast.loading('地图加载中');
        MapLoader(false, [ 'AMap.PolyEditor', 'AMap.MouseTool', 'AMap.Geocoder', 'AMap.Geolocation', 'AMap.ToolBar' ]).then(
            AMap => {
                this.map.instance = new AMap.Map("details_map", {
                    center: [this.params.lng, this.params.lat],
                    resizeEnable: this.map.resizeEnable,
                    zoom: this.map.zoom,
                    zoomEnable: true
                });
                // 构建逆地理编码器
                this.map.geocoder = new AMap.Geocoder({
                    extensions: "all"
                });
                const toolBar = new AMap.ToolBar({ offset: new AMap.Pixel(10, 310), position: 'RB' });
                this.map.instance.addControl(toolBar);
                this.initCenterMarker();
                this.$toast.success('地图加载完成');
                this.geocoder([this.params.lng, this.params.lat]);
            },
            err => {
                this.$toast.clear();
                console.log("加载地图失败:::", err);
            }
        );
        setTimeout(() => {
            this.$toast.clear();
        }, 5000)
    },
    // 初始化marker
    initCenterMarker() {
        const content = '<div class="centerMarker"><i class="cir"></i></div>';
        let position = this.map.instance.getCenter();
        console.log("position", position);
        position = [ position.lng, position.lat ];
        if(this.map.centerMarker) {
            // 如果 存在marker，则清掉前一个marker，防止出现多个marker的情况
            this.map.instance.remove(this.map.centerMarker);
        }
        // 创建一个 Icon
        let markerIcon = new AMap.Icon({
            size: new AMap.Size(25, 34),
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
            imageSize: new AMap.Size(135, 40),
            imageOffset: new AMap.Pixel(-95, -3)
        });
        this.map.centerMarker = new AMap.Marker({
            position: position,
            icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
            offset: new AMap.Pixel(-13, -30)
        });
        this.map.instance.add(this.map.centerMarker);
    },
    // 逆地理编码，通过坐标获取详细中文地址
    geocoder(lngLat) {
        this.map.geocoder.getAddress(lngLat, (status, result) => {
            if (status == "complete" && result.info == "OK") {
                this.currentAddress.address = result.regeocode.formattedAddress;
                this.alarm.address = result.regeocode.formattedAddress;
                console.log("使用高德逆地理解析得到的地址", this.currentAddress.address);
            }
        });
    },
    // 调用高德定位api获取当前位置
    createGeolocation() {
        this.map.geolocation = new AMap.Geolocation({
            nableHighAccuracy: true, //是否使用高精度定位，默认:true
            timeout: 10000,           //超过10秒后停止定位，默认：5s
            zoomToAccuracy: false,     //定位成功后是否自动调整地图视野到定位点
            buttonPosition:'LT',      //定位按钮的停靠位置
            showButton: process.env.NODE_ENV !== 'production',
            buttonOffset: new AMap.Pixel(20, 400), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: false,        // 定位成功后是否显示marker
            showCircle: false,        // 定位成功并且有精度信息时，是否用一个圆圈circle表示精度范围，默认值：true
        });
        this.map.instance.addControl(this.map.geolocation);
        const _this = this;
        const localeLoading = this.$toast.loading('获取定位中...');
        this.map.geolocation.getCurrentPosition(function (status, result) {
            try {
                if(status == 'complete') {
                    console.log('定位完成:::', result);
                    const position = [ result.position.lng, result.position.lat ];
                    _this.geocoder(position);
                } else {
                    console.error('用户未授权定位:::');
                    console.error('status:::', status);
                    console.error('result:::', result);
                    _this.$notify({
                        type: 'warning',
                        message: '您未打开定位服务，前往设置可打开'
                    });
                }
            } catch (e) {
                console.log(e);
            } finally {
                localeLoading.clear();
            }
        })
    },
    // 免告警
    onErrorReport(name) {
        if(name === 'goHere') {
            // 根据选择的地图跳转不同地图app的url
            this.actionSheetShow = true;
        } else {
            this.$dialog({
                title: '',
                message: '点击确认后，进入这个区域将永不告警',
                showCancelButton: true,
                closeOnClickOverlay: true,
            }).then(() => {
                // 调取接口设置该设备IMEI与该水域告警poi_id不做任何报警信息处理
                this.drownReportFilterAdd();
            }).catch(() => {
                console.log("取消");
            })
        }
    },
    // 误报接口
    drownReportFilterAdd() {
        this.$toast.loading('设置中');
        let reqBody = {
            ...this.params
        };
        reqBody['status'] = true;
        delete reqBody.message;
        delete reqBody.time;
        console.log("请求的参数", reqBody);
        APICore.drownReportFilterAdd(reqBody).then(res => {
            console.log("res", res);
            let data = res.data;
            if(data.code === 0) {
                this.$toast.success('设置成功')
            };
        }).catch(error => {
            this.$dialog.confirm({
                message: `${error.message}`
            });
        }).finally(() => {
            setTimeout(() => {
                this.$toast.clear();
            },1500)
        })
    },
    // 选择打开外部地图app
    onSelect(item) {
        if(item.number === 0) {
            // 高德
            this.wakeUpGaodeMap(item.wakeUpUrl);
        } else if (item.number === 1) {
            this.wakeUpTencentMap(item.wakeUpUrl);
        }
    },
    // 唤醒高德地图
    wakeUpGaodeMap(wakeUpUrl) {
        const position = this.params.lng + ',' +this.params.lat;
        const name = this.params.address;
        window.location.href = `${wakeUpUrl}position=${position}&name=${name}&callnative=1`;
    },
    // 唤醒 腾讯地图
    wakeUpTencentMap(wakeUpUrl) {
        const position = this.params.lat + ',' + this.params.lng ;
        const address = this.params.address;
        const key = 'UHFBZ-I5ECQ-GSA5B-GW3UW-V2NL5-A3FNY';
        const myAppName = 'ssjlqqmap';
        window.location.href = `${wakeUpUrl}type=0&marker=coord:${position};title:${address};addr:${address}&key=${key}&referer=${myAppName}`;
    },
    // 刷新
    onRefresh() {
        this.reload();
    }
  }
}
</script>
<style lang="scss">
    .alarm-container {
        .details_map {
            $width: 50PX;
            $cirWidth: 15PX;
            .centerMarker {
                position: relative;
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 999;
            }

            .centerMarker i.cir {
                display: flex;
                justify-content: center;
                align-items: center;
                width: $width;
                height: $width;
                background: rgba(255, 178, 128, 0.4);
                border-radius: 50%;
            }
            .centerMarker i.cir:after {
                content: " ";
                width: $cirWidth;
                height: $cirWidth;
                background: #ff9625;
                border: 2PX solid #fff;
                border-radius: 50%;
            }
        }
    }
</style>
<style scoped lang="scss">
.alarm-container {
    position: relative;
    height: 100vh;
    width: 100%;
    .van-nav-bar {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
    }
    .notice {
        position: absolute;
        top: 40px;
        height: 40px;
        width: 100%;
        background-color: #ee0a24;
        color: #fff;
        font-size: 14px;
        @include center();
    }
    .refresh {
        position: absolute;
        top: 100px;
        right: 20px;
        height: 50px;
        width: 50px;
        background-color: #fff;
        box-shadow: 0 0 5px 1px rgba(185, 185, 185, 0.4);
        border-radius: 5px;
        @include center();
        flex-direction: column;
        span {
            font-size: 14px;
        }
    }
    .bottom {
        width: 100%;
        position: absolute;
        bottom: 0;
        left: 0;
        background-color: $background;
        z-index: 999;
        padding-bottom: constant(safe-area-inset-bottom); //* 兼容 iOS<11.2 */
        padding-bottom: env(safe-area-inset-bottom); ///* 兼容iOS>= 11.2 */
        .address {
            padding: 10px;
            display: flex;
            justify-content: flex-start;
            align-items: flex-start;
            flex-direction: column;
            font-size: 14px;
            margin: 10px 10px 0 10px;
            .title {
                width: 100%;
                text-align: left;
                font-weight: bold;
            }
            .time {
                width: 100%;
                background-color: #fff;
                padding: 5px 0;
                margin: 5px 0;
                font-weight: 400;
                text-align: left;
                border-radius: 5px;
                span {
                    margin-left: 5px;
                }
            }
        }
        .action {
            display: flex;
            justify-content: space-around;
            padding-bottom: 15px;
            .van-button {
                width: 120px;
            }
        }
    }
}
</style>
