<template>
  <div>

    <div class="dialog-h-content scroll-h">
      <el-form ref="ref_form"
               :inline="true"
               :model="formData"
               :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="formData.name">
          </el-input>
        </el-form-item>
        <!--<el-form-item label="场所类型"
                      prop="categoryName"
                      label-width="150px"
                      style="display: block">
          <el-select class="item_width_1"
                     v-model="formData.categoryName"
                     placeholder="请选择"
                     filterable
                     clearable>
            <el-option v-for="item in typeList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>-->
        <el-form-item label="场所分类"
                      prop="serviceMatter"
                      label-width="150px"
                      style="display: block">
          <el-select class="item_width_1"
                     v-model="formData.category"
                     placeholder="请选择"
                     size="small"
                     filterable
                     clearable>
            <el-option v-for="item in serviceList"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>

        </el-form-item>

        <el-form-item label="占地面积"
                      style="display: block"
                      prop="areaCovered"
                      label-width="150px">
          <el-input-number class="item_width_4"
                           v-model="formData.areaCovered"
                           :precision="2"
                           :step="0.01"
                           :min="0"
                           :max="9600000"
                           label="占地面积"></el-input-number>平方公里
        </el-form-item>
        <el-form-item label="容纳人数"
                      style="display: block"
                      prop="capacity"
                      label-width="150px">
          <el-input-number class="item_width_4"
                           v-model="formData.capacity"
                           :min="0"
                           :max="9999"
                           label="容纳人数"></el-input-number>人
        </el-form-item>

        <el-form-item label="负责人"
                      style="display: block"
                      label-width="150px"
                      prop="principal">
          <el-input v-model="formData.principal"
                    class="item_width_1"
                    placeholder="请输入负责人姓名"></el-input>
        </el-form-item>
        <el-form-item label="联系电话"
                      style="display: block"
                      label-width="150px"
                      prop="mobile">
          <el-input v-model="formData.mobile"
                    class="item_width_1"
                    placeholder="请输入联系电话"></el-input>
        </el-form-item>

        <el-form-item label="地图位置"
                      prop="longitude"
                      label-width="150px"
                      style="display: block">
          <div style="width: 500px">
            <el-select v-model="searchValue"
                       filterable
                       style="width: 500px"
                       remote
                       :reserve-keyword="true"
                       placeholder="请输入关键词"
                       :remote-method="remoteMethod"
                       :loading="loading">
              <el-option v-for="(item,index) in searchOptions"
                         @click.native="handleClickKey(index)"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
            <div id="app_csgl"
                 class="div_map"></div>
          </div>
        </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="formData.address">
          </el-input>
        </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 { mapGetters } from 'vuex'
import { Loading } from 'element-ui' // 引入Loading服务
import { requestPost } from '@/js/dai/request'
import daiMap from "@/utils/dai-map";


var map
var search
var markers
var infoWindowList
var geocoder // 新建一个正逆地址解析类

let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      searchOptions: [],
      searchValue: '',
      resultList: [],
      loading: false,

      btnDisable: false,
      serviceList: [],
      icCityManagementId: '',
      keyWords: '',
      formData: {
        name: '',
        category: '',//场所分类字典表值
        areaCovered: '',//占地面积
        capacity: 0,//容纳人数
        address: '', //详细地址
        longitude: null, //经度
        latitude: null, //纬度
        principal: '',
        mobile: ''
      },
      cityManagement: {

      }
    }
  },
  components: {},
  mounted () {

  },

  methods: {

    async initForm (type, icCityManagementId) {
      this.startLoading()
      this.$refs.ref_form.resetFields();
      let { latitude, longitude } = this.$store.state.user;
      //获取服务事项
      await this.loadService()

      this.formType = type
      if (icCityManagementId) {
        this.icCityManagementId = icCityManagementId
        this.formData.icCityManagementId = icCityManagementId
        await this.loadFormData()
      } else {
        this.formData.latitude = latitude
        this.formData.longitude = longitude
      }
      // if (!map) {
      this.initMap(this.formData.latitude, this.formData.longitude);
      // }
      this.endLoading()

    },

    //获取服务事项下拉框
    async loadService () {
      const url = "/gov/org/coverage/dict-select-list/city_management"
      // const url = "http://yapi.elinkservice.cn/mock/245/gov/org/coverage/dict-select-list/city_management"
      let params = {
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        this.serviceList = data

      } else {
        this.$message.error(msg)
      }

    },

    //加载组织
    async loadFormData () {
      const url = '/gov/org/icCityManagement/detail'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/icCityManagement/detail'
      let params = {
        icCityManagementId: this.icCityManagementId
      }

      const { data, code, msg } = await requestPost(url, params)

      if (code === 0) {
        if (null != data) {
          data: this.cityManagement
        }
        this.formData = { ...data }
        // let { latitude, longitude } = this.$store.state.user;
        // const lat = this.formData.latitude === null || this.formData.latitude === '' ? latitude : this.formData.latitude;
        // const lon = this.formData.longitude === null || this.formData.longitude === '' ? longitude : this.formData.longitude;
        // if (this.formData.latitude !== null && this.formData.latitude !== '' && this.formData.longitude !== null && this.formData.longitude !== '') {
        //   map.setCenter(new TMap.LatLng(this.formData.latitude, this.formData.longitude))
        //   this.setMarker(this.formData.latitude, this.formData.longitude)
        // }
      } else {
        this.$message.error(msg)
      }
    },



    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.addUnit()
        }

      })


    },
    async addUnit () {
      let url = ''
      if (this.formType === 'add') {
        url = '/gov/org/icCityManagement/add'
      } else {
        url = '/gov/org/icCityManagement/edit'
      }
      const { data, code, msg, internalMsg } = await requestPost(url, this.formData)
      if (code === 0) {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.resetData()
        this.$emit('dialogOk')
        this.btnDisable = false
      } else {
        this.btnDisable = false
        this.$message.error(internalMsg)
      }
    },

    handleCancle () {
      this.resetData()
      this.$emit('dialogCancle')

    },

    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    initMap (latitude, longitude) {

      map = new daiMap(
        document.getElementById("app_csgl"),
        { latitude, longitude },
        {
          zoom: 16.2, // 设置地图缩放级别
          pitch: 43.5, // 设置俯仰角
          rotation: 45, // 设置地图旋转角度
        }
      );

      // 监听地图平移结束
      map.on("dragend", (e) => {
        this.handleMoveCenter(e);
      });

      map.setCenter(latitude, longitude);
      map.setMarker(latitude, longitude);

    },


    async handleMoveCenter () {
      //修改地图中心点
      const { lat, lng } = map.getCenter();
      this.formData.latitude = lat;
      this.formData.longitude = lng;
      map.setMarker(lat, lng);

      let { msg, data } = await map.getAddress(lat, lng);
      if (msg == "success") {
        this.formData.address = data.address
        this.searchValue = data.address
        this.searchOptions = []

      }
    },
    async remoteMethod (query) {

      if (query !== '') {
        this.loading = true;

        const { msg, data } = await map.searchNearby(query);
        this.loading = false;
        this.resultList = []

        if (msg == "success" && data.resultList && data.resultList.length > 0) {

          if (data.resultList && data.resultList.length > 0) {
            this.resultList = data.resultList
            this.searchOptions = this.resultList.map(item => {
              return { value: `${item.hotPointID}`, label: `${item.address + item.name}` };

            });
          }
        } else {
          this.searchOptions = [
            {
              value: '0',
              label: '未检索到结果'
            }
          ]
        }
      } else {
        this.searchOptions = [];
      }
    },

    handleClickKey (index) {
      let selPosition = this.resultList[index]
      let lonlat = selPosition.lonlat.split(" ")
      map.setCenter(lonlat[1], lonlat[0]);
      map.setMarker(lonlat[1], lonlat[0]);
      this.formData.latitude = lonlat[1];
      this.formData.longitude = lonlat[0];
      this.formData.address = selPosition.address + selPosition.name
    },


    resetData () {
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []
      this.unitId = ''
      this.keyWords = ''
      this.formData = {
        name: '',
        category: '',//场所分类字典表值
        areaCovered: '',//占地面积
        capacity: 0,//容纳人数
        address: '', //详细地址
        longitude: '', //经度
        latitude: '' //纬度
      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {

        name: [
          { required: true, message: '场所名称不能为空', trigger: 'blur' },
        ],
        categoryName: [
          { required: true, message: '场所类型不能为空', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '地址不能为空', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ],
        latitude: [
          { required: true, message: '坐标不能为空', trigger: 'blur' }
        ]
      }
    },

  },
  props: {

    typeList: {
      type: Array,
      default: []
    },

  }
}
</script>
<style scoped>
.div_map {
  position: relative;
}
.div_searchmap {
  z-index: 5000;
  position: absolute;
  top: 5px;
  left: 5px;
}
</style>

<style lang="scss" scoped >
@import "@/assets/scss/modules/visual/communityManageForm.scss";
</style>
