<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyName" size="small" clearable placeholder="请输入机构名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" size="small" v-on:click="getList">查询</el-button>
				</el-form-item>
				<el-form-item style="float:right;">
                    <!--  v-if="user.parentId == 1 && user.subordinateType == 0" -->
					<el-button type="primary" size="small" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="list" highlight-current-row v-loading="listLoading" :height="tableHeight" style="width: 100%;">
			<el-table-column type="index" width="60"></el-table-column>
			<el-table-column prop="name" label="机构名称" width="300" sortable></el-table-column>
            <el-table-column prop="phone" label="联系方式" width="200" sortable></el-table-column>
            <el-table-column prop="address" label="机构位置" sortable></el-table-column>
			<el-table-column label="操作" width="160" align="center">
				<template slot-scope="scope">
                    <el-button type="primary" size="small" @click="toDetail(scope.row.id)">详情</el-button>
					<el-button type="danger" size="small" @click="toDelete(scope.row.id)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :page-sizes="[20 , 50 , 80 , 100]"
                :page-size="20"
                layout="total, sizes, prev, pager, next"
                :total="total"
                style="float:right;">
            </el-pagination>
		</el-col>

        <!--新增界面-->
		<el-dialog title="新增培训机构" v-if="addFormVisible" :visible.sync="addFormVisible" :close-on-click-modal="false" customClass='customWidth'>
            <el-form :model="addForm" label-width="100px" :rules="formRules" ref="addForm">
				<el-form-item label="机构名称" prop="name">
					<el-input v-model="addForm.name" autocomplete="off" placeholder="请输入机构名称"></el-input>
				</el-form-item>
                <el-form-item label="联系方式" prop="phone">
					<el-input v-model="addForm.phone" autocomplete="off" placeholder="请输入联系方式"></el-input>
				</el-form-item>
                <el-form-item label="机构地址" prop="address">
					<el-input v-model="addForm.address" autocomplete="off" :change="changeFactoryArea('addContainer')" placeholder="请输入机构地址"></el-input>
				</el-form-item>
                <div id="addContainer" class="formMap"></div>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import Vue from 'vue';
    import util from '../../common/js/util'
    
	export default {
		data() {
			return {
				filters: {
					keyName: ''
                },
                user: JSON.parse(sessionStorage.getItem('user')),
                charger: [],
                molds: [],

				list: [],
				total: 0,
                page: 1,
                size: 20,
                listLoading: false,
                tableHeight: 0,

                formRules: {
					name: [
						{ required: true, message: '请输入机构名称', trigger: 'blur' }
                    ]
                },

                // 地图
                map: '',
                marker: '',
                
                // 新增界面
                addFormVisible: false,
				addLoading: false,
				addForm: {
					name: '',
                    address: '',
                    phone: '',
                    yLng: 116.397511,
                    xLat: 39.907545,
				}

			}
		},
		methods: {
			//分页
			handleCurrentChange(val) {
				this.page = val;
				this.getList();
            },

            handleSizeChange(val) {
                this.size = val;
				this.getList();
            },
            
			//获取项目列表
			getList() {
				this.listLoading = true;
				this.http.post(this.port.agency.list, {
                    // keyName: this.filters.keyName,
                    pageNum: this.page,
                    pageSize: this.size,
                }, res => {
                    this.listLoading = false;
                    if (res.code == "ok") {
                        this.list = res.data.list;
                        this.total = res.data.total;
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.listLoading = false;
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },

            //详情
            toDetail(id) {
                this.$router.push('/agency/' + id);
            },

            //删除
            toDelete(id) {
                this.$confirm('确认删除该培训机构吗?', '提示', {
					type: 'warning'
				}).then(() => {
                    this.http.post(this.port.agency.delete, {
                        id: row.id
                    }, res => {
                        if (res.code == "ok") {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                            this.getList();
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            });
                        }
                    }, error => {
                        this.$message({
                            message: error,
                            type: 'error'
                        });
                    })
				});
            },

            //显示新增界面
			handleAdd() {
				this.addFormVisible = true;
				this.addForm = {
					name: '',
                    address: '',
                    phone: '',
                    yLng: 116.397511,
                    xLat: 39.907545,
				};
            },

            //新增
			addSubmit() {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
                        this.addLoading = true;
                        this.http.post(this.port.agency.add, {
                            name: this.addForm.name,
                            address: this.addForm.address,
                            lng: this.addForm.address==''?null:this.addForm.yLng,
                            lat: this.addForm.address==''?null:this.addForm.xLat,
                        } , res => {
                            this.addLoading = false;
                            if (res.code == "ok") {
                                this.addFormVisible = false;
                                this.$message({
                                    message: '创建成功',
                                    type: 'success'
                                });
                                this.getList();
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.addLoading = false;
                            this.addFormVisible = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
					}
				});
            },

            //地址输入切换
            changeFactoryArea(mapId) {
                if(mapId == "addContainer"){
                    this.markLocation(this.addForm.address, mapId);
                } else {
                    this.markLocation(this.editForm.address, mapId);
                }
            },
            
            //获取地图
            setMap(mapId) {
                if(mapId == 'addContainer') {
                    this.map = new AMap.Map('addContainer', {
                        resizeEnable: true, // 允许缩放
                        center:[ this.addForm.yLng , this.addForm.xLat ],
                        zoom:10
                    })

                    this.marker = new AMap.Marker({
                        map: this.map,
                        position: new AMap.LngLat(this.addForm.yLng , this.addForm.xLat),   // 经纬度
                    });
                } else {
                    this.map = new AMap.Map('editContainer', {
                        resizeEnable: true, // 允许缩放
                        center:[this.editForm.yLng , this.editForm.xLat],
                        zoom:10
                    })

                    this.marker = new AMap.Marker({
                        map: this.map,
                        position: new AMap.LngLat(this.editForm.yLng , this.editForm.xLat),   // 经纬度
                    });
                }
                
                var _this = this;
                this.map.on('click', function(e) {
                    if(_this.map){
                        _this.map.remove(_this.marker);
                    }
                    var Lng = e.lnglat.getLng(),
                    Lat = e.lnglat.getLat();
                    if(mapId == 'addContainer') {
                        _this.addForm.yLng = Lng;
                        _this.addForm.xLat = Lat;
                    } else {
                        _this.editForm.yLng = Lng;
                        _this.editForm.xLat = Lat;
                    }
                    _this.marker = new AMap.Marker({
                        map: _this.map,
                        position: new AMap.LngLat(Lng , Lat),   // 经纬度
                    });
                });
            },

            // 获取经纬度
            markLocation(address,mapId) {
                var _this = this;
                AMap.plugin('AMap.Geocoder', function() {
                    var geocoder = new AMap.Geocoder();            
                    geocoder.getLocation(address, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            // 经纬度                      
                            var lng = result.geocodes[0].location.lng;
                            var lat = result.geocodes[0].location.lat;
                            
                            _this.noSub = false;
                            if(mapId == "addContainer") {
                                _this.addForm.yLng = lng;
                                _this.addForm.xLat = lat;
                            } else {
                                _this.editForm.yLng = lng;
                                _this.editForm.xLat = lat;
                            }
                            
                            // 添加标记
                            if(_this.map){
                                _this.map.remove(_this.marker);
                                _this.map.setZoomAndCenter(10, [lng, lat]);
                                _this.marker = new AMap.Marker({
                                    map: _this.map,
                                    position: new AMap.LngLat(lng, lat),   // 经纬度
                                });
                            }

                        } else {
                            //console.log('定位失败！');
                        }
                    });
                });
            }
        },
        created() {
            let height = window.innerHeight;
            this.tableHeight = height - 210;
            const that = this;
            window.onresize = function temp() {
                that.tableHeight = window.innerHeight - 210;    
            };
        },
        watch: {
            addFormVisible(val) {
                if(val){
                    var _this = this
                    setTimeout(function(){ _this.setMap('addContainer'); }, 300);
                }
            },
            editFormVisible(val) {
                if(val){
                    var _this = this
                    setTimeout(function(){ _this.setMap('editContainer'); }, 300);
                }
            }
        },
		mounted() {
			this.getList();
		}
	}

</script>

<style scoped>
    .formMap {
        height: 400px;
    }
</style>