<template>
  <el-dialog :title="form.showTitle" :visible.sync="isVisible">
    <el-form :model="form" :rules="rules" ref="form" label-width="120px">
      <el-form-item :label="form.headTitle"  prop="name">
        <el-input v-model="form.name" placeholder="请输入名称"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="省份">
            <el-select class="filter-item" v-model="listQuery.addrProvince" placeholder="请选择省份（直辖市）"  @change='getValue'>
              <el-option v-for="item in provinceRegions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="城市">
            <el-select class="filter-item" v-model="listQuery.addrCity" placeholder="请选择城市">
              <el-option v-for="item in cityRegions4Query" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="详细地址" prop="address">
        <el-input v-model="form.address" placeholder="请输入详细地址"></el-input>
      </el-form-item>
      <el-row>
        <el-col :span="8" v-if="form.headTitle == '途径地名称'">
          <el-form-item label="排序">
            <el-input style="width: 150px;" type="number" min="0" v-model="form.rank" placeholder="请输入排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="纬度" prop="latitude">
            <el-input :value="form.latitude" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col  :span="8">
          <el-form-item label="经度"  prop="longitude">
            <el-input :value="form.longitude" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="拾取经纬度">
        <el-input v-model="keyword" placeholder="请输入详细地址获取经纬度"></el-input>
      </el-form-item>
      <el-form-item v-if="1>2">
        <baidu-map class="map" id="mapID" center="东莞市" :zoom="zoom" :scroll-wheel-zoom="true" @click="getPoint"  @ready="handler">
          <!--地图类型，两种：一种是路线一种是绿的那种-->
          <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type>
          <!--地图搜索功能，绑定上面的input，-->
          <!--display: none样式很关键，因为下面默认会有地址提示信息很长，很烦，这样搜索会很舒服，-->
          <!--zoom是搜索结果的视图比例，个人觉得12.8很舒服显示-->
          <bm-local-search :keyword="keyword" :auto-viewport="true" :location="location" zoom="12.8" style="display: none"></bm-local-search>
          <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
          <!--信息窗口，show属性是控制显示隐藏，infoWindowClose和infoWindowOpen是控制信息窗口关闭隐藏的方法-->
          <bm-marker :position="postionMap" >
            <bm-info-window :show="show" class="bm-info" @close="infoWindowClose" @open="infoWindowOpen" style="font-size: 14px">
              <!--<p>站点地址：{{ add.site }}</p>-->
            </bm-info-window>
          </bm-marker>
        </baidu-map>
      </el-form-item>
      <el-form-item>
        <!--:center="center"-->
        <baidu-map

        :zoom="zoom"
        :dragging="true"
        :scroll-wheel-zoom="true"
        class="map"
        @ready="handler"
        @click="getPoint"
        >
        <bm-local-search
          :keyword="keyword"
          :auto-viewport="true"
          :location="location"
          style="display: none"
        ></bm-local-search>
        <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
        <bm-geolocation
          anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
          :showAddressBar="true"
          :autoLocation="true"
        ></bm-geolocation>
        <bm-marker :position="{lng:form.longitude, lat: form.latitude}"></bm-marker>
        </baidu-map>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button  v-if="form.showTitle == '途径地编辑'" type="danger" @click="deleteHandler()">删除</el-button>
      <el-button type="primary" @click="okHandler('form')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import BaiduMap from 'vue-baidu-map';
  import {
    getSonRegionByCodes,
    getRegionByCodes,
  } from 'api/base_info/region/';

  import rsCode from '../../../utils/rsCode';

  import {mapGetters} from 'vuex';
  import {
    getAllCompany,
    getAll
  } from 'api/base_info/branch_company/';
  import ElRow from "element-ui/packages/row/src/row";
  import ElInput from "../../../../node_modules/element-ui/packages/input/src/input.vue";
  import ElCol from "element-ui/packages/col/src/col";
  import ElFormItem from "../../../../node_modules/element-ui/packages/form/src/form-item.vue";
  export default {
    props: ["obj"],
    name: 'destinationDialog',
    components: {
      ElFormItem,
      ElCol,
      ElInput,
      ElRow
    },
    data() {
      return {
        jgNameDialog: false,
        show: false,
        postionMap:{  //地图坐标
          lng: 120.211486,
          lat: 30.256576
        },
        visible2: false,//是否显示删除确认框
        location: '',
        keyword: '',  //搜索框关键词
        zoom: 12.8,   //放大比例
        address:'',   //位置详细信息
        add:{
          siteName:'',
          site:'',
          jd:'',
          wd:'',
          desce:'',
          type:'',
          jgName:'',
          jgNum:'',
        },
        organizationData:[],
        jgName:'',
        jgNum:'',
        form: {
          showTitle: "",//弹框名称
          name: undefined,//地址名称
          keyword:"",//根据关键词查找经纬度
          address:undefined,//详细地址
          longitude: undefined,
          latitude:undefined,
          eventName: undefined
        },
        listQuery: {
          addrProvince: undefined,
          addrCity: undefined,
        },
        rules: {
          name:{
              type: 'string',
              required: true,
              message: '请输入名称',
              trigger: 'blur'
            },
          address: {
              type: 'string',
              required: true,
              message: '请输入详细地址',
              trigger: 'blur'
            },
          longitude:{
            required: true,
            message: '请选择经纬度',
            trigger: 'blur'
          },
          latitude:{
            required: true,
            message: '请选择经纬度',
            trigger: 'blur'
          }
        },
        allCompanies: {},
        allCompaniesArr: [],
        isVisible: false,
        allUpkeepItems: null,
        dialogStatus: undefined,
        baidumapSwitch:false,
        zoom: 16,
        location: "深圳市",
      }
    },
    created() {

    },
    watch: {
      isVisible(newValue, oldValue){
        if(!newValue){
          this.$emit(this.form.eventName, false);
          this.cleanForm();
        }
      },
    },
    mounted() {
      let that = this;
      let row = this.obj;
      this.cleanForm();
      this.form = this.obj;
      this.listQuery.addrProvince = this.obj.province;
      this.listQuery.addrCity = this.obj.city;
      this.keyword = row.keyword?row.keyword:"东莞市";
      this.isVisible = true;
    },
    computed: {
      ...mapGetters([
        'elements',
      ]),
      provinceRegions() {
        return getSonRegionByCodes(1);
      },
      cityRegions4Query() {
        if (!this.$utils.isInteger(this.listQuery.addrProvince)) {
          return null;
        }
        return getSonRegionByCodes(this.listQuery.addrProvince);
      },
    },
    methods: {
      /**
       * 删除
       * */
      deleteHandler(formName) {
//       删除
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.method = 'delete';
          this.$emit(this.form.eventName, this.form);
        })
      },
      querySearch(queryString, cb) {
        let selectArry = [];
        this.allCompaniesArr.map(function(item){
          item.value = item.name;
          selectArry.push(item);
        });
        this.selectArry = selectArry;
        var results = queryString ? selectArry.filter(this.createFilter(queryString)) : selectArry;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      handleSelect(item) {
        this.upkeepForm.branchCompanyId = item.id;
        console.log(item);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return (restaurant.name.indexOf(queryString.toLowerCase()) != -1);
        };
      },
      getTypeName: function(type) {
        if (this.$utils.isEmpty(this.vehicleWarningMsgType[type])) {
          return '未知';
        }
        return this.vehicleWarningMsgType[type].val;
      },
      getValue(e){
        this.listQuery.addrCity = undefined;
      },
      /**
       * 确定
       * */
      okHandler(formName) {
        const set = this.$refs;
        if(!this.listQuery.addrProvince){
          this.$notify({
            title: '请选择省份',
            message: '操作失败！',
            type: 'error',
            duration: 2000
          });
          return;
        }
        if(!this.listQuery.addrCity){
          this.$notify({
            title: '请选择城市',
            message:'操作失败！',
            type: 'error',
            duration: 2000
          });
          return;
        }
        this.form.province = this.listQuery.addrProvince;
        this.form.city = this.listQuery.addrCity;
        set[formName].validate(valid => {
          if (valid) {
            this.$emit(this.form.eventName, this.form);
          } else {
            return;
          }
        });
      },
      /**
       * 加载地图
       * */
      handler({map}){

      },
      //点击获取到当前经纬度
      getClickInfo(e) {
        console.log(e.point.lng);
        console.log(e.point.lat);
        this.form.longitude = e.point.lng;
        this.form.latitude = e.point.lat;
      },
//双向绑定经纬度以及缩放尺寸
      syncCenterAndZoom(e) {
        const { lng, lat } = e.target.getCenter();
        this.form.longitude = lng;
        this.form.latitude = lat;
        // this.zoom = e.target.getZoom();
      },
//经纬度同步
      baidumap(){
        this.baiduDevicelocationx = this.form.longitude
        this.baiduDevicelocationy = this.form.latitude
      },
      /**
       * 弹框-取消
       * */
      cancel() {
        this.$emit(this.form.eventName, false);
        this.cleanForm();
      },
      /**
       * 清空弹框数据
       */
      cleanForm() {
        this.form = {
          showTitle: "",//弹框名称
          name: undefined,//地址名称
          keyword:"",//根据关键词查找经纬度
          address:undefined,//详细地址
          longitude: undefined,
          latitude:undefined,
          eventName: undefined
        };
        this.listQuery = {
          addrProvince: undefined,
          addrCity: undefined,
        }
       
      },
      getPoint(e){    //点击地图获取一些信息，
        this.show = true;
        this.postionMap.lng = e.point.lng;     //通过  e.point.lng获取经度
        this.postionMap.lat = e.point.lat;     //通过  e.point.lat获取纬度
        this.add.jd = e.point.lng;
        this.add.wd = e.point.lat;
        this.zoom = e.target.getZoom();

        let geocoder= new BMap.Geocoder();  //创建地址解析器的实例
        geocoder.getLocation(e.point,rs=>{
          this.add.site = rs.address;
          this.keyword = rs.address;
          this.form.latitude = rs.point.lat;
          this.form.longitude = rs.point.lng;
          //地址描述(string)=
          // console.log(rs.address);    //这里打印可以看到里面的详细地址信息，可以根据需求选择想要的
          // console.log(rs.addressComponents);//结构化的地址描述(object)
           console.log(rs.addressComponents.province); //省
           console.log(rs.addressComponents.city); //城市
           console.log(rs.addressComponents.district); //区县
           console.log(rs.addressComponents.street); //街道
           console.log(rs.addressComponents.streetNumber); //门牌号
          // console.log(rs.surroundingPois); //附近的POI点(array)
          // console.log(rs.business); //商圈字段，代表此点所属的商圈(string)
        });
      },
      infoWindowClose () {
        this.show = false
      },
      infoWindowOpen () {
        //这里有个问题纠结了很久，百度的信息窗口默认有个点击其他地方就消失的事件，我没有找到
        //并且信息窗口点击一次显示，一次消失
        //于是我加了一个100毫秒的定时器，保证每次点击地图都可以展示信息窗口
        setInterval(()=>{
          this.show = true
        },100)
      },
    }
  }
</script>
<style scoped>
  .map {
    width: 100%;
    height: 500px;
  }

  .bm-info input[type="button"]{
    width: 30px;
  }
</style>
