<template>
    <div class="teachingset">
        <m-header />
        <van-search
            v-model="search_value"
            shape="round"
            placeholder="搜小区、学校"
            background="transparent"
            show-action
            @search="onSearch">
            <div slot="action" @click="onSearch">搜索</div>
        </van-search>
        <el-amap :zoom="zoom" :events="amapEvents()" :plugin="plugin" :center="center">
            <el-amap-marker :clickable="true" 
                :events="marker.events" 
                :position="marker.position"  
                v-for="(marker, index) in markers" 
                :key="index"  ></el-amap-marker>
        </el-amap>
        <van-cell-group>
            <van-field
                type="textarea"
                rows="1"
                autosize
                v-model="addressDetail"
                readonly
                label="教学地址"
                placeholder="详情地址" />
            <van-field
                type="text"
                v-model="teachingSchool"
                label="教学点名称"
                placeholder="请输入名称" />
        </van-cell-group>

        <div class="button-group">
            <van-button type="primary" @click="onSubmit" round size="large">确认</van-button>
        </div>
    </div>
</template>
<script>
// import AMap from 'vue-amap'
// AMap.initAMapApiLoader({
//     key: 'c7856e7c812d299cff150e74d60ea608',
//     plugin: ['Geolocation', 'PlaceSearch', 'Geocoder', 'ToolBar'],
//     v: '1.4.4'
// })
/* eslint-disable */
import MHeader from '@/components/MHeader'
import { schoolAdd, schoolUpdate } from '@/api/teacher'
import setLoading from '@/utils/loading'
export default {
    name: 'teachingset',
    components: { MHeader },
    data() {
        let self = this
        return {
            type: this.$route.query.type,
            search_value: '', // 搜索地址
            zoom: 12,
            center: [114.34371, 30.55939],
            markers: [],
            searchResult: [], // 搜索出来的数据
            plugin: [
                {
                pName: 'Geolocation',
                events: {
                    init(o) {
                        if(self.type == 'create') {
                            o.getCurrentPosition((status, result) => {
                                if(result && result.position) {
                                    self.lng = result.position.lng
                                    self.lat = result.position.lat
                                    self.center = [self.lng, self.lat]
                                    self.loaded = true
                                    self.$nextTick()
                                }
                            })
                        }
                    }
                }
            },
             {
                pName: 'ToolBar',
                events: {
                    init() {
                        // console.log(instrance)
                    }
                }
            }],
            searchOption: {
                pageSize: 1, // 单页显示结果条数
                pageIndex: 1, // 页码
                autoFitView: true // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
            },
            addressDetail: null, // 输入详情地址
            teachingSchool: null, // 教学点
            lnglat: null, // 教学点经纬度
        }
    },
    mounted() {
        document.title = '教学点设置'
        let params = this.$route.query
        if(params.Authorization) {
            localStorage.setItem('Authorization', decodeURI(params.Authorization))
            localStorage.setItem('userInfo', decodeURI(params.Authorization))
        }
        if(params.type == 'update') {
            this.addressDetail = params.address
            this.teachingSchool = params.name
            this.lnglat = params.longitudeLatitude
            let tempLnglat = params.longitudeLatitude.split(',')
            this.center = [tempLnglat[0], tempLnglat[1]]
            this.markers.push({
                position: [tempLnglat[0], tempLnglat[1]],
                events: this.markerEvents()
            })
        }
    },
    methods: {
        amapEvents() {
            return {
                complete: () => {
                    // this.$toast('加载完成')
                }
            }
        },
        async onSubmit() { // 确定提交
            if(!this.addressDetail) {
                this.$toast('请选择教学地点')
                return
            }
            if(!this.teachingSchool) {
                this.$toast('请输入教学点名称')
                return
            }
            // 添加教学点
            if(this.type == 'create') {
                setLoading(true)
                await schoolAdd({
                    name: this.teachingSchool,
                    address: this.addressDetail,
                    longitudeLatitude: this.lnglat
                }).then(res => {
                    setLoading(false)
                    let result = res.data
                    if(result.code == 200) {
                        this.$toast('添加成功')
                        this.$router.push('/teachingSchool')
                    } else {
                        this.$toast(result.msg)
                    }
                }).catch(() => {
                    setLoading(false)
                })
            } else if(this.type == 'update') {
                setLoading(true)
                await schoolUpdate({
                    id: this.$route.query.id,
                    name: this.teachingSchool,
                    address: this.addressDetail,
                    longitudeLatitude: this.lnglat
                }).then(res => {
                    setLoading(false)
                    let result = res.data
                    if(result.code == 200) {
                        this.$toast('修改成功')
                        this.$router.push('/teachingSchool')
                    } else {
                        this.$toast(result.msg)
                    }
                }).catch(() => {
                    setLoading(false)
                })
            }
        },
        onSearch() {
            if(!this.search_value) return
            this.markers = [] // 重置位置
            let mapSearch = new AMap.PlaceSearch(this.searchOption)

            // 目前只需要搜索第一条数据
            mapSearch.search(this.search_value, (status, sr) => {
                if(sr && sr.poiList && sr.poiList.count) {
                    let pois = sr.poiList.pois[0]
                    this.searchResult.push(pois)
                    this.markers.push({
                        position: [pois.location.lng, pois.location.lat],
                        events: this.markerEvents(pois)
                    })
                    this.center = [pois.location.lng, pois.location.lat]
                } else if (sr.poiList === undefined) {
                    throw new Error(sr);
                } else if(sr.poiList && sr.poiList.pois.length <= 0) {
                    this.$toast('请输入详细地址')
                }
            })
        },
        markerEvents() { 
            // marker 事件列表
            let that = this
            return {
                click: (e) => {
                    let geocoder = new AMap.Geocoder()
                    geocoder.getAddress(e.lnglat, function(status, result) {
                        if(status === 'complete' && result.regeocode) {
                            that.lnglat = e.lnglat.lng + ',' + e.lnglat.lat
                            that.addressDetail = result.regeocode.formattedAddress
                        } else {
                            that.$toast('请重新选择地址')
                        }
                    })
                }
            }
        }
    }
}
</script>
<style lang='less' scoped>
@import url("../../assets/commonLess/variable.less");
.teachingset {
    min-height: 100vh;
}
.el-vue-amap-container {
    height: 60vh;
}
/deep/.van-sticky--fixed {
    top: .44rem !important;
}
/deep/.van-search {
    position: fixed;
    top: .44rem !important;
    right: 0;
    left: 0;
    z-index: 99;
    padding: .1rem .23rem;
    .van-cell {
        padding: .12rem;
        line-height: .24rem;
    }
    .van-field__control {
        font-size: .16rem;
    }
    .van-search__content {
        border-radius: .5rem;
        background: @whiteColor;
        box-shadow:0px 4px 8px 0px rgba(0,0,0,0.08),0px 0px 1px 0px rgba(0,0,0,0.08);
    }
    .van-icon-search {
        font-size: .2rem;
        font-weight: bold;
        color: @mColor;
    }
    .van-search__action {
        // background-color: #89C8C4;
        background-color: #14928A;
        color: #fff;
        border-radius: 0.15rem;
        position: absolute;
        right: 0.2rem;
        height: .48rem;
        display: inline-block;
        line-height: .5rem;
        border-radius: 2rem;
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
        padding: 0 .2rem;
        font-size: .16rem;
    }
}
.button-group {
    margin: .3rem .26rem .2rem;
    .van-button--primary {
        background: @mColor;
        border-color: @mColor;
        font-size: .18rem;
        height: .5rem;
        line-height: .48px;
    }
}
</style>