<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-12-17 09:40:42
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-25 17:22:38
 -->

<!--
<map-select
  :mapShow="mapShow"
  @hideMapDialog="hideMapDialog">
</map-select>

import mapSelect from '@/components/app/dailyAttendance/map-select.vue'
 -->

<template>
  <div v-show="customDialog">
    <el-dialog class="edit-dialog" title="考勤地点" :visible.sync="customDialog" width="600px" :before-close="handleClose">
      <div class="edit-dialog-body">
        <div class="amap-page-container">
          <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"></el-amap-search-box>
          <el-amap vid="amapDemo" :center="mapCenter" :zoom="zoom" class="amap-demo" :plugin="plugin" :events="events">
            <el-amap-marker v-for="(marker, index) in markers" :position="marker" :key="index + 'maker'" :events="events"></el-amap-marker>
          </el-amap>
          <div class="toolbar m-t-20">
            <!-- position: [{{ lng }}, {{ lat }}] address: {{ address }} -->
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="详细地址：" prop="address">
                <el-input readonly v-model="ruleForm.address"></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click.stop="customCancel">取消</el-button>
        <el-button type="primary" @click.stop="customConfirm('ruleForm')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// import { getRequest } from '@/api/api';
// import errMsg from '@/common/js/error';
// import showMsg from '@/common/js/showmsg';
import { _debounce } from '@/common/js/public';
export default {
  name: 'class-select',
  components: {},
  props: {
    mapShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    let that = this;
    const checkAddress = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择考勤地点'));
      } else if (!this.lng || !this.lat) {
        callback(new Error('请选择考勤地点'));
      } else {
        callback();
      }
    };
    return {
      enterpriseId: JSON.parse(localStorage.getItem('userInfo')).enterpriseId,
      userId: JSON.parse(localStorage.getItem('userInfo')).userId,
      selClassesId: this.classesId,
      customDialog: false,
      ruleForm: {
        address: ''
      },
      rules: {
        address: [{ required: true, validator: checkAddress, message: '请选择考勤地点', trigger: 'blur' }]
      },
      markers: [],
      searchOption: {
        city: '杭州',
        citylimit: false
      },
      zoom: 12,
      mapCenter: [120.12497, 30.277155],
      address: '',
      plugin: [
        {
          pName: 'ToolBar'
        }
      ],
      events: {
        click(e) {
          let { lng, lat } = e.lnglat;
          that.lng = lng;
          that.lat = lat;

          // 这里通过高德 SDK 完成。
          var geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          });
          geocoder.getAddress([lng, lat], function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                /* eslint-disable */
                console.log(result);
                that.address = result.regeocode.formattedAddress;
                that.ruleForm.address = result.regeocode.formattedAddress;
                that.$nextTick();
              }
            }
          });
        }
      },
      lng: 0,
      lat: 0
    };
  },
  methods: {
    /**
     * 搜索
     */
    onSearchResult(pois) {
      let latSum = 0;
      let lngSum = 0;
      if (pois.length > 0) {
        pois.forEach(poi => {
          let {lng, lat} = poi;
          lngSum += lng;
          latSum += lat;
          this.markers.push([poi.lng, poi.lat]);
        });
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        };
        this.mapCenter = [center.lng, center.lat];
      }
    },
    /*
     * 提交
     */
    customConfirm: _debounce(async function(formName) {
      const that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          that.customDialog = false;
          that.$emit('hideMapDialog', {
            address: that.address,
            longitude: that.lng,
            latitude: that.lat
          });
          that.$nextTick(() => {
            that.address = '';
            that.ruleForm.address = '';
          });
        }
      });
    }, 300),
    /**
     *   关闭
     */
    handleClose(done) {
      const that = this;
      done();
      that.hideDialog();
    },

    /**
     *  取消
     */
    customCancel() {
      const that = this;
      that.hideDialog();
    },
    /**
     * 隐藏弹出层
     */
    hideDialog() {
      const that = this;
      that.customDialog = false;
      that.$emit('hideMapDialog');
      that.$nextTick(() => {
        that.address = '';
        that.ruleForm.address = '';
      });
    }
  },
  watch: {
    mapShow: function(newData, oldData) {
      const that = this;
      that.customDialog = newData;
    }
  },
  mounted() {
    const that = this;
    that.customDialog = that.mapShow;
  }
};
</script>

<style lang="less" scoped>
.amap-demo {
  height: 300px;
}
.amap-page-container {
  position: relative;
  .search-box {
    position: absolute;
    top: 25px;
    right: 20px;
    width: 240px;
    height: 32px;
  }
}

</style>
