<template>
  <section class="addResource">
    <ai-detail>
      <template #title>
        <ai-title title="添加社会资源" isShowBack isShowBottomBorder @onBackClick="cancel"></ai-title>
      </template>

      <template slot="content">
        <ai-card>
          <template #content>
            <el-form ref="form" class="ai-form" :model="form" :rules="rules" label-width="110px" label-position="right">

              <el-form-item label="资源分类" style="width: 100%;" prop="categoryId">
                <ai-select v-model="form.categoryId" :selectList="categoryList"/>
              </el-form-item>

              <el-form-item style="width: 100%" label="资源名称" prop="resourceName">
                <el-input size="small" placeholder="请输入资源名称" show-word-limit v-model="form.resourceName" :maxlength="20"></el-input>
              </el-form-item>

              <el-form-item style="width: 100%" label="地区" prop="areaId">
                <ai-area-get v-model="form.areaId" :instance="instance" @select="handleAreaSelect" :root="areaId"/>
              </el-form-item>

              <el-form-item style="width: 100%" label="地址" prop="address">
                <el-input size="small" placeholder="请输入地址" v-model="form.address" show-word-limit maxlength="50"></el-input>
              </el-form-item>

              <el-form-item style="width: 100%" label="地理位置" prop="location">
                <el-button @click="showMap = true">地图标绘</el-button>
              </el-form-item>

              <el-form-item style="width: 100%" label="资源信息">
                <el-input size="small" type="textarea" :rows="5" placeholder="请输入资源信息" show-word-limit v-model="form.information" :maxlength="500"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </ai-card>
      </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 AMapLoader from '@amap/amap-jsapi-loader'
export default {
  name: 'addResource',
  props: {
    instance: Function,
    dict: Object,
    areaId: String,
    permissions: Function,
  },
  data() {
    var validLocation =  (rule, value, callback) => {
      if(!this.form.lat || !this.form.lng) {
        return callback(new Error('请标绘地理位置'))
      } else {
        callback()
      }
    }
    return {
      form: {
        categoryName: '',
        categoryId: '',
        resourceName: '',
        areaId: '',
        areaName: '',
        address: '',
        lng: '',  // 经度
        lat: '',  // 纬度
        information: '',
      },
      categoryList: [],
      searchPlace: '',
      placeDetail: {
        lng: '',  // 经度
        lat: '',  // 纬度
      },
      map: null,
      placeDetail: {
        lng: '',
        lat: '',
      },
      showMap: false,
      searchPlace: '',
      rules: {
        categoryId: [{ required: true, message: '请选择资源分类', trigger: 'blur' }],
        resourceName: [{ required: true, message: '请输入资源名称', trigger: 'blur' }],
        areaId: [{ required: true, message: '选择地区', trigger: 'change' }],
        address: [{ required: true, message: '请输入地址', trigger: 'change' }],
        location: [{ required: true, validator: validLocation, trigger: 'change' }],
      },
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    cancel() {
      // currentPage: resourceManagement
      this.$router.push({hash: "#AppCommunityResource", query: {}})
    },
    getCategoryList() {
      this.instance.post(`/app/appresourcecategory/list`,null,{
        params: {
          current: 1,
          size: 3000,
        }
      }).then(res=> {
        if(res?.data) {
          this.categoryList = res.data.records.map(item=> {
            return {
              dictName: item.categoryName,
              dictValue: item.id
            }
          })
        }
      })
    },
    handleAreaSelect(v) {
      if(v.length) {
        this.form.areaName = v[0]?.label
      }
    },
    selectMap() {
      this.form.lng = this.placeDetail.lng
      this.form.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: 'b553334ba34f7ac3cd09df9bc8b539dc',
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],
      }).then((AMap) => {
        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()
      }
    },


    confirm() {
      this.$refs.form.validate((valid) => {
        if(valid) {
          this.instance.post(`/app/appresourceinfo/addOrUpdate`, {
            ...this.form
          }).then(res => {
            if (res.code == 0) {
              this.$message.success('新增成功')
              this.cancel()
            }
          })
        }
      })
      
    },
  },
}
</script>

<style lang="scss" scoped>
.addResource {

  ::v-deep .amap-logo {
    display: none!important;
  }
  ::v-deep .amap-copyright {
    display: none!important;
  }

  ::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>