<template>
    <view>
        <view v-if="isshow" :style="{ height: (winHeight)+ 'px',width: winWidth+'px',overflow:'hidden'}">
            <view class="jfh" :style="{ height: (iStatusBarHeight + 44 )+ 'px' }">
                <view class="jfhz" @tap="guanbi">
                    取消
                </view>
                <!--  <view class="jfhy" @tap="ok">
                    确定
                </view> -->
                <CityPopup :show="showCity" @select="afterSlectCity" @close="showCity = false"></CityPopup>
            </view>
            <view class="search" :style="{ marginTop: (iStatusBarHeight + 44 )+ 'px' }">
                <view class="search-content">
                    <view class="search-icon" @click="selectCity">{{city.label}}</view>
                    <input class="search-input" v-model="keyword" placeholder="请输入详细地址" />
                    <view class="search-btn" @click="searchKeyword">搜索</view>
                </view>
            </view>
            <view id="mapDiv" class="mapDiv" :prop="option" :change:prop="Trenderjs.updateEcharts"
                :style="{height:(winHeight-0-180)+'px'}"></view>

            <!--            <image src="./xwz_dw.png" mode="" class="mapDiv21" :style="{top:((winHeight-iStatusBarHeight-180)/2)+'px'}"> -->
            </image>

            <view class="xlistw">
                <view class="xlistt">
                    所有地址
                </view>
                <view class="xlistwx">
                    <view class="xlist" v-for="(iv,index) in arr_list" :key="index" @click="ok(iv)">
                        <view class="xlist1">
                            {{iv.address}}{{iv.name && `(${iv.name})`}}
                        </view>
                        <view class="xlist2">
                            {{iv.infomation.city && iv.infomation.city }} ({{iv.location.lon}},{{iv.location.lat}})
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import CityPopup from './citypopup.vue';
    export default {
        components: {
            CityPopup
        },
        name: 'syljSelectlocation',
        props: {

            apikey: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                winHeight: 500,
                winWidth: 300,
                iStatusBarHeight: 0,
                arr_list: [],
                lng: "",
                lat: "",
                isshow: false,
                showCity: false,
                keyword: '',
                option: {
                    lng: "",
                    lat: "",
                    apikey: "",
                },
                city: {
                    "label": "德阳市",
                    "value": "156510600"
                }
            }
        },
        props: {

            apikey: {
                type: String,
                default: ''
            }
        },
        onLoad(e) {
            var that = this;
            that.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight;
            uni.getSystemInfo({
                success: function(res) {
                    that.winWidth = res.windowWidth
                    that.winHeight = res.windowHeight


                }
            });
        },
        onHide() {
            //console.log('hide')
        },
        methods: {
            selectCity() {
                this.showCity = true
            },
            afterSlectCity(val) {
                this.city = val
                this.showCity = false
            },
            searchKeyword() {
                if (!this.keyword) {
                    uni.showToast({
                        title: '请输入详细地址',
                        icon: 'none',
                        mask: false,
                    });
                    return
                }
                var that = this;
                let params = {
                    postStr: {
                        "keyWord": this.keyword,
                        "queryType": 12,
                        "start": 0,
                        "count": 10,
                        "specify": this.city.value
                    },
                    type: 'query',
                    tk: this.apikey,
                }
                uni.showLoading({
                    mask: true
                })
                uni.request({
                    url: 'https://api.tianditu.gov.cn/v2/search',
                    method: 'GET',
                    data: params,
                    success: res => {
                        if (res.data.status.infocode === 1000) {
                            const {
                                pois: aPoints,
                                count
                            } = res.data
                            if (count === '0' || !aPoints || !aPoints.length) {
                                uni.showToast({
                                    title: '没有找到该地址',
                                    icon: 'none',
                                    mask: false,
                                });
                                return
                            }
                            const {
                                pois,
                                keyWord,
                                lonlat
                            } = aPoints[0]
                            const values = aPoints.map((item) => this.formatterAdressLocation(item, 2))
                            that.arr_list = values
                            const [lon, lat] = lonlat.split(',')
                            this.setIcon(new T.LngLat(lon, lat), true)
                            this.changeCenter(lon, lat)
                        } else {

                        }
                    },
                    fail: () => {
                        //console.log('获取失败')
                    },
                    complete: () => {
                        uni.hideLoading();
                    }
                });
            },
            ok(item) {
                this.$emit('ok', item)
                this.isshow = false
                this.$destroy();
            },
            open(e, f, g) {
                var that = this;
                that.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight;
                uni.getSystemInfo({
                    success: function(res) {
                        that.winWidth = res.windowWidth
                        that.winHeight = res.windowHeight


                    }
                });

                if (e && f && g) {
                    that.isshow = true
                    that.lng = e
                    that.lat = f
                    that.option = {
                        lng: e,
                        lat: f,
                        apikey: g
                    }
                    that.nijiexi({
                        lng: e,
                        lat: f,
                        apikey: g
                    })
                } else {
                    if (g) {
                        that.lng = 116.40769
                        that.lat = 32.89945
                        that.nijiexi({
                            lng: e,
                            lat: f,
                            apikey: g
                        })
                    } else {
                        uni.showToast({
                            title: '请输入天地图apikey',
                            icon: 'none',
                            //mask: true,
                            duration: 2000
                        });
                    }

                }

            },
            guanbi() {
                var that = this;
                that.isshow = false
                this.$emit('guanbi', this.arr_list[0])
                //console.log(888)
                //this.$destroy();
                //that.$refs.selectLocationPop.$destroy()
            },
            queding() {
                var that = this;
                uni.navigateBack();
            },
            nijiexi(e) {
                ////console.log(e)
                var that = this;
                uni.showLoading({
                    //content: '',
                    mask: true
                })
                uni.request({
                    //url: 'https://service.sdmap.gov.cn/geodecode',
                    url: 'https://api.tianditu.gov.cn/geocoder',
                    method: 'GET',
                    data: {
                        postStr: JSON.stringify({
                            lon: e.lng,
                            lat: e.lat,
                            ver: 1,
                        }),
                        type: 'geocode',
                        tk: e.apikey
                    },
                    success: res => {
                        if (res.data.result) {
                            const value = that.formatterAdressLocation(res.data.result, 1)
                            that.arr_list = [value]

                            //that.dqdz=res.data.result.point.name

                        } else {

                        }
                    },
                    fail: () => {
                        if (window.location.origin.search('localhost') >= 0 || window.location.origin
                            .search('10.165.0.173') >= 0) { // 测试环境
                            const value = that.formatterAdressLocation({
                                "formatted_address": "四川省德阳市广汉市西高镇李家院子东北约95米",
                                "location": {
                                    "lon": 104.20046,
                                    "lat": 31.0513
                                },
                                "addressComponent": {
                                    "address": "李家院子",
                                    "town": "高坪镇",
                                    "nation": "中国",
                                    "city": "德阳市",
                                    "county_code": "156510681",
                                    "poi_position": "东北",
                                    "county": "广汉市",
                                    "city_code": "156510600",
                                    "address_position": "东北",
                                    "poi": "李家院子",
                                    "province_code": "156510000",
                                    "town_code": "156510681103",
                                    "province": "四川省",
                                    "road": "洛小路",
                                    "road_distance": 126,
                                    "address_distance": 95,
                                    "poi_distance": 95
                                }
                            }, 1)
                            that.arr_list = [value]
                        }
                    },
                    complete: () => {
                        uni.hideLoading();
                    }
                });

            },
            formatterAdressLocation(obj, type) {
                switch (type) {
                    case 1:
                        return {
                            address: obj.formatted_address,
                                name: '',
                                location: obj.location,
                                infomation: obj.addressComponent
                        }
                        break;
                    case 2:
                        const [lon, lat] = obj.lonlat.split(',')
                        return {
                            address: obj.address,
                                name: obj.name,
                                location: {
                                    lon,
                                    lat
                                },
                                infomation: obj
                        }
                        break
                    default:
                        break;
                }
            }
        }
    }
</script>

<script module="Trenderjs" lang="renderjs">
    const iconPath = require('./xwz_dw.png')
    let Tmap
    export default {
        data() {
            return {
                isinit: false,

            }
        },
        mounted(e) {

            if (typeof window.T === 'function') {


                //this.initEcharts()
            } else {
                ////console.log('init00')
                if (this.option && this.option.apikey) {
                    const script = document.createElement('script')
                    // view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
                    script.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk=' + this.option.apikey

                    script.onload = this.initEcharts.bind(this)
                    document.head.appendChild(script)


                }

            }
        },
        methods: {
            updateEcharts(newValue, oldValue, ownerInstance, instance) {
                // 监听 service 层数据变更
                ////console.log(9999)
                ////console.log(newValue)
                ////console.log(oldValue)
                if (this.option.apikey) {

                    const script = document.createElement('script')
                    script.src = 'http://api.tianditu.gov.cn/api?v=4.0&tk=' + this.option.apikey

                    script.onload = this.initEcharts.bind(this)
                    document.head.appendChild(script)



                }



            },
            initEcharts() {
                var that = this;
                //return
                ////console.log(window.T)
                Tmap = new T.Map('mapDiv', {
                    projection: 'EPSG:4326',
                    minZoom: 10,
                    maxZoom: 20,
                    zoom: 12,
                });
                //console.log(this.option)
                //console.log('init')
                Tmap.centerAndZoom(new T.LngLat(that.option.lng, that.option.lat), 17);
                //Tmap.removeEventListener("moveend");
                this.setIcon(new T.LngLat(that.option.lng, that.option.lat))
                // Tmap.addEventListener("moveend", function(e) {
                //     ////console.log(e.target.getCenter().getLng() + "," + e.target.getCenter().getLat())
                //     that.$ownerInstance.callMethod('nijiexi', {
                //         lng: e.target.getCenter().getLng(),
                //         lat: e.target.getCenter().getLat(),
                //         apikey: that.option.apikey
                //     })
                // });
                Tmap.addEventListener('click', (e) => {
                    const {
                        lnglat
                    } = e
                    const {
                        lat,
                        lng
                    } = lnglat
                    that.$ownerInstance.callMethod('nijiexi', {
                        lng: lng,
                        lat: lat,
                        apikey: that.option.apikey
                    })

                    this.setIcon(new T.LngLat(lng, lat), true)
                });

            },
            changeCenter(lng, lat) {
                Tmap.centerAndZoom(new T.LngLat(lng, lat), 17);
            },
            setIcon(position, isClear) {
                if (isClear) {
                    Tmap.clearOverLays()
                }
                const icon = new T.Icon({
                    iconUrl: iconPath,
                    iconSize: new T.Point(30, 30),
                    iconAnchor: new T.Point(30, 30),
                });
                const marker = new T.Marker(position, {
                    icon,
                });
                Tmap.addOverLay(marker);
            }
        }
    }
</script>

<style>
    page {
        background-color: #FFF;
    }

    .mapDiv {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1008;
        background: #EDEDED;
    }

    .mapDiv2 {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 1;

    }

    .mapDiv21 {
        width: 30px;
        height: 30px;
        position: fixed;
        left: 50%;
        margin-left: -15px;
        top: 50%;
        margin-top: -15px;
        z-index: 10010;
    }

    .jfh {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 44px;
        z-index: 100101;
        background: white;
    }


    .jfhz {
        widows: 40px;
        height: 26px;
        line-height: 26px;
        position: absolute;
        left: 4%;
        bottom: 9px;
        text-align: left;
        font-size: 14px;
        color: #464646;
    }

    .jfhy {
        width: 40px;
        height: 26px;
        line-height: 26px;
        position: absolute;
        right: 4%;
        bottom: 9px;
        text-align: center;
        font-size: 14px;
        color: white;
        background: #3E89F7;
        border-radius: 6px;
    }

    .search {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 44px;
        z-index: 100100;
        display: flex;
        justify-content: center;
        background-color: #FFFFFF;
    }

    .search-content {
        width: calc(100% - 48px);
        height: 32px;
        border-radius: 10px;
        padding: 0 5px 0 10px;
        background-color: rgb(242, 242, 242);
        border-radius: 100px;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .search-icon {
        margin-right: 5px;
        border-right: 1px solid #bababa;
        padding-right: 5px;
    }

    .search-icon:active {
        color: #666666;
    }

    .search-input {
        flex: 1;
        font-size: 14px;
    }

    .search-btn {
        height: 24px;
        color: #FFFFFF;
        font-size: 14px;
        background-color: rgba(148, 170, 41, 0.7);
        text-align: center;
        line-height: 24px;
        border-radius: 25px;
        padding: 0 8px;
    }

    .search-btn:active {
        background-color: #e8e8e8;
        color: #666666;
    }

    .xlistt {
        width: 100%;
        height: 50px;
        line-height: 50px;
        text-align: center;
        font-size: 16px;
        font-weight: bold;
        color: #333333;
        border-bottom: 1px solid #F3F3F3;
        background-color: #FFFFFF;
        position: absolute;
        top: -50px;
        z-index: 1;
    }

    .xlistw {
        position: fixed;
        height: 240px;
        left: 0;
        bottom: 0;
        background-color: white;
        width: 100%;
        z-index: 10006;
        display: flex;
        flex-direction: column;
    }

    .xlistwx {
        flex: 1;
        overflow: scroll;
    }

    .xlist {
        width: 100%;
        height: auto;
        position: relative;
        line-height: 20px;

    }

    .xlist:active {
        background-color: #e8e8e8;
    }

    .xlist1 {
        width: 100%;
        height: auto;
        box-sizing: border-box;
        position: relative;
        line-height: 20px;
        padding-top: 10px;
        padding-bottom: 5px;
        padding-left: 4%;
        padding-right: 4%;
        font-size: 16px;
        color: #1A1A1A;
    }

    .xlist2 {
        width: 100%;
        height: auto;
        box-sizing: border-box;
        position: relative;
        line-height: 20px;
        padding-top: 0px;
        padding-bottom: 10px;
        padding-left: 4%;
        padding-right: 4%;
        font-size: 14px;
        color: #BEBEBE;
    }
</style>