<template>
  <section style="height: 100%" class="Add">
    <ai-detail>
      <ai-title slot="title" title="添加微心愿" isShowBack isShowBottomBorder @onBackClick="cancel(false)"/>
      <template slot="content">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px" label-position="right">
          <ai-card title="基础信息">
            <template #content>
              <div class="ai-form">
                <el-form-item label="姓名" prop="name">
                  <el-input
                    size="small"
                    v-model="form.name"
                    placeholder="请输入..."
                    clearabel
                    :maxLength="60"
                  ></el-input>
                </el-form-item>
                <el-form-item label="联系方式" prop="phone">
                  <el-input
                      size="small"
                      v-model="form.phone"
                      placeholder="请输入..."
                      clearabel
                      :maxLength="11"
                  ></el-input>
                </el-form-item>
                <el-form-item label="事件类型" prop="groupId">
                  <ai-select
                      v-model="form.groupId"
                      placeholder="请选择"
                      :selectList="dictList"
                  ></ai-select>
                </el-form-item>
                <el-form-item label="事件描述" prop="content" style="width: 100%">
                  <el-input
                    type="textarea"
                    :rows="4"
                    v-model="form.content"
                    placeholder="请输入..."
                    clearabel
                    :maxLength="60"
                  ></el-input>
                </el-form-item>
                <el-form-item label="所属地区" prop="areaId" style="width: 100%">
                  <ai-area-select
                    clearable
                    :instance="instance"
                    v-model="form.areaId"
                    @fullname="v => form.areaName = v"
                    always-show
                    area-level="5"
                    :disabledLevel="disabledLevel"
                  />
                </el-form-item>
                <el-form-item label="上报位置" prop="lat">
                  <el-button @click="showMap = true">地图标绘</el-button>
                </el-form-item>
                <el-form-item label="现场照片" style="width: 100%;">
                  <ai-uploader
                      :instance="instance"
                      isShowTip
                      v-model="form.files"
                      :limit="9">
                  </ai-uploader>
                </el-form-item>
              </div>
            </template>
          </ai-card>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="cancel(false)">取消</el-button>
        <el-button type="primary" @click="confirm">提交</el-button>
      </template>
    </ai-detail>
    <ai-dialog title="地图" :visible.sync="showMap" @opened="initMap" width="800px" class="mapDialog" @onConfirm="selectMap">
      <div id="map" style="height:400px;"></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" style="width:100px;"></el-input>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input disabled size="small" v-model="placeDetail.lat" style="width:100px;"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input disabled size="small" v-model="placeDetail.address" style="width:300px;"></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",
  props: {
    instance: Function,
    dict: Object,
    selected: Object,
  },
  computed: {
    ...mapState(["user"]),
  },
  data() {
    return {
      disabledLevel: 0,
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
        phone: [{ required: true, message: '请输入联系方式', trigger: 'change' }],
        groupId: [{ required: true, message: '请选择事件类型', trigger: 'change' }],
        content: [{ required: true, message: '请输入事件描述', trigger: 'change' }],
        areaId: [{ required: true, message: '请选择所属地区', trigger: 'change' },
          {
            validator: (r, v, cb) => {
              if (/.+0{3}$/.test(v)) {
                cb("所属地区必须选到村级")
              } else cb()
            }, trigger: "blur"
          }
        ],
        lat: [{ required: true, message: '请进行地图标绘', trigger: 'change' }],
      },
      form: {
        name: '',
        phone: '',
        groupId: '',
        content: '',
        areaId: '',
        areaName: '',
        lat: '',
        lng: '',
        address: '',
        files: []
      },
      dictList: [],
      showMap: false,
      map: null,
      placeSearch: null,
      placeDetail: {
        lng: '',
        lat: '',
        address: ''
      },
      searchPlace: '',
    };
  },
  created() {
    this.disabledLevel = this.user.info.areaList.length
    this.form.areaId = this.user.info.areaId
    this.getDict()
  },
  methods: {
    selectMap() {
      this.form.lng = this.placeDetail.lng
      this.form.lat = this.placeDetail.lat
      this.form.address = this.placeDetail.address
      this.showMap = false
    },
    initMap() {
      AMapLoader.load({
        key: '54a02a43d9828a8f9cd4f26fe281e74e',
        version: '2.0',
        plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geocoder'],
      }).then((AMap) => {
        this.map = new AMap.Map('map', {
          resizeEnable: true,
          zooms: [6, 20],
          zoom: 11,
          center:[107.11059, 31.56618],
        })
        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()
      }
    },
    getDict() {
      this.instance.post(`/app/appclapeventgrouppingchang/list?current=1&size=100000`).then(res => {
        if (res.code == 0) {
          this.dictList = res.data.records.map(v => {
            return {
              dictValue: v.id,
              dictName: v.groupName
            }
          })
        }
      })
    },
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.instance.post(`/app/appclapeventinfopingchang/addOrUpdate`, {
            ...this.form, 
            groupName: this.dictList.filter(v => v.dictValue === this.form.groupId)[0].dictName,
          }).then((res) => {
            if (res.code == 0) {
              this.$message.success('新增微心愿成功')
              setTimeout(() => {
                this.cancel(true)
              }, 600);
            }
          });
        }
      });
    },
    cancel(isRefresh) {
      this.$emit('change', {
        type: 'list',
        isRefresh: !!isRefresh
      })
    },
  }
};
</script>
<style lang="scss" scoped>
  .Add {
    .ai-form {
      display: flex;
    }
    .text {
      display: inline-block;
      padding-left: 8px;
      color: #999;
    }
    ::v-deep .el-range-separator {
      width: 28px!important;
    }
    ::v-deep .el-date-editor {
      width: 100%;
    }
  }
</style>