<template>
  <div>
    <div class="dialog-h-content scroll-h">

      <el-form ref="ref_form"
               :inline="true"
               :model="dataForm"
               :rules="dataRule"
               label-width="150px"
               class="edit_form">
        <el-form-item label="所属小区"
                      style="display: block">
          <span>{{ agencyObj.agencyName }}—{{ agencyObj.gridName }}—{{ agencyObj.label }}</span>
        </el-form-item>

        <el-form-item label="楼栋名称"
                      prop="buildingName"
                      style="display: block">
          <el-input class="edit_item_width_normal"
                    maxlength="10"
                    placeholder="请输入楼栋名称"
                    v-model="dataForm.buildingName">
          </el-input>
        </el-form-item>
        <el-form-item label="楼栋编码"
                      prop="coding"
                      style="display: block">
          <el-input class="edit_item_width_normal"
                    maxlength="50"
                    placeholder="请输入楼栋编码"
                    v-model="dataForm.coding">

          </el-input>
          <el-button style="margin-left: 10px"
                     type="text"
                     class="div-table-button--blue"
                     icon="el-icon-upload2"
                     size="small"
                     @click="handleCode">生成</el-button>

        </el-form-item>
        <el-form-item label="楼栋类型"
                      prop="type"
                      style="display: block">
          <el-radio-group v-model="buildType">

            <el-radio :label="'1'">商品房</el-radio>
            <el-radio :label="'2'">自建房</el-radio>
            <el-radio :label="'3'">别墅</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="排序"
                      prop="sort"
                      style="display: block"
                      >
          <el-input-number class="edit_item_width_normal"
                           v-model="dataForm.sort"
                           label="排序"></el-input-number>
        </el-form-item> -->
        <el-form-item label="单元数"
                      style="display: block"
                      prop="totalUnitNum">
          <el-input-number class="item_width_4"
                           v-model="dataForm.totalUnitNum"
                           :min="1"
                           :max="9999"
                           label="单元数"></el-input-number>
        </el-form-item>
        <el-form-item label="层数"
                      style="display: block"
                      prop="totalFloorNum">
          <el-input-number class="item_width_4"
                           v-model="dataForm.totalFloorNum"
                           :min="0"
                           :max="9999"
                           label="层数"></el-input-number>
        </el-form-item>
        <el-form-item label="总户数"
                      style="display: block"
                      prop="totalHouseNum">
          <el-input-number class="item_width_4"
                           v-model="dataForm.totalHouseNum"
                           :min="0"
                           :max="9999"
                           label="总户数"></el-input-number>
        </el-form-item>
        <el-form-item label="人口数"
                      style="display: block"
                      prop="realPerson">
          <el-input-number class="item_width_4"
                           v-model="dataForm.realPerson"
                           :min="0"
                           :max="9999"
                           label="人口数"></el-input-number>
        </el-form-item>
        <el-form-item label="楼长姓名"
                      prop="buildingLeaderName"
                      style="display: block">
          <el-input class="edit_item_width_normal"
                    placeholder="请输入楼长姓名"
                    v-model="dataForm.buildingLeaderName">
          </el-input>
        </el-form-item>

        <el-form-item label="楼长电话"
                      prop="buildingLeaderMobile"
                      style="display: block">
          <el-input class="edit_item_width_normal"
                    type='number'
                    placeholder="请输入楼长电话"
                    v-model="dataForm.buildingLeaderMobile">
          </el-input>
        </el-form-item>

        <el-form-item label="地图位置"
                      prop="longitude"
                      style="display: block">
          <div class="edit_item_width_normal edit_map">
            <el-select v-model="searchValue"
                       filterable
                       class="edit_item_width_normal edit_map_search"
                       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_build"
                 class="edit_div_map"></div>
          </div>
        </el-form-item>
        <el-form-item label="楼栋地址"
                      prop="coordinatePosition"
                      style="display: block">
          <!-- <span>{{ dataForm.coordinatePosition }}</span> -->
          <el-input class="edit_item_width_normal"
                    placeholder="请选择楼栋地址"
                    v-model="dataForm.coordinatePosition" />
        </el-form-item>
      </el-form>

    </div>
    <div class="div_btn">
      <el-button size="small"
                 class="diy-button--white"
                 @click="handleCancle">取 消</el-button>
      <el-button size="small"
                 type="primary"
                 class="diy-button--blue"
                 :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
let loading // 加载动画
export default {
  data () {
    return {
      formType: 'add', //表单操作类型 add新增，edit编辑，detail详情
      searchOptions: [],
      searchValue: '',
      resultList: [],
      loading: false,

      btnDisable: false,
      buildingId: '', //楼栋ID
      buildType: "1",
      dataForm: {
        agencyId: '', // 所属组织ID
        agencyName: '',
        gridId: '', //所属网格ID
        neighborHoodId: '',//所属小区id
        buildingName: '',//房屋名称
        // sort: 0,//排序
        totalUnitNum: 1,//单元数	
        totalFloorNum: 0,//层数	
        totalHouseNum: 0,//总户数	
        realPerson: 0,
        buildingLeaderName: '',//楼长姓名
        buildingLeaderMobile: '',//楼长电话
        type: '',//房屋类型
        coordinatePosition: '',
        sysCoding: '',
        coding: '',
        location: '', //坐标位置
        longitude: '', //经度
        latitude: '' //纬度
      },

      keyWords: '',
      agencyObj: {},

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

  },

  methods: {
    async initForm (type, row, agencyObj) {
      this.$refs.ref_form.resetFields();
      let { latitude, longitude } = this.$store.state.user;
      this.agencyObj = agencyObj
      this.dataForm.agencyId = agencyObj.agencyId
      this.dataForm.gridId = agencyObj.gridId
      this.dataForm.neighborHoodId = agencyObj.id

      this.formType = type
      if (row) {
        this.dataForm = JSON.parse(JSON.stringify(row))
        this.buildingId = this.dataForm.buildingId
        // this.buildType = this.dataForm.buildingTypeKey
        this.buildType = this.dataForm.type

      } else {
        this.dataForm.latitude = latitude
        this.dataForm.longitude = longitude
      }
      this.$nextTick(() => {
        if (!map) {
          this.initMap(this.dataForm.latitude, this.dataForm.longitude);
        } else {
          map.setCenter(this.dataForm.latitude, this.dataForm.longitude);
          map.setMarker(this.dataForm.latitude, this.dataForm.longitude);
        }
      })
    },

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

      })
    },
    async handleCode () {
      const { data, code, msg } = await requestPost(
        "/gov/org/houseInformation/getBuildingCoding/" + this.dataForm.neighborHoodId);
      console.log('data----', data)
      console.log('code----', code)
      console.log('msg----', msg)
      if (msg == "success" && code == 0) {
        this.dataForm.coding = data.coding
        this.dataForm.sysCoding = data.sysCoding

      }
    },
    async addBuild () {
      if (this.dataForm.buildingLeaderMobile) {
        const regPhone = /^1(3|4|5|6|7|8|9)\d{9}$/; //手机号码
        if (this.dataForm.buildingLeaderMobile && regPhone.test(this.dataForm.buildingLeaderMobile) === false) {
          this.btnDisable = false
          this.$message({
            type: 'warning',
            message: '请输入正确的楼主手机'
          })
          return false;
        }
      }

      let url = ''
      if (this.formType === 'add') {
        url = '/gov/org/building/buildingadd'
      } else {
        url = '/gov/org/building/buildingupdate'

        this.dataForm.buildingId = this.buildingId
      }

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

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

      } else {
        this.btnDisable = false
        this.$message.error(msg)
      }

    },

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

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

      map = new daiMap(
        document.getElementById("app_build"),
        { 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.dataForm.latitude = lat;
      this.dataForm.longitude = lng;
      map.setMarker(lat, lng);

      let { msg, data } = await map.getAddress(lat, lng);
      if (msg == "success") {
        this.dataForm.coordinatePosition = 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.dataForm.latitude = lonlat[1];
      this.dataForm.longitude = lonlat[0];
      this.dataForm.coordinatePosition = selPosition.address + selPosition.name
    },


    resetData () {
      this.searchValue = ''
      this.searchOptions = []
      this.resultList = []
      this.buildingId = '' //楼栋ID
      this.buildType = '1'
      this.dataForm = {
        agencyId: '', // 所属组织ID
        agencyName: '',
        gridId: '', //所属网格ID
        neighborHoodId: '',//所属小区id
        buildingName: '',//房屋名称
        // sort: 0,//排序
        totalUnitNum: 1,//单元数	
        totalFloorNum: 0,//层数	
        totalHouseNum: 0,//总户数	
        realPerson: 0,
        buildingLeaderName: '',//楼长姓名
        buildingLeaderMobile: '',//楼长电话
        type: '',//房屋类型
        location: '', //坐标位置
        longitude: '', //经度
        latitude: '', //纬度
        coding: '',
        sysCoding: '',
        coordinatePosition: ''
      }
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: '正在加载……', // 加载中需要显示的文字
        background: 'rgba(0,0,0,.7)' // 背景颜色
      })
    },
    // 结束加载动画
    endLoading () {
      // clearTimeout(timer);
      if (loading) {
        loading.close()
      }
    }
  },
  computed: {
    dataRule () {
      return {
        buildingName: [
          { required: true, message: '楼栋名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '小区名称长度在 1 到 10个字符',
            trigger: 'blur'
          }
        ],
        type: [
          { required: true, message: '楼栋类型不能为空', trigger: 'blur' }
        ],
        totalUnitNum: [
          { required: true, message: '单元数不能为空', trigger: 'blur' }
        ],
        coding: [
          { required: true, message: '楼栋编码不能为空', trigger: 'blur' }
        ]
        // totalFloorNum: [
        //   { required: true, message: '层数不能为空', trigger: 'blur' }
        // ],
        // totalHouseNum: [
        //   { required: true, message: '户数不能为空', trigger: 'blur' }
        // ],
        // longitude: [
        //   { required: true, message: '坐标不能为空', trigger: 'blur' }
        // ],
      }
    },

  },
  props: {}
}
</script>
<style lang="scss" scoped >
@import "@/assets/scss/modules/management/edit-main.scss";
</style>