<template>
  <div>
    <van-nav-bar title="帮扶活动" @click-left="$router.back()" left-arrow fixed placeholder safe-area-inset-top />
    <van-form @submit="lovingHelpSave">
      <div class="main">
        <van-row class="cell">
          <van-col span="6">活动名称：</van-col>
          <van-col span="18">
            <van-field v-model="form.name" :rules="[{ required: true}]" placeholder="活动名称" :disabled="id!=undefined" />
          </van-col>
        </van-row>

        <van-row class="cell">
          <van-col span="6">活动时间：</van-col>
          <van-col span="18" @click="clickdateshow">
            <!-- {{form.workDate?form.workDate:'请选择'}} -->
            <van-field v-model="form.workDate" :rules="[{ required: true}]" placeholder="请选择" disabled />
          </van-col>
          <van-popup v-model="dateshow" position="bottom" :style="{ height: '50%' }">
            <van-datetime-picker @confirm="dateConfirm" @cancel="dateshow=false" v-model="workDate" type="date" :min-date="minDate" :max-date="maxDate" :columns-order="[ 'year','month', 'day']"
              :formatter="formatter" />
          </van-popup>
        </van-row>
        <van-row class="cell">
          <van-col span="6">选择街道：</van-col>
          <van-col span="18">
            <van-field v-model="form.areaName" :rules="[{ required: true}]" @click="clickstreetShow" placeholder="请选择" disabled />
          </van-col>
          <!-- <van-col span="18" @click="streetshowPopup">{{form.streetName?form.streetName:'请选择'}}</van-col> -->
          <van-popup v-model="streetShow" position="bottom" :style="{ height: '50%' }">
            <van-picker default-index="2" show-toolbar :columns="streetList" @confirm="onConfirm" @cancel="streetShow=false" value-key="name" />
          </van-popup>
        </van-row>
        <van-row class="cell">
          <van-col span="6">活动地址：</van-col>
          <van-col span="18">
            <van-field v-model="form.address" :rules="[{ required: true}]" placeholder="请输入活动地址" :disabled="id!=undefined" />
          </van-col>
        </van-row>
        <van-row class="cell">
          <van-col span="6">帮扶对象：</van-col>
          <van-col span="18">
            <div class="serviceTarget" @click="clickserviceTargetShow">
              <!-- {{form.helpChildren?form.helpChildren:'请选择'}} -->
              <van-field v-model="form.helpChildren" :rules="[{ required: true}]" placeholder="请输入帮扶对象" :disabled="id!=undefined" />
            </div>
            <van-popup position="bottom" v-model="serviceTargetShow">
              <div class="field">
                <div v-for="(item,index) in serviceTarget" :key="index">{{item}}
                  <van-icon name="clear" color="#999" @click="clearserviceTarget(index)" />
                </div>
              </div>
              <van-search placeholder="请输入姓名查询" @input="listChildInfoByName" v-model="positionSearch" />
              <van-picker cancel-button-text='取消' :confirm-button-text='childList.length>0?"选择":"确定"' value-key="title" show-toolbar :columns="childList" @confirm="onConfirmPicker"
                @cancel="serviceTargetShow = false">
                <template #option="item">
                  <span>{{item.name}}</span>
                  <span>({{item.idCard}})</span>
                </template>
              </van-picker>
            </van-popup>
          </van-col>
        </van-row>
        <van-row class="cell">
          <van-col span="6">主办单位：</van-col>
          <van-col span="18">
            <van-field v-model="orglist.name" placeholder="请输入主办单位" disabled />
          </van-col>
        </van-row>
        <van-row class="cell">
          <van-col span="6">联系人：</van-col>
          <van-col span="18">
            <van-field v-model="orglist.owner" placeholder="联系人" disabled />
          </van-col>
        </van-row>
        <van-row class="cell">
          <van-col span="6">联系方式：</van-col>
          <van-col span="18">
            <van-field v-model="orglist.mobile" placeholder="联系方式" disabled />
          </van-col>
        </van-row>
        <van-row class="cell">
          <van-col span="6">活动详情：</van-col>
          <van-col span="18">
            <van-field class="textarea" :rules="[{ required: true}]" :disabled="id!=undefined" v-model="form.content" rows="1" type="textarea" placeholder="请输入活动详情" />
          </van-col>
        </van-row>
        <div v-if="!id">
          <vanUploader :text="'图片'" @getfileList="getfileList"></vanUploader>
          <vanUploader :text="'视频'" @getfileList="getfileList"></vanUploader>
        </div>
        <div v-else class="imgvideo">
          <div>
            <p>照片：</p>
            <div class="boximg">
              <div v-for="(item,index) in pics" :key="index">
                <van-image fit="contain" :src="item" alt="" @click="showPopup" />
              </div>
            </div>
            <van-image-preview v-model="show" :images="pics"></van-image-preview>
          </div>
          <div>
            <p>视频：</p>
            <div class="boximg">
              <div v-for="(item,index) in videos" :key="index">
                <video @click="showvideoplay=true,videourl=item" style="object-fit:cover;" :src="item" poster='../../assets/video.png'></video>
              </div>
            </div>
          </div>
        </div>
      </div>
      <van-dialog style="width:100%;border-radius:0;height:200px" v-model="showvideoplay" :show-cancel-button="false" :show-confirm-button="false" closeOnClickOverlay>
        <video controls preload="auto" style="width:100%;height:200px;object-fit: contain;" :src="videourl" v-if="videourl"></video>
      </van-dialog>
      <div style="text-align:center;" v-if="!id">
        <van-button native-type="submit">确 定</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  organizationDetail,
  lovingHelpSave,
  listChildInfoByName,
  uploadImage,
  getStreetList,
  lovingHelpDetail,
} from '../../api/index.js'
import vanUploader from '../../components/vanUploader.vue'
export default {
  components: { vanUploader },
  data() {
    return {
      showvideoplay: false,
      streetshowPopup: false,
      streetShow: false,
      show: false,
      searchshow: false,
      serviceTargetShow: false,
      fileList: [],
      streetList: [],
      form: {
        fileList: [],
      },
      dateshow: false,
      appendFile: [],
      workDate: new Date(),
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2025, 10, 1),
      orglist: '',
      positionSearch: '',
      serviceTarget: [],
      childList: [],
      id: '',
      orgId: '',
      pics: [],
      videos: [],
    }
  },
  created() {
    this.id = this.$route.query.id
    console.log(this.id, 'id')
    this.orgId = this.$route.query.orgId
    this.getStreetList()
    this.organizationDetail()

    if (this.id) {
      this.lovingHelpDetail()
    }
  },
  methods: {
    clearserviceTarget(index) {
      if (!this.form.serviceTarget) return
      var serviceTarget = this.form.serviceTarget.split(',')
      serviceTarget.splice(index, 1)
      this.serviceTarget.splice(index, 1)
      this.form.serviceTarget = serviceTarget.join(',')
    },
    clickdateshow() {
      if (this.id) return
      this.dateshow = !this.dateshow
    },
    clickstreetShow() {
      if (this.id) return
      this.streetShow = !this.streetShow
    },
    clickserviceTargetShow() {
      if (this.id) return
      this.serviceTargetShow = !this.serviceTargetShow
    },
    async getStreetList() {
      const res = await getStreetList()
      this.streetList = res.data
    },
    async lovingHelpDetail() {
      const res = await lovingHelpDetail({ id: this.id })
      this.form = res.data
      this.pics = res.data.pics.split(',')
      if (!res.data.videos) return
      this.videos = res.data.videos.split(',')
    },
    async listChildInfoByName() {
      if (!this.positionSearch) return
      const res = await listChildInfoByName({ name: this.positionSearch })
      this.childList = res.data
    },
    async organizationDetail() {
      console.log(this.orgId, 'this.orgId')
      const res = await organizationDetail({ id: this.orgId })
      this.orglist = res.data
    },
    onConfirm(value) {
      this.form.areaName = value.name
      this.form.areaId = value.id
      this.streetShow = false
    },
    dateConfirm(v) {
      console.log(v)
      this.form.workDate = this.timeFormat(v)
      this.dateshow = false
    },
    onConfirmPicker(value) {
      if (!value) {
        console.log(value)
        this.serviceTargetShow = !this.serviceTargetShow
        return
      }
      this.serviceTarget.push(value.name)
      this.$set(this.form, 'helpChildren', this.serviceTarget.join(','))
      this.childList = []
      this.positionSearch = ''
    },
    getfileList(v, index) {
      if (index == undefined) {
        if (
          v.indexOf('.png') != -1 ||
          v.indexOf('.jpg') != -1 ||
          v.indexOf('.jpeg') != -1
        ) {
          this.pics.push(v)
        } else {
          this.videos.push(v)
        }
      } else {
        if (v == '图片') {
          this.pics.splice(index, 1)
        } else {
          this.videos.splice(index, 1)
        }
      }
    },
    async lovingHelpSave() {
      if (this.pics.length == 0) {
        this.$toast.fail('请选择至少一张图片')
        return
      }
      this.form.pics = this.pics.join(',')
      this.form.videos = this.videos.join(',')
      var data = JSON.parse(JSON.stringify(this.form))
      data.workDate = data.workDate + ' 00:00:00'
      const res = await lovingHelpSave(data)
      if (res.code == '0000') {
        this.$toast.success('成功')
        this.$router.go(-1)
      }
    },
    showPopup() {
      this.show = true
    },
    getPositionList() {},
    async afterRead(file) {
      console.log(file.file)
      file.status = 'uploading'
      file.message = '上传中...'
      let formDate = new FormData()
      //添加入参
      formDate.append('file', file.file)
      const res = await uploadImage(formDate)
      if (res.code == '0000') {
        file.status = 'success'
        file.message = '成功'
        this.form.fileList.push({
          url: res.data,
          type: file.file.type,
        })
        // 上传图片 设置col高度
        if (this.form.fileList.length % 2 == 0) {
          var index = 3.2 * (this.form.fileList.length / 2 + 1) + 'rem'
          this.$refs.boxlist.style.height = index
        }
      } else {
        file.status = 'failed'
        file.message = '上传失败'
      }
    },
    deleteUploader(v, index) {
      console.log(index)
      this.form.fileList.splice(index.index, 1)
    },
    formatter(type, val) {
      if (type === 'year') {
        return val + '年'
      }
      if (type === 'month') {
        return val + '月'
      }
      if (type === 'day') {
        return val + '日'
      }
      return val
    },
    timeFormat(time) {
      // 时间格式化 2019-09-08
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      if (month < 10) {
        month = '0' + month
      }

      let day = time.getDate()
      if (day < 10) {
        day = '0' + day
      }
      return year + '-' + month + '-' + day
    },
  },
}
</script>
<style lang="scss" scoped>
.tx {
  width: 160px;
  height: 160px;
}
.message {
  padding: 0 30px;
}
.field {
  padding: 0 30px;
  display: flex;
  margin-top: 16px;
  div {
    margin: 0 10px;
    font-size: 26px;
    padding: 10px;
    line-height: normal;
    background-color: #eee;
    border-radius: 40px;
  }
}
.topBox {
  padding: 24px 0;
  border-bottom: 1px solid #eee;
}
.van-row {
  font-size: 30px;
  text-align: left;
}
.row {
  .van-col {
    line-height: 60px;
  }
}
.main {
  padding: 0 30px;
}
.cell {
  border-bottom: 1px solid #eee;
  margin-top: 16px;
  .van-col {
    line-height: 80px;
  }
  .van-cell {
    padding: 0;
    line-height: 80px;
  }
}
.textarea {
  line-height: 30px !important;
  margin-top: 25px;
}
.van-button {
  width: 690px;
  margin: 24px auto;
  color: #fff;
  background-color: #1677ff;
  border-radius: 8px;
  font-size: 30px;
}
.box {
  position: relative;
  height: 240px;
  .boxlist {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    flex-wrap: wrap;
    div {
      width: 200px;
      height: 200px;
      margin: 20px;
    }

    img {
      width: 100%;
      height: 100%;
    }
    video {
      width: 100%;
      height: 100%;
    }
    // background-color: chocolate;
  }
  .van-uploader {
    position: absolute;
    top: 0;
    left: 0;
    /deep/.van-uploader__wrapper {
      .van-uploader__upload {
        width: 200px;
        height: 200px;
      }
    }

    /deep/.van-uploader__preview {
      margin: 20px;
      .van-uploader__file {
        opacity: 0;
      }
      .van-image {
        width: 200px;
        height: 200px;
        opacity: 0;
        // margin: 20px;
      }
      width: 200px;
      height: 200px;
    }
  }
}
/deep/.van-field__control {
  color: #333;
}
/deep/.van-field__control:disabled {
  color: #333;
  -webkit-text-fill-color: unset;
}
.imgvideo {
  font-size: 30px;
  text-align: left;
  margin-bottom: 30px;
  .boximg {
    min-height: 100px;
    border: 1px solid #eee;
    padding: 20px 0;
    font-size: 26px;
    color: #999;
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    .van-image {
      max-width: 200px;
      //   max-height: 200px;
      //   margin-right: 16px;
      margin: 0 10px;
      margin-bottom: 16px;
    }
    video {
      width: 180px;
      height: 180px;
      margin: 0 10px;
      //   margin-right: 16px;
      margin-bottom: 16px;
    }
  }
}
</style>