<template>
  <section style="height: 100%" class="AppBuildManage">
    <ai-detail class="Add">
      <!-- 返回按钮 -->
      <template #title>
        <ai-title :title="isEdit ? '编辑楼栋信息' : '添加楼栋'" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
      </template>

      <template #content>
        <el-form :model="formData" :rules="formRules" ref="ruleForm" label-width="150px" label-suffix="：" align-items="center">
          <!-- 小区名称 -->
          <ai-bar title="基础信息"></ai-bar>
          <el-form-item label="小区名称" prop="communityName" class="line" ref="communityNameContent">
            <!-- 选择小区 -->
            <ai-select v-if="instance" :instance="instance" v-model="formData.communityId" action="/app/appcommunityinfo/listAll" :prop="{ label: 'communityName' }"></ai-select>
          </el-form-item>

          <div class="flex">
            <!-- 楼栋号 -->
            <el-form-item label="楼栋号" prop="buildingNumber" :rules="[{ required: true, message: '请输入楼栋号', trigger: 'blur' }]">
              <el-input size="small" v-model="formData.buildingNumber" placeholder="请输入" clearable :disabled="isEdit" />
            </el-form-item>

            <!-- 单元数 -->
            <el-form-item label="单元数" prop="unitNumber">
              <el-input size="small" v-model.number="formData.unitNumber" placeholder="请输入" clearable :disabled="isEdit" />
            </el-form-item>

            <!-- 起始计数层数 -->
            <el-form-item label="起始计数层数" prop="layerStart">
              <el-input size="small" v-model.number="formData.layerStart" placeholder="请输入" clearable :disabled="isEdit"></el-input>
            </el-form-item>

            <!-- 最高层数 -->
            <el-form-item label="最高层数" prop="layerNumber">
              <el-input size="small" v-model.number="formData.layerNumber" placeholder="请输入" clearable :disabled="isEdit"></el-input>
            </el-form-item>

            <!-- 起始计数户数 -->
            <el-form-item label="起始计数户数" prop="householdStart">
              <el-input size="small" v-model.number="formData.householdStart" placeholder="请输入" clearable :disabled="isEdit"></el-input>
            </el-form-item>

            <!-- 每层户数 -->
            <el-form-item label="每层户数" prop="householdNumber">
              <el-input size="small" v-model.number="formData.householdNumber" placeholder="请输入" clearable :disabled="isEdit"></el-input>
            </el-form-item>

            <!-- 楼栋长姓名 -->
            <el-form-item label="楼栋长姓名" prop="managerName">
              <el-input size="small" v-model="formData.managerName" placeholder="请输入" clearable></el-input>
            </el-form-item>

            <!-- 楼栋长联系方式 -->
            <el-form-item label="楼栋长联系方式" prop="managerPhone">
              <el-input size="small" v-model.number="formData.managerPhone" placeholder="请输入" clearable></el-input>
            </el-form-item>

            <!-- 房屋类别 -->
            <el-form-item label="房屋类别" prop="buildingType" class="buildingTypes">
              <el-radio-group v-model="formData.buildingType">
                <el-radio label="0">单元（公寓）楼</el-radio>
                <el-radio label="1">筒子楼</el-radio>
                <el-radio label="2">别墅</el-radio>

                <el-radio label="3">自建楼</el-radio>
                <el-radio label="4">平房</el-radio>
                <el-radio label="5">高层公共建筑</el-radio>

                <el-radio label="6">商住两用</el-radio>
                <el-radio label="7">其它</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 楼栋经度坐标 -->
            <el-form-item label="楼栋经度坐标" prop="lng">
              <el-input size="small" v-model="formData.lng" placeholder="请输入" clearable></el-input>
            </el-form-item>

            <!-- 楼栋纬度坐标 -->
            <el-form-item label="楼栋纬度坐标" prop="lat">
              <el-input size="small" v-model="formData.lat" placeholder="请输入" clearable></el-input>
            </el-form-item>

            <!-- 地图位置 -->
            <el-form-item label="地图位置" prop="lat">
              <el-button @click="showMap = true">地图标绘</el-button>
            </el-form-item>
          </div>
        </el-form>
      </template>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="confirm()">提交</el-button>
      </template>
    </ai-detail>
    <ai-dialog title="地图" :visible.sync="showMap" @opened="getCorpLocation" width="800px" class="mapDialog" @onConfirm="selectMap">
      <div id="map"></div>
      <el-form label-width="80px" style="padding: 10px 20px 0 20px;">
        <el-row type="flex" justify="space-between">
          <el-form-item label="经度">
            <el-input disabled size="small" v-model="placeDetail.lng"></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input disabled size="small" v-model="placeDetail.lat"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <el-input id="searchPlaceInput" size="medium" class="searchPlaceInput" clearable v-model="searchPlace" autocomplete="on" @change="placeSearch.search(searchPlace)" placeholder="请输入关键字">
        <el-button type="primary" slot="append" @click="placeSearch.search(searchPlace)">搜索</el-button>
      </el-input>
      <div id="searchPlaceOutput" />
    </ai-dialog>
  </section>
</template>

<script>
import { mapState } from 'vuex'
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  name: 'Add',
  components: {},
  props: {
    dict: Object,
    params: Object,
    instance: Function,
  },
  data() {
    return {
      formData: {
        communityName: '',
        buildingNumber: '',
        unitNumber: '',
        layerStart: '1',
        layerNumber: '',
        householdStart: '1',
        householdNumber: '',
        managerName: '',
        managerPhone: '',
        lng: '',
        lat: '',
        id: '', // 小区编号
        buildingType: '0',
        communityId: '',
      },
      formRules: {
        unitNumber: [
          { required: true, message: '请输入单元数', trigger: 'change' },
          {
            validator: (r, v, cb) => (!v || /^[1-9]\d*|0$/g.test(v) ? cb() : cb('请输入正整数')),
          },
        ],
        layerStart: [
          { required: true, message: '请输入起始计数层数', trigger: 'change' },
          {
            validator: (r, v, cb) => (!v || /^[1-9]\d*|0$/g.test(v) ? cb() : cb('请输入正整数')),
          },
        ],

        layerNumber: [
          { required: true, message: '请输入最高层数', trigger: 'change' },
          {
            validator: (r, v, cb) => (!v || /^[1-9]\d*|0$/g.test(v) ? cb() : cb('请输入正整数')),
          },
        ],
        householdStart: [
          { required: true, message: '请输入起始计数户数', trigger: 'change' },
          {
            validator: (r, v, cb) => (!v || /^[1-9]\d*|0$/g.test(v) ? cb() : cb('请输入正整数')),
          },
        ],

        householdNumber: [
          { required: true, message: '请输入最高层数', trigger: 'change' },
          {
            validator: (r, v, cb) => (!v || /^[1-9]\d*|0$/g.test(v) ? cb() : cb('请输入正整数')),
          },
        ],
      },
      plot: [],
      dialogVisible: false,
      treeData: [],
      map: null,
      placeDetail: {
        lng: '',
        lat: '',
      },
      showMap: false,
      searchPlace: '',
    }
  },
  computed: {
    ...mapState(['user']),

    isEdit() {
      return !!this.params.id
    },
  },
  created() {
    this.formData.communityId = this.params.communityId
    this.getListinfo()
  },
  methods: {
    selectMap() {
      this.formData.lng = this.placeDetail.lng
      this.formData.lat = this.placeDetail.lat
      this.showMap = false
    },
    getCorpLocation() {
      this.instance.post('/app/appdvcpconfig/getCorpLocation').then((res) => {
        if (res.code == 0) {
          this.initMap(res.data)
        }
      })
    },

    initMap({ lng, lat }) {
      AMapLoader.load({
        key: '54a02a43d9828a8f9cd4f26fe281e74e',
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],
      }).then((AMap) => {
        this.placeDetail.lng = this.formData.lng
        this.placeDetail.lat = this.formData.lat
        this.map = new AMap.Map('map', {
          resizeEnable: true,
          zooms: [6, 20],
          center: [lng, lat],
          zoom: 11,
        })
        this.placeSearch = new AMap.PlaceSearch({ map: this.map })
        new AMap.AutoComplete({
          input: 'searchPlaceInput',
          output: 'searchPlaceOutput',
        }).on('select', (e) => {
          if (e?.poi) {
            this.placeSearch.setCity(e.poi.adcode)
            this.movePosition(e.poi.location)
          }
        })
        this.map.on('click', (e) => {
          new AMap.Geocoder().getAddress(e.lnglat, (sta, res) => {
            if (res?.regeocode) {
              this.placeDetail = {
                lng: e.lnglat?.lng,
                lat: e.lnglat?.lat,
                address: res.regeocode.formattedAddress,
              }
            }
          })
          this.movePosition(e.lnglat)
        })
      })
    },

    movePosition(center) {
      if (this.map) {
        this.map.clearMap()
        this.map.panTo(center)
        this.map.add([
          new AMap.Marker({
            position: center,
            clickable: true,
          }),
        ])
        this.map.setFitView()
      }
    },

    getListinfo() {
      return this.instance
        .post('/app/appcommunitybuildinginfo/queryDetailById', null, {
          params: {
            id: this.params.id,
          },
        })
        .then((res) => {
          if (res.data) {
            this.formData = res.data
          }
        })
    },

    confirm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.instance
            .post(`/app/appcommunitybuildinginfo/addOrUpdate`, {
              ...this.formData,
            })
            .then((res) => {
              if (res.code == 0) {
                this.$message.success('提交成功')
                setTimeout(() => {
                  this.cancel(true)
                }, 1000)
              }
            })
        }
      })
    },

    // 返回按钮
    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh,
      })
    },
  },
  watch: {
    communityNameContent: {
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.AppBuildManage {
  ::v-deep .amap-logo {
    display: none!important;
  }
  ::v-deep .amap-copyright {
    display: none!important;
  }
}
.Add {
  height: 100%;
  .ai-detail__title {
    background-color: #fff;
  }
  .ai-detail__content {
    .ai-detail__content--wrapper {
      .el-form {
        background-color: #fff;
        padding: 0 60px;
        .flex {
          display: flex;
          flex-wrap: wrap;
          justify-content: space-between;
          .el-form-item {
            width: 48%;
          }
          .buildingTypes {
            width: 100%;
          }
        }
      }
    }
  }
}

::v-deep .mapDialog {
  .el-dialog__body {
    padding: 0;

    .ai-dialog__content {
      padding: 0;
    }

    .ai-dialog__content--wrapper {
      padding: 0 !important;
      position: relative;
    }

    #map {
      width: 100%;
      height: 420px;
    }

    .searchPlaceInput {
      position: absolute;
      width: 250px;
      top: 30px;
      left: 25px;
    }

    #searchPlaceOutput {
      position: absolute;
      width: 250px;
      left: 25px;
      height: initial;
      top: 80px;
      background: white;
      z-index: 250;
      max-height: 300px;
      overflow-y: auto;

      .auto-item {
        text-align: left;
        font-size: 14px;
        padding: 8px;
        box-sizing: border-box;
      }
    }
  }
}
</style>
