<template>
  <div>
    <!--   百度地图模块   -->
    <el-dialog
      width="70%"
      height="700px"
      title="地图"
      :visible.sync="innerVisible"
      append-to-body
    >
      <baidu-map
        v-if="handReset"
        ref="map"
        :style="mapStyle"
        :center="center"
        :zoom="9"
        :scroll-wheel-zoom="true"
        :dragging="true"
        @click="clickMap"
      >
        <bm-boundary name="宁夏回族自治区" :strokeWeight="1" strokeColor="blue" fillColor="#87a1bc"
                     :fillOpacity="fillOpacityValue"
        ></bm-boundary>
        <bm-view style="width: 100%; height: 100%;" />
        <bm-marker
          :position="{ lng: center.lng, lat: center.lat }"
          :dragging="true"
          animation="BMAP_ANIMATION_BOUNCE"
        />
        <bm-control :offset="{ width: '10px', height: '10px' }">
          <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 100 }">
            <el-input
              v-model="keyword"
              type="text"
              placeholder="请输入地名关键字"
              clearable
            >
              <i slot="prefix" class="el-input__icon el-icon-search" />
            </el-input>
          </bm-auto-complete>
        </bm-control>
        <bm-control anchor="BMAP_ANCHOR_BOTTOM_RIGHT">
          <el-button icon="el-icon-check" circle @click="addressDirectory"></el-button>
        </bm-control>
        <bm-local-search
          :keyword="keyword"
          :auto-viewport="true"
          :panel="mapDetails"
          location=""
          zoom="19"
          :selectFirstResult="true"
        />
      </baidu-map>
    </el-dialog>
    <el-form ref="elForm" :model="form" :rules="rules" label-width="80px">
      <el-input v-model="form.addressId" v-show="false" max="100" />
      <el-form-item label="请输入" prop="proAddress">
        <el-input v-model="form.proAddress" placeholder="请输入工程地址" maxlength="100" show-word-limit  v-no-whitespace/>
      </el-form-item>
      <el-form-item label="经度" prop="longitude">
        <el-input v-model="form.longitude" placeholder="请输入经度" @focus="toggleInnerDialog " v-no-whitespace />
      </el-form-item>
      <el-form-item label="纬度" prop="latitude">
        <el-input v-model="form.latitude" placeholder="请输入纬度" @focus="toggleInnerDialog" v-no-whitespace />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
     <el-button type="primary" @click="submitForm" style="margin-left:65%;" v-preventReClick="5000">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
  </div>
</template>

<script>
import { updateAddress, addAddress } from '@/api/basics/address'

export default {
  name: 'Post',
  dicts: ['sys_normal_disable'],
  props: {
    items: {
      type: Object,
      open: 'true',
      default: () => {
        return {}
      }
    },
    // 在子组件中使用 props 选项去接收来自父组件传递过来的数据
    dialogVisible: Boolean,
    mapHeight: {
      type: Number,
      default: 700
    },
    width: {
      type: [Number, String],
      default: '85%'
    },
    height: {
      type: [Number, String],
      default: '80%'
    }
  },
  data() {
    return {
      fillOpacityValue: 0.2,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: '',
      // 地图是否显示弹出层
      innerVisible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        proAddress: [
          { required: true, message: '工程地址不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '经度不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '纬度不能为空', trigger: 'blur' }
        ]
      },
      //top
      top: 50,
      // 地图参数
      keyword: '', // 地区搜索的信息
      handReset: true,
      mapDetails: false,
      center: { lng: 106.07145, lat: 37.427088 },
      mapStyle: {
        width: '100%',
        height: this.mapHeight + 'px'
      },
      lat: '',
      lon: '',
      selectedProvince: ''
    }
  },
  watch: {
    items: function(val) {
      console.log('监控当前的地图点位', val)
      this.form = val
    },
    // 更新地图点
    center: function(currentValue) {
      console.log('监控当前的地图点位', currentValue)
      // this.BMap.reload()
      this.handReset = false
      this.$nextTick(() => {
        this.handReset = true
      })
    },
    lat: function(currentValue) {
      this.form.latitude = this.$set(this.form, 'latitude', currentValue)
    },
    lon: function(currentValue) {
      this.form.longitude = this.$set(this.form, 'longitude', currentValue)
    },
    selectedProvince: function(currentValue) {
      this.form.selectedProvince = this.$set(this.form, 'selectedProvince', currentValue)
    }
  },
  created() {
    console.log(this.items)
  },
  methods: {
    /** 地图搜索信息显示隐藏 */
    addressDirectory() {
      this.mapDetails = !this.mapDetails
    },
    /** 地图显示隐藏 */
    toggleInnerDialog() {
      console.log('toggleInnerDialog')
      this.innerVisible = true
    },
    /** 点击地图 */
    clickMap(e) {
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat
      this.lat = e.point.lat
      this.lon = e.point.lng

      const geoc = new BMap.Geocoder()
      geoc.getLocation(e.point, (result) => {
        if (result) {
          let province = result.addressComponents.province
          province = province.replace(/(省|市|自治区|回族自治区|壮族自治区|维吾尔自治区)$/, '')
          console.log('Selected Province:', province)
          // You can store the province in a data property if needed
          this.selectedProvince = province
        }
      })

      setTimeout(() => {
        this.innerVisible = false
      }, 100)
    },

    // 取消按钮
    cancel() {
      this.$emit('closeMain')
      this.reset()
    },
    // 表单重置
    reset() {
      this.from = {
        addressId: undefined,
        proAddress: undefined,
        longitude: undefined,
        latitude: undefined,
        selectedProvince: undefined
      }
      this.resetForm('elForm')
    },
    // 在合适的时机触发事件，例如处理完成后
    /** 提交按钮 */
    submitForm: function() {
      console.log('this.form:' + JSON.stringify(this.form))
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          this.items.proAddress = this.form.proAddress
          this.items.longitude = this.form.longitude
          this.items.latitude = this.form.latitude
          this.items.selectedProvince = this.form.selectedProvince
          if (this.items.addressId === -1) {
            console.log('from:' + JSON.stringify(this.form))
            console.log('items:' + JSON.stringify(this.items))
            addAddress(this.items).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.$emit('closeMain')
            })
          } else {
            updateAddress(this.items).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.$emit('closeMain')
            })
          }
        }
      })
    }
  }
}
</script>
