<template>
  <div>
    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
                :inline="true"
                :model="dataForm"
                :rules="dataRule"
                :disabled="formType === 'detail'"
                class="form">

        <el-form-item label="服务站名称"
                      prop="name"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入服务站名称"
                    v-model="dataForm.name">
          </el-input>
        </el-form-item>
        <el-form-item label="服务站地址"
                      prop="address"
                      label-width="150px"
                      style="display: block">
          <el-input class="item_width_1"
                    maxlength="50"
                    show-word-limit
                    placeholder="请输入服务站地址"
                    v-model="dataForm.address">
          </el-input>
        </el-form-item>

        <el-form-item label="服务站坐标"
                      prop="longitude"
                      label-width="150px"
                      style="display: block">
          <div style="width:500px">
            <el-input class="item_width_4"
                      maxlength="50"
                      placeholder="请输入关键字"
                      v-model="keyWords">
            </el-input>
            <el-button style="margin-left: 10px"
                        type="primary"
                        size="small"
                        @click="handleSearchMap">查询</el-button>
            <div id="app"
                  class="div_map"></div>
            <div style="margin-top: 10px">
              <span>经度</span>
              <el-input class="item_width_3"
                        maxlength="50"
                        placeholder="请输入经度"
                        readonly="true"
                        v-model="dataForm.longitude">
              </el-input>
              <span style="margin-left: 20px">纬度</span>
              <el-input class="item_width_3"
                        maxlength="50"
                        placeholder="请输入纬度"
                        readonly="true"
                        v-model="dataForm.latitude">
              </el-input>
            </div>
          </div>
        </el-form-item>
        <el-form-item label-width="150px" label="排序">
            <el-input-number v-model="dataForm.sort" :min="0" :max="10" label="请输入排序"></el-input-number>
        </el-form-item>
      </el-form>
    </div>
    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 v-if="formType != 'detail'"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { requestPost } from '@/js/dai/request'
var map
var search
var markers
var infoWindowList
let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      btnDisable: false,
      dataForm: {
        structReferenceId: '', //关联动力主轴ID
        name: '', //服务站名称
        address: '', // 服务站地址
        longitude: '', //服务站经度
        latitude: '', //服务站纬度
        sort: '', // 排序
      },
      keyWords: ''
    }
  },
  components: {},
  mounted () {
    this.initMap()
  },

  methods: {
    async initForm (type, row, agencyObj) {
      this.$refs.ref_form.resetFields();
      this.agencyObj = agencyObj
      this.formType = type
      console.log(row)
      if (row) {
        this.dataForm = JSON.parse(JSON.stringify(row))
        map.setCenter(new TMap.LatLng(this.dataForm.latitude, this.dataForm.longitude))
        this.setMarker(this.dataForm.latitude, this.dataForm.longitude)
      } 
      // else {
      //   map.setCenter(new TMap.LatLng(agencyObj.latitude, agencyObj.longitude))
      // }
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap () {
      // 定义地图中心点坐标
      var center = new window.TMap.LatLng(36.0722275, 120.38945519)
      // 定义map变量，调用 TMap.Map() 构造函数创建地图
      map = new window.TMap.Map(document.getElementById('app'), {
        center: center, // 设置地图中心点坐标
        zoom: 17.2, // 设置地图缩放级别
        pitch: 43.5, // 设置俯仰角
        rotation: 45 // 设置地图旋转角度
      })

      search = new window.TMap.service.Search({ pageSize: 10 })
      // 新建一个地点搜索类
      markers = new TMap.MultiMarker({
        map: map,
        geometries: []
      })
      infoWindowList = Array(10)

      // 监听地图平移结束
      map.on('panend', () => {
        this.handleMoveCenter()
      })
      this.handleMoveCenter()
    },

    setMarker (lat, lng) {
      markers.setGeometries([])
      markers.add([
        {
          id: '4',
          styleId: 'marker',
          position: new TMap.LatLng(lat, lng),
          properties: {
            title: 'marker4'
          }
        }
      ])
    },

    handleSearchMap () {
      infoWindowList.forEach((infoWindow) => {
        infoWindow.close()
      })
      infoWindowList.length = 0
      markers.setGeometries([])
      // 在地图显示范围内以给定的关键字搜索地点
      search
        .searchRectangle({
          keyword: this.keyWords,
          bounds: map.getBounds()
        })
        .then((result) => {
          let { data } = result
          if (Array.isArray(data) && data.length > 0) {
            const {
              location: { lat, lng }
            } = data[0]
            map.setCenter(new TMap.LatLng(lat, lng))
            this.setMarker(lat, lng)
            this.dataForm.latitude = lat
            this.dataForm.longitude = lng
          } else {
            this.$message.error('未检索到相关位置坐标')
          }
        })
    },

    handleMoveCenter () {
      //修改地图中心点
      const center = map.getCenter()
      const lat = center.getLat()
      const lng = center.getLng()
      this.dataForm.latitude = lat
      this.dataForm.longitude = lng
      this.setMarker(lat, lng)
    },

    async handleComfirm () {
        this.btnDisable = true
        setTimeout(() => {
          this.btnDisable = false
        }, 10000)
        this.$refs['ref_form'].validate((valid, messageObj) => {
          if (!valid) {
            app.util.validateRule(messageObj)
            this.btnDisable = false
          } else {
            this.addCommunity()
          }

        })
    },
    async addCommunity () {

      let url = ''
      this.dataForm.structReferenceId = this.axisStructId
      if (this.formType === 'add') {
        url = '/pli/power/serviceStation/save'
      } else {
        url = '/pli/power/serviceStation/update'
      }

      const { data, code, msg } = await requestPost(url, this.dataForm)

      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },

    handleCancle () {
        this.resetData()
        this.$emit('dialogCancle')
    },
    resetData () {
      this.keyWords = ''
      this.dataForm = {
        name: '', // 服务站名称
        address: '', //详细地址
        longitude: '', //服务站经度
        latitude: '' //服务站纬度
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: '服务站名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '服务站名称长度在 1 到 50个字符',
            trigger: 'blur'
          }
        ],
        address: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ]
      }
    },
    propertyRule () {
      name: [
        { required: true, message: '物业名称不能为空', trigger: 'blur' }
        // { min: 1, max: 50, message: '小区名称长度在 1 到 50个字符', trigger: 'blur' }
      ]
    }
  },
  props: {
    axisStructId: { // 动力主轴id
      type: String,
      default: ''
    }
  },
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>



