<template>
  <div>
    <div class="dialog-h-content scroll-h"
      style="display: flex; flex-direction: row; justify-content:space-between; padding: 20px;">
      <div style="width: 48%; ">
        <el-form ref="ref_form" :model="formData" class="form" label-width="90px" :rules="rules">
          <el-form-item label="主办方" prop="agencyId" required>
            {{ formData.agencyName}}
          </el-form-item>
          <el-form-item label="活动标题" prop="title" required>
            <!-- <el-input type="textarea" style="width: 300px;" placeholder="请输入活动标题，不超过50子" v-model="formData.title" maxlength="50"
                show-word-limit>
              </el-input> -->
            {{formData.title }}
          </el-form-item>
          <el-form-item label="活动详情" prop="content" style="display: block" required>
            <div>
              <div class="span1" v-html="formatContent(formData.content)"></div>
            </div>
          </el-form-item>

          <el-form-item label="照片" prop="activityImgs" required>
            <div>
              <!-- <el-upload :headers="$getElUploadHeaders()" class="avatar-uploader" :action="uploadUrl"
                :show-file-list="true" :data="{ customerId: customerId }" :file-list="formData.activityImgs"
                :on-preview="handleImgPreview" :on-success="handleImgSuccess" :on-remove="handleImgRemove"
                :on-exceed="handleImgExceed" :before-upload="beforeImgUpload" list-type="picture-card" :limit="1">
                <i class="el-icon-plus avatar-uploader-icon" style="width: 50px;height: 50px;"></i> </el-upload> -->
                <el-image :src="formData.imgs"></el-image>
            </div>
          </el-form-item>

          <el-form-item label="活动时间" prop="strTime" required>
            <!-- <el-date-picker v-model="formData.strTime" type="datetime" placeholder="开始时间" format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss" style="width: 150px;">
              </el-date-picker>至 <el-date-picker v-model="formData.endTime" type="datetime" placeholder="结束时间"
                format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"style="width: 150px;"@change="actcontrolTime">
              </el-date-picker> -->
            {{ formData.strTime }} <span style="margin: 0 10px">至</span>{{ formData.endTime }}
          </el-form-item>
          <el-form-item label="活动范围" prop="strTime" required>
            {{ formData.districtName }}
          </el-form-item>
          <el-form-item label="活动名额" prop="points" required>
            <div style="display: flex; flex-direction: column;">
              <el-input-number disabled="false" v-model.trim="formData.quota" label="描述文字" v-if="formData.quota!=0"
                type="number"></el-input-number>
              <span v-if="formData.quota==0">不限名额</span>
            </div>
          </el-form-item>
          <el-form-item label="活动类型" prop="type" required>
            {{ formData.typeName }}
          </el-form-item>

          <el-form-item label="活动地址" prop="address" required>
            {{ formData.address }}
          </el-form-item>
          <el-form-item label="活动对象" prop="activityObject" required>
            <template slot-scope="scope">{{ scope.row.strTime }}至{{ scope.row.endTime}}
            </template>
          </el-form-item>
          <el-form-item label=" 联系人" prop="linkman" required>
            {{ formData.linkman }}
          </el-form-item>
          <el-form-item label=" 联系电话" prop="linkMobile" required>
            {{ formData.linkMobile }}
          </el-form-item>

        </el-form>
      </div>
      <div style="width: 48%;">
        <el-form ref="ref_form" :inline="true" :model="formData" class="form" label-width="115px">
          <div>
            <el-form-item label="活动积分" prop="integral">
              <el-input-number disabled="false" v-model="formData.points" :min="1" :max="10"
                label="描述文字"></el-input-number>
            </el-form-item>
            <el-form-item label="服务时长" prop="serviceTime" required>
              <div style="display: flex; justify-items:center; align-items: center;">
                <el-input-number disabled="false"  v-model.trim="formData.serviceTime" :min="1" label="描述文字"
                  type="number"></el-input-number>
              </div>
            </el-form-item>
   
            <el-form-item label="报名条件" prop="conditions" style="display: block">
              {{formData.conditions}}

            </el-form-item>
            <el-form-item label="所属项目" prop="typeId" required>
              {{ formData.projectTitle}}
    
            </el-form-item>
            <el-form-item label="签到时间" prop="signInTime" required>
              {{formData.signInTime}}至 {{formData.signOutTime}}
            </el-form-item>
            <el-form-item label="报名截止时间" prop="deadline" required>
              {{ formData.deadline }}
            </el-form-item>

            <el-form-item v-if="formType!=='records'" label="上线" style="display: block" prop="peopleCount">
              <el-switch disabled="false" v-model="formData.online" :active-value='1' :inactive-value='0'
                @change="handleSwitchChange"></el-switch>
            </el-form-item>
          </div>
          <div v-if="formData.sponsors" v-for="(item, index) in formData.sponsors" :label="index" :key="item.name"
            :prop=index>
            <el-form-item label="赞助单位" prop="sponsors" style="margin-bottom:20px" label-width="110px">
              {{ item.name }}
            </el-form-item>
            <el-form-item label="联系电话" prop="sponsors">
              {{item.phone}}
            </el-form-item>
          </div>
          <el-form-item label="活动地点" prop="searchValue">
            <div style="width: 300px">
              <!-- <el-select v-model.trim="searchValue" filterable style="width: 300px" remote :reserve-keyword="true"
                placeholder="请输入关键词" :remote-method="remoteMethod" :loading="loading">
                <el-option v-for="(item, index) in searchOptions" @click.native="handleClickKey(index)"
                  style="width: 400px;" :key="item.value || index" :label="item.label" :value="item.value">
                </el-option>
              </el-select> -->
              {{ searchValue }}
            </div>
            <div v-if="true" id="app_activity" class="div_map"></div>
          </el-form-item>
        </el-form>
      </div>
    </div>

  </div>
</template>
  <script>
  import { Loading } from 'element-ui' // 引入Loading服务
  import { mapGetters } from 'vuex'
  import { requestPost, requestGet } from '@/js/dai/request'
  import fileList from '@/views/components/fileList'
  import Tinymce from '@c/tinymce2/index.vue'
  import UploadImage from '@/views/modules/plugins/rent/upload-image.vue'
  import daiMap from "@/utils/dai-map";
  var map
  var search
  var markers
  var infoWindowList
  var geocoder // 新建一个正逆地址解析类
  export default {
    data () {
      return {
        loading: false,
        searchOptions: [],
        orgOptionProps: {
          value: 'agencyId',
          label: 'agencyName',
          children: 'subAgencyList',
          emitPath: false,
          multiple: false,
          checkStrictly: true
      },
      customerId: localStorage.getItem('customerId'),
      uploadUrl: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadqrcodeV2',
        orgOptions:[],
        resultList: [],
        btnDisable: false,    
        searchValue:"",
        formData: {
          title:"",
      agencyId:"",
      projectId:"",
      content:"",
      points:10,
      imgs:"",
      deadline:"",
      strTime:"",
      endTime:"",
      signInTime:"",
      signOutTime:"",
      quota:'',
      conditions:"",
      notQuota:'',
      linkman:"",
      linkMobile:"",
      address:"",
      longitude: this.$store.state.user.longitude, //经度
      latitude: this.$store.state.user.latitude,//纬度
      type:"",
      online:0,
      sponsors:[
      ],
     
        },
        typeList:[],//活动类型
        ServicetypeListName:[],
        activityImgs:[],//图片

        uploadUlr: window.SITE_CONFIG['apiURL'] + '/oss/file/uploadvariedfile',
          tableDate:{},
          rules: {
            linkMobile: [
            { required: true, message: '联系电话不能为空', trigger: 'blur' },
            { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
          ],
          title: [
            { required: true, message: '活动标题不能为空', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '活动详情不能为空', trigger: 'blur' },
          ],
          
          type: [
            { required: true, message: '活动类型不能为空', trigger: 'blur' },
          ],
          linkman: [
            { required: true, message: '联系人不能为空', trigger: 'blur' },
          ],
          signInTime: [
            { required: true, message: '签到时间不能为空', trigger: 'blur' },
          ],
          deadline: [
            { required: true, message: '活动报名时间不能为空', trigger: 'blur' },
          ],
        }
      }
    },
    watch: {
      'formData.notQuota'(newValue) {
        console.log(newValue,'newvalue');
        // 当 notQuota 变为 '0' 时，清空 quota
        if (newValue === '0') {
          this.formData.quota = '';
        }
        console.log( this.formData.quota);
        
      }
    },
    components: { fileList,Tinymce,UploadImage},
    async mounted () {
      this.volunteerservicetype()
      this.getTableData1()
      this.getTableData()

      // this.startLoading()
      // await this.loadInfo()
      // this.endLoading()
      console.log(this.list,"dsfslfjl");
      this.getOrgTreeList()
  
    },
  
    methods: {
        //查询所属项目
        async getTableData1() {
          const url = "/voluntary/project/admin/list";
          let params={
            projectTitle:this.formData.projectTitle,
            pageSize:9999,
            pageNo:1,
            onlineStatus:1
            // ...this.formData
          }
          const { data, code, msg } = await requestGet(url,params);
          if (code === 0) {
            console.log("列表请求成功！！！！！！！！！！！！！！");
            this.typeList = data
          } else {
          }
        },
            // 获取志愿组织服务类型
            async   volunteerservicetype() {
            console.log("skldfjlsdfjlksjfd");
            const url = "/sys/dict/data/dictlist"
            let params = {
                dictType: 'voluntary_project_service_class'
            }
            await requestPost(url, params).then(res=>{
                console.log(res,"res");
                this.ServicetypeListName=res.data
            })
            // console.log(data,"sdlkfjlsdkf");
            
            // if (code === 0) {
            //     this.ServicetypeListName = data;
      
                
            // } else {
            //     this.$message.error(msg)
            // }
            console.log(this.ServicetypeListName,"  this.ServicetypeListName ");
        },
 
      formatContent(content) {
        return content.replace(/<img([^>]*)>/g, function(imgTag, attributes) {
            return `<img${attributes} style="max-width: 130px; max-height: 130px; width: auto; height: auto;">`;
        });
    },
      //获取活动详情
          async getTableData() {
          // const url = "http://yapi.elinkservice.cn/mock/245/gov/project/project/project-list";
          const url = `/voluntary/activityInfo/detail/${this.list.id}`;
          let params = {
        }
        requestGet(url, params).then((res) => {
          if (res.code == 0) {
              this.formData=res.data;
              this.tableDate=res.data.sponsors[0],
              this.searchValue=res.data.address
              this.formData.activityImgs=[{url:res.data.imgs}]
              console.log(this.typeList,"this.sfaafsd");
              this.typeList.list.forEach(item => {
                console.log(item,"item");
                console.log(item.label,"item.label111");
                if (item.id == this.formData.projectId) {
                  console.log(item.projectTitle,"item.label");
                    this.formData.projectTitle=item.projectTitle
                }
              });
              this.ServicetypeListName.forEach(item => {
                console.log(item,"item");
                console.log(item.value,this.formData.type.toString(),"item.lsdfsfsabel111");
                if (item.value == this.formData.type.toString()) {
                  console.log(item.projectTitle,"item.label");
                    this.formData.typeName=item.label
                }
              });

              
              
          } else {
            this.$message.error(res.msg);
          }
        });
          // const { data, code, msg } = await requestGet(url, params)
          // if (code === 0) {
          //   console.log("列表请求成功！！！！！！！！！！！！！！");
          //   this.total = data.total || 0;
          //   this.tableData = data.list
          //   console.log(this.tableData,"this.tableData");
            
      
          // } else {
          // }
        },
          //控制活动时间
          actcontrolTime(){
        console.log("dislfj");
          if(this.formData.strTime>this.formData.endTime){
            this.$message.error('活动结束时间不能在活动开始时间之前');
            this.formData.endTime=''
            return
          }
      },
      //控制签到时间
      controlTime(){
        console.log("dislfj");
          if(this.formData.signInTime>this.formData.signOutTime){
            this.$message.error('签到开始时间不能在签到结束时间之后');
            this.formData.signOutTime=''
            return
          }
      },
         //提交
        async  handleComfirm() {
          console.log(this.tableDate);
        this.formData.sponsors.push(this.tableDate);
        console.log(this.formData,"this,formD");
        if (this.formData.address == '') {
          this.$message.error('请输入活动地点');
          return;
        }
        if (this.formData.agencyId == '') {
          this.$message.error('请选择主办方');
          return;
        }
        if (this.formData.title == '') {
          this.$message.error('请输入活动标题');
          return;
        }
        if (this.formData.content == '') {
          this.$message.error('请输入活动详情');
          return;
        }
        // if (this.formData.imgs == '') {
        //   this.$message.error('请上传图片');
        //   return;
        // }
        if (this.formData.strTime  == '') {
          this.$message.error('请填写活动开始时间');
          return;
        }
        if (this.formData.endTime  == '') {
          this.$message.error('请填写活动结束时间');
          return;
        }
        if (this.formData.type=='') {
          this.$message.error('请填写活动和类型');
          return;
        }
        if (this.formData.linkman=='') {
          this.$message.error('请填写联系人');
          return;
        }
        if (this.formData.linkMobile=='') {
          this.$message.error('请填写联系电话');
          return;
        }
        if (this.formData.signInTime=='') {
          this.$message.error('请填写签到开始时间');
          return;
        }
        if (this.formData.signOutTime=='') {
          this.$message.error('请填写签到结束时间');
          return;
        }
        if (this.formData.deadline=='') {
          this.$message.error('请填写报名截止时间');
          return;
        }
        let url="/voluntary/activityInfo/updateInfo";
        let parms={
          ...this.formData
        }
        console.log(parms,"parms");
        
        await requestPost(url,parms).then((res)=>{
          console.log(res,"res");
          if (res.code==0) {
            this.$message.success('添加成功');
            this.$emit('updateClose')
            // this.$router.push({path:'/volunteer/activityArchive'})
          }else{
            this.$message.error(res.msg);
          }
          
        })
      },
      addDomain() {
        console.log(this.formData.sponsors,this.tableDate,);
          this.formData.sponsors.push(this.tableDate);
          console.log(this.formData.sponsors,this.tableDate,);
     
          
        },
      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.formData.latitude = lonlat[1];
              this.formData.longitude = lonlat[0];
              this.formData.address = selPosition.address + selPosition.name
          },
  
      async handleMoveCenter(e) {
              //修改地图中心点
              // const { lat, lng } = map.getCenter();
              const { lat, lng } = e.latLng;
              this.formData.latitude = lat;
              this.formData.longitude = lng;
              map.setMarker(lat, lng);
  
              let { msg, data } = await map.getAddress(lat, lng);
              if (msg == "success") {
                  this.formData.address = data.address
                  this.searchValue = data.address
                  this.searchOptions = []
                  console.log('data,this.searchValue ', this.searchValue)
  
              }
          },
          // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
          initMap(latitude, longitude) {
              console.log(latitude, longitude,"564564568");
              map = new daiMap(
                  document.getElementById("app_activity"),
                  { latitude, longitude },
                  {
                      zoom: 16.2, // 设置地图缩放级别
                      pitch: 43.5, // 设置俯仰角
                      rotation: 45, // 设置地图旋转角度
                  }
              );           
  
              // 监听地图平移结束
              /*  map.on("dragend", (e) => {
                  this.handleMoveCenter(e);
                });*/
              map.on("click", (e) => {
                  this.handleMoveCenter(e);
              });
  
              map.setCenter(latitude, longitude);
              map.setMarker(latitude, longitude);
  
          },
      async remoteMethod(query) {
              console.log(query, "sfsvsdv");
              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
                          console.log(this.resultList, "this.resultList");
                          this.searchOptions = this.resultList.map(item => {
                              return { value: `${item.id}`, label: `${item.address + item.title}` };
  
                          });
                          console.log(this.searchOptions, "this.searchOptions");
                      }
                  } else {
                      this.searchOptions = [
                          {
                              value: '0',
                              label: '未检索到结果'
                          }
                      ]
                  }
              } else {
                  this.searchOptions = [];
              }
          },
             // 上传前的验证
             beforeImgUpload(file) {
              const isLt1M = file.size / 1024 / 1024 < 10;
              const srcType = file.type;
              const format = file.name.split('.').pop();
              if (!isLt1M) {
                  this.$message.error('上传文件大小不能超过 10MB!');
                  return false;
              }
              if (srcType.indexOf('image') == -1) {
                  this.$message.error('仅限图片格式');
                  return false;
              }
              return true;
          },
              // 文件数量超过限制
              handleImgExceed() {
              this.$message({
                  type: 'warning',
                  message: '文件数量最多不超过一个'
              });
          },
              // 删除图片
              handleImgRemove(file) {
              console.log('handleImgRemove', file);
              if (file.response) {
                  let index = this.activityImgs.findIndex(item => item.url == file.response.data.url);
                  this.activityImgs.splice(index, 1);
              } else if (file.url) {
                  let index = this.activityImgs.findIndex(item => item.url == file.url);
                  this.activityImgs.splice(index, 1);
              }
          },
            // 上传成功
            handleImgSuccess(res, file, fileList) {
              if (res.code === 0 && res.msg === 'success') {
                  let format = file.name.split('.').pop();
                  let srcType = file.raw.type;
                  let type = 'file';
                  if (srcType.indexOf('image') != -1) {
                      type = 'image';
                  } else if (srcType.indexOf('video') != -1) {
                      type = 'video';
                  }
                  this.activityImgs.push(res.data.url);
                  this.formData.imgs=this.activityImgs[0]
                console.log( this.formData.imgs," this.formData.imgs");
                
                  
  
              } else {
                  this.$message.error(res.msg);
              }
          },
         // 图片预览
          handleImgPreview(file) {
              console.log(file);
              window.open(file.url || file.response.data.url);
          },
      handleSwitchChange(value) {
        // 将 value 转换为整数
        this.formData.online = Number(value);
      },
    
      handleOnlineRegistration(value) {
              if (value) {
                  this.online = true;
                  this.formData.online = 1;
              } else {
                  this.online = false;
                  this.formData.cutOffTime = ''
                  this.formData.online = 0;
              }
          },
      handleChangeAgency(val) {
              console.log(val);
              this.formData.agencyId = val
         },
   
      //图片
      removedImg() {
              this.formData.imgs = ''
       },
      onChangeFileList(e) {
              console.log(e, 'sssssb');
              // this.formData.$slotsimgs = e.length > 0 ? e.map(item => ({
              //     fileType: '0',
              //     fileUrl: item.response.data.url
              // })) : []; // 当e为空时清空fileList
              if (e.length > 0) {
                  this.formData.imgs = e[0].response.data.url;
              } else {
                  this.formData.imgs = '';
              }
          },
      //获取当前组织
     getOrgTreeList() {
        this.$http
          .post("/gov/org/customeragency/agencygridtree", {orgTypeFilter:this.orgTypeFilter})
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              this.orgOptions = [];
              this.orgOptions.push(res.data);
              console.log(this.orgOptions,"this.orgOptions");
              
            }
          })
          .catch(() => {
            return this.$message.error("网络错误");
          });
          this.$nextTick(() => {
            console.log(map,"mao");
                  if (!map) {
                      this.initMap(this.formData.latitude, this.formData.longitude);
                      console.log("map", map,this.formData.latitude, this.formData.longitude)
                  } else {
                      map.setCenter(this.formData.latitude, this.formData.longitude);
                      map.setMarker(this.formData.latitude, this.formData.longitude);
                      console.log("mapmapmap", map)
                  }
              })
      },
      handleCancle () {
        console.log(    "kdsljk");
    
        this.$emit('updateClose')
  
      },
           // 开启加载动画
           startLoading() {
              loading = Loading.service({
                  lock: true, // 是否锁定
                  text: '正在加载……', // 加载中需要显示的文字
                  background: 'rgba(0,0,0,.7)' // 背景颜色
              })
          },
          // 结束加载动画
          endLoading() {
              // clearTimeout(timer);
              if (loading) {
                  loading.close()
              }
          }
    },
    computed: {
    },
    props: {
  
      formType: { //表单操作类型 add新增，edit编辑，detail详情
        type: String,
        required: ''
      },
      icPartyActId: {
        type: String,
        required: ''
      },
      list:{
        type: Object,
        default: () => {}
      }
  
  
    },
    destroyed () {
    map = null
  }
  }
  
  </script>
  <style lang="scss" scoped>
.span1 img {
    max-width: 100%; /* 图片宽度不超过容器宽度 */
    max-height: 100px; /* 图片高度最大为 100px */
    width: auto; /* 自动调整宽度保持比例 */
    height: auto; /* 自动调整高度保持比例 */
}

  .div_map{
    width: 300px;
    margin-top: 10px;
  }
  .div_btn1{
    display: flex;
      justify-content: center;
  }
  </style>