<template>
  <section class="activitiesAdd">
    <ai-detail v-show="id && !isEdit">
      <template slot="title">
        <ai-title title="活动详情" isShowBack isShowBottomBorder @onBackClick="cancel(false)"></ai-title>
      </template>
      <template slot="content">
        <ai-card :title="info.title">
          <template #right>
            <span style="color:#2266FF;cursor: pointer;font-size: 12px;" class="iconfont iconEdit" v-if="isEdit==false && info.status==0" @click="update">修改</span>
          </template>
          <template #content v-if="isEdit == false">
            <ai-wrapper>
              <ai-info-item label="活动名称" :value="info.title"></ai-info-item>
              <ai-info-item label="创建人" :value="info.createUserName"></ai-info-item>
              <ai-info-item label="活动说明" isLine :value="info.detail"></ai-info-item>
              <ai-info-item label="活动地点" :value="info.address"></ai-info-item>
              <ai-info-item label="标绘地址" isLine><div id="mapDetail"></div></ai-info-item>
              <ai-info-item label="活动状态">
                {{ dict.getLabel('tfx_activityStatus',info.status) }}
              </ai-info-item>
              <ai-info-item label="打卡范围">{{ info.clockRange }}米</ai-info-item>
              <ai-info-item label="进场打卡时间">{{ info.intoBegintime }}至{{ info.intoEndtime}}</ai-info-item>
              <ai-info-item label="进场得积分">{{ info.intoIntegral }}分</ai-info-item>
              <ai-info-item label="离场打卡时间">{{ info.exitBegintime }}至{{ info.exitEndtime}}</ai-info-item>
              <ai-info-item label="离场得积分">{{ info.exitIntegral }}</ai-info-item>
            </ai-wrapper>
          </template>
        </ai-card>
      </template>
    </ai-detail>
    <ai-detail v-show="!id || isEdit==true">
      <ai-title slot="title" :title="id? '编辑活动':'创建活动'" isShowBottomBorder isShowBack @onBackClick="cancel(true)"/>
      <template slot="content">
        <ai-card title="基本信息">
          <template #content>
            <div class="add-form">
              <el-form ref="form" :model="form" :rules="formRules" size="small"  label-width="150px">

                <el-form-item label="活动名称" prop="title">
                  <el-input v-model="form.title" placeholder="请输入" show-word-limit maxlength="64"></el-input>
                </el-form-item>

                <el-form-item label="活动说明">
                  <el-input type="textarea" :rows="5" v-model="form.detail" placeholder="请输入" show-word-limit maxlength="500"></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 label="标绘地址">
                  <el-input v-model="form.address" disabled ></el-input>
                </el-form-item>

                <el-form-item label="打卡范围" prop="clockRange" style="width: 550px">
                  <el-input type="number" v-model="form.clockRange" placeholder="请输入" >
                    <template slot="append">米</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="进场打卡时间" prop="intoTime">
                  <el-date-picker v-model="form.intoTime" type="datetimerange" start-placeholder="开始日期" :picker-options="timeOption"
                  end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" ></el-date-picker>
                </el-form-item>

                <el-form-item label="进场得积分" prop="intoIntegral" style="width: 550px">
                  <el-input v-model="form.intoIntegral" type="number" placeholder="请输入" >
                    <template slot="append">积分</template>
                  </el-input>
                </el-form-item>

                <el-form-item label="离场打卡时间" prop="exitTime">
                  <!-- { start: formData.startTime, minTime: formData.startTime} -->
                  <el-date-picker v-model="form.exitTime" type="datetimerange" start-placeholder="开始日期" :picker-options="timeOption"
                  end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
                </el-form-item>

                <el-form-item label="离场得积分" prop="exitIntegral" style="width: 550px">
                  <el-input v-model="form.exitIntegral" type="number" placeholder="请输入" >
                    <template slot="append">积分</template>
                  </el-input>
                </el-form-item>

              </el-form>
            </div>
          </template>
        </ai-card>
      </template>
      <template #footer>
        <el-button class="delete-btn footer-btn" @click="cancel(false)">取消</el-button>
        <el-button class="footer-btn" 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"></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: "activitiesAdd",
  props: {
    instance: Function,
    dict: Object,
    params: Object,
  },

  data() {
    var validLocation =  (rule, value, callback) => {
      if(!this.form.lat || !this.form.lng) {
        return callback(new Error('请标绘地理位置'))
      } else {
        callback()
      }
    }
    return {
      form: {
        title: '',
        detail: '',
        lng: '',
        lat: '',
        address: '',
        clockRange: '',
        intoTime: [],
        intoBegintime: '',
        intoEndtime: '',
        intoIntegral: '',
        exitTime: [],
        exitBegintime: '',
        exitEndtime: '',
        exitIntegral: '',        
      },
      formRules: {
        title: [{required: true, message: "请输入活动名称", trigger: "blur"}],
        location: [{required: true, validator: validLocation, trigger: "blur"}],
        clockRange: [{required: true, message: "请输入打卡范围", trigger: "blur"}],
        intoTime: [{required: true, message: "请选择进场打卡时间", trigger: "blur"}],
        intoIntegral: [{required: true, message: "请输入进场得积分", trigger: "blur"}],
        exitTime: [{required: true, message: "请选择离场打卡时间", trigger: "blur"}],
        exitIntegral:  [{required: true, message: "请输入离场得积分", trigger: "blur"}],
      },
      id: '',
      isEdit: false,
      info: {},
      mapDetail: null,
      map: null,
      placeSearch: null,
      placeDetail: {
        lng: '',
        lat: '',
        address: ''
      },
      showMap: false,
      searchPlace: '',
      timeOption: {
        disabledDate(date) {
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
    }
  },
  created() {
    this.$dict.load('tfx_activityStatus')
    if(this.params && this.params.id) {
      this.id = this.params.id
      this.getDetail()
      setTimeout(() => {
        this.getMap(this.info.lng,this.info.lat,this.info.address)
      },500)
    }
  },
  watch: {
    'form.intoTime': {
      handler(val) {
        if(val) {
          this.form.intoBegintime = val[0]
          this.form.intoEndtime = val[1]
        }
      }
    },
    'form.exitTime': {
      handler(val) {
        if(val) {
          this.form.exitBegintime = val[0]
          this.form.exitEndtime = val[1]
        }
      }
    }
  },
  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,
        })
        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()
      }
    },
    cancel (isRefresh) {
      this.$emit('change', {
        type: 'activitiesList',
        isRefresh: !!isRefresh
      })
    },

    getMap(lng,lat,address) {
      this.mapDetail = new AMap.Map(document.getElementById("mapDetail"), {
        resizeEnable: true,
        zooms: [6, 20],
        zoom: 11,
      })
      var marker = new AMap.Marker({
        position: new AMap.LngLat(lng,lat),
        title: address
      })
      this.mapDetail.add(marker);
    },

    update() {
      this.isEdit = true
      this.getDetail()
    },

    getDetail() {
      this.instance.post(`api/appactivityinfo/queryDetailById`,null, {
        params: {id:this.id}
      }).then((res) => {
        if(res?.data) {
          this.form = res.data
          this.form.intoTime = [res.data.intoBegintime,res.data.intoEndtime]
          this.form.exitTime = [res.data.exitBegintime,res.data.exitEndtime]
          this.info = res.data
          this.placeDetail.lng = res.data.lng
          this.placeDetail.lat = res.data.lat
        }
      })
    },
    selectCandidate(v) {
      this.form.candidateUsers = v
    },
    selectVote(e) {
      this.form.voteUsers = e
    },
    
    handleAreaSelect(v) {
      this.form.areaName = v?.[0]?.label
    },

    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if(new Date(this.form.intoBegintime).getTime() <= Date.now()){
            return this.$message.error('进场打卡开始时间不能小于当前时间')
          }
          let intoEnd = new Date(this.form.intoEndtime).getTime()
          let exitBegin = new Date(this.form.exitBegintime).getTime()
          if(exitBegin <= intoEnd) {
            return this.$message.error('离场的开始时间不能小于且等于进场的结束时间')
          }
          this.instance.post(`api/appactivityinfo/addOrUpdate`,{
            ...this.form
          }).then(res => {
            if(res.code == 0) {
              this.$message.success(this.id ? '编辑成功' : '新增成功')
              this.cancel(true)
            }
          }).catch(err => {
            console.log(err);
          })
        }
      })
    },
  },
}
</script>

<style lang="scss" scope>
.activitiesAdd {
  height: 100%;

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

  ::v-deep .el-date-editor .el-input {
    width: 100%;
  }

  .tips {
    width: 100%;
    border: 1px solid #f82;
    background-color: #fff3e9;
    color: #f82;
    padding: 8px 16px;
    box-sizing: border-box;
    border-radius: 4px;
    margin-bottom: 32px;
    font-size: 13px;
  }

  .amap-container {
    height: 380px;
  }
}

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