<template>
  <view>
    <Loading :type="3" :loadStatus="loadStatus" :showText="errorText" />

    <zj-page-layout v-if="detailData" :hasFooter="true" bgColor="#ffffff">
      <view class="swiper-container" v-if="bannerList.length > 0">
        <swiper class="banner-swiper" @change="changeBanner" :autoplay="true">
          <block v-for="(item, index) in bannerList" :key="index">
            <swiper-item>
              <image :src="item" mode="aspectFill"></image>
            </swiper-item>
          </block>
        </swiper>
        <view class="dots-conatiner">
          <view class="con" :style="'width:' + bannerList.length * 20 + 'rpx;'">
            <view class="dot" :style="'transform:translateX(' + bannerCurrent * 100 + '%)'"></view>
          </view>
        </view>
        <view class="explain" @tap="toExplain">活动说明</view>
      </view>

      <view class="all-container">
        <view class="form-container">
          <view class="row" v-if="websitName">
            <view class="label">所属网点</view>
            <u--input placeholder="" border="none" inputAlign="right" v-model="websitName" readonly></u--input>
          </view>
          <view class="row">
            <view class="label"><text>*</text>您的姓名</view>
            <u--input
              placeholder="请输入您的姓名"
              border="none"
              inputAlign="right"
              v-model="name"
              :readonly="isDisabled"
            ></u--input>
          </view>
          <view class="row">
            <view class="label"><text>*</text>您的电话</view>
            <u--input
              placeholder="请输入您的电话"
              border="none"
              inputAlign="right"
              v-model="phone"
              :maxlength="11"
              :readonly="isDisabled"
            ></u--input>
          </view>
          <view class="row">
            <view class="label"><text>*</text>您的地址</view>
            <u--input
              placeholder="请输入您的地址"
              border="none"
              inputAlign="right"
              v-model="address"
              :readonly="isDisabled"
            ></u--input>
            <view class="r" @tap="getLocation"><text class="iconfont icon-dingwei1"></text>定位</view>
          </view>
        </view>

        <block v-for="(item, index) in questionList" :key="index">
          <view class="picker-container" v-if="item.type == 1 || item.type == 2">
            <view class="label"
              ><text v-if="item.isRequire">*</text>{{ item.question }}（{{
                { 1: '单选', 2: '多选' }[item.type]
              }}）</view
            >
            <view class="img-list" v-if="item.answerType == 1 || item.answerType == 3">
              <view
                class="item"
                :class="it.active ? 'active' : ''"
                v-for="(it, idx) in item.answer"
                :key="idx"
                @tap="clickOption(index, idx)"
              >
                <image v-if="it.option_files.length" :src="it.option_files[0].url" mode="aspectFill"></image>
                <view class="text" v-if="item.answerType == 1">{{ it.option_value }}</view>
              </view>
            </view>
            <view class="text-list" v-else>
              <view
                class="item"
                :class="it.active ? 'active' : ''"
                v-for="(it, idx) in item.answer"
                :key="idx"
                @tap="clickOption(index, idx)"
              >
                {{ it.option_value }}
              </view>
            </view>
          </view>

          <view class="input-container" v-else-if="item.type == 3">
            <view class="label"><text v-if="item.isRequire">*</text>{{ item.question }}</view>
            <u--textarea
              autoHeight
              :placeholder="`请输入${item.question}`"
              border="none"
              :maxlength="item.answer[0].option_limit"
              count
              v-model="item.inputValue"
              :disabled="isDisabled"
            ></u--textarea>
          </view>

          <view class="input-container" v-else-if="item.type == 4">
            <view class="label"><text v-if="item.isRequire">*</text>{{ item.question }}</view>
            <view class="images">
              <view class="img" v-for="(it, idx) in item.fileValue">
                <image :src="it" mode="aspectFill" @tap="prevImg(it, item.fileValue)"></image>
                <text class="iconfont icon-guanbi1" @tap="delImage(questionList, index, idx)"></text>
              </view>
              <view
                class="add"
                @tap="addImage(questionList, index)"
                v-if="item.fileValue.length < item.answer[0].option_limit"
              >
                <text class="iconfont icon-xiangji"></text>
                <text class="text">图片</text>
              </view>
            </view>
          </view>

          <view class="input-container" v-else-if="item.type == 5">
            <view class="label"><text v-if="item.isRequire">*</text>{{ item.question }}</view>
            <view class="images">
              <view v-for="(it, idx) in item.fileValue" class="img" style="width: 100%">
                <video :src="it" style="width: 100%; height: 240px"></video>
                <text
                  style="z-index: 100000"
                  class="iconfont icon-guanbi1"
                  @tap="delImage(questionList, index, idx)"
                ></text>
              </view>
              <view
                class="add"
                @tap="addVideo(questionList, index)"
                v-if="item.fileValue.length < item.answer[0].option_limit"
              >
                <text class="iconfont icon-xiangji"></text>
                <text class="text">视频</text>
              </view>
            </view>
          </view>
        </block>

        <view class="carousel-container" v-if="applyList && applyList.length > 0">
          <carousel :list="applyList" :showNum="3" :standstill="1000">
            <template slot-scope="slot">
              <view class="item" v-for="(item, index) in slot.data" :key="index">
                <view class="left">
                  <view class="name">{{ item.name }}[{{ item.mobile }}]</view>
                  <view class="text">{{ item.remark }}</view>
                </view>
                <!-- <view class="right">{{item.createTime | timeFilter}}</view> -->
                <view class="right">{{ item.min }}分钟前</view>
              </view>
            </template>
          </carousel>
        </view>
      </view>

      <template slot="footer">
        <view class="footer-btn-group">
          <u-button text="报名记录" @tap="toList"></u-button>
          <u-button type="primary" text="提交" @click="submitData" v-if="!isDisabled"></u-button>
        </view>
      </template>
    </zj-page-layout>
  </view>
</template>

<script>
import carousel from '@/components/carousel'
import { uploadImgFull } from '@/common/utils/util.js'

export default {
  components: {
    carousel
  },

  data() {
    return {
      loadStatus: 1,
      errorText: '',
      id: '',
      websitName: '',
      bannerList: [], // 轮播图列表
      bannerCurrent: 0, // 轮播图当前值
      detailData: null,
      questionList: [],
      applyList: [],

      name: '',
      phone: '',
      address: '',
      isNotYetStarted: true
    }
  },

  onLoad({ id, websitName }) {
    this.id = id
    this.websitName = websitName || ''
    this.getDetail()
  },
  onShow() {
    // if(uni.getStorageSync('formData')){
    // 	let {name,phone,address} = uni.getStorageSync('formData')
    // 	alert(name)
    // 	this.name = name
    // 	this.phone = phone
    // 	this.address = address
    // }
  },
  computed: {
    isDisabled() {
      return (
        !this.detailData.isShow ||
        this.isNotYetStarted ||
        !!~[2, 3].indexOf(this.detailData.status) ||
        (this.detailData.limit == 0 && this.detailData.submitLimit != -1)
      )
    }
  },
  methods: {
    getDetail() {
      this.$api
        .post('/promotion/questionnaire/detail', {
          id: this.id
        })
        .then(res => {
          this.detailData = res.data
          this.bannerList = res.data.detailImgs.split(',')
          res.data.promotionQuestionnaireItems.forEach(item => {
            item.answer = JSON.parse(item.answer)
            item.inputValue = ''
            item.fileValue = []
            item.answer.forEach(it => {
              it.active = false
            })
          })
          this.questionList = res.data.promotionQuestionnaireItems
          console.log(this.questionList)
          this.applyList = res.data.promotionQuestionnaireUsers
          // 获取当前时间
          var currentTime = new Date()
          // 解析日期字符串
          var dateParts = res.data.startTime.split(/[\s-:]/)
          // 构造日期对象
          var specifiedTime = new Date(
            parseInt(dateParts[0]), // 年
            parseInt(dateParts[1]) - 1, // 月（月份从0开始，所以需要减1）
            parseInt(dateParts[2]), // 日
            parseInt(dateParts[3]), // 时
            parseInt(dateParts[4]), // 分
            parseInt(dateParts[5]) // 秒
          )
          // 比较当前时间和指定时间
          if (currentTime.getTime() >= specifiedTime.getTime()) {
            this.isNotYetStarted = false
          }
          if (res.data.status == 2) {
            this.$tips(`该活动已过期，不可提交报名！`)
          } else if (res.data.status == 3) {
            this.$tips(`该活动已终止，不可提交报名！`)
          } else if (!!~[0, 1].indexOf(this.detailData.status) && res.data.submitLimit > -1) {
            this.$tips(`您还可以提交${res.data.limit}次`)
          }
          this.loadStatus = 0
        })
        .catch(res => {
          this.errorText = res.message
          this.loadStatus = 2
        })
    },

    clickOption(index, idx) {
      if (this.isDisabled) {
        return
      }
      // 单选题
      if (this.questionList[index].type == 1) {
        this.questionList[index].answer.forEach((item, ind_) => {
          this.questionList[index].answer.splice(ind_, 1, {
            ...item,
            active: ind_ == idx ? (this.questionList[index].isRequire ? true : !item.active) : false
          })
        })
      }
      // 多选题
      else {
        this.questionList[index].answer.splice(idx, 1, {
          ...this.questionList[index].answer[idx],
          active: !this.questionList[index].answer[idx].active
        })
      }
    },

    // 切换广告图
    changeBanner(e) {
      this.bannerCurrent = e.detail.current
    },

    toList() {
      this.$navToPage({
        url: `/packageHome/pages/codeActivity/applyList?id=${this.id}`
      })
    },

    toExplain() {
      this.$navToPage({
        url: `/packageHome/pages/codeActivity/activityExplain?id=${this.id}`
      })
    },

    submitData() {
      // 校验必填
      if (!this.name) return this.$toast('请输入您的姓名')
      if (!this.phone) return this.$toast('请输入您的电话')
      if (!/^1[3456789]\d{9}$/.test(this.phone)) return this.$toast('请填写正确的电话号码')
      if (!this.address) return this.$toast('请输入您的地址')
      for (let i = 0; i < this.questionList.length; i++) {
        if (this.questionList[i].isRequire) {
          // 单选题多选题
          if (
            (this.questionList[i].type == 1 || this.questionList[i].type == 2) &&
            this.questionList[i].answer.every(o => !o.active)
          ) {
            return this.$toast(`请选择${this.questionList[i].question}`)
          }
          // 填写题
          if (this.questionList[i].type == 3 && !this.questionList[i].inputValue) {
            return this.$toast(`请输入${this.questionList[i].question}`)
          }
          // 图片视频题
          if (
            (this.questionList[i].type == 4 || this.questionList[i].type == 5) &&
            !this.questionList[i].fileValue.length
          ) {
            return this.$toast(`请完善${this.questionList[i].question}`)
          }
        }
      }

      // 生成题目提交信息
      // let items = [];
      let questionList = JSON.parse(JSON.stringify(this.questionList))
      for (let index = 0; index < questionList.length; index++) {
        // 单选题多选题
        if (questionList[index].type == 1 || questionList[index].type == 2) {
          questionList[index].answer = questionList[index].answer
          questionList[index].answer = JSON.stringify(questionList[index].answer)
        }
        // 填写题
        if (questionList[index].type == 3) {
          questionList[index].answer[0].option_value = questionList[index].inputValue
          questionList[index].answer = JSON.stringify(questionList[index].answer)
        }
        // 图片视频题
        if (questionList[index].type == 4 || questionList[index].type == 5) {
          questionList[index].answer[0].option_value = questionList[index].fileValue
          questionList[index].answer = JSON.stringify(questionList[index].answer)
        }
      }

      this.$api
        .postJson('/promotion/activity/add', {
          userName: this.name,
          userMobile: this.phone,
          userAddress: this.address,
          items: questionList,
          promotionQuestionnaireId: this.id,
          customWebsitName: this.websitName || ''
        })
        .then(res => {
          this.$successToast('提交成功')
          this.$navToPage(
            {
              url: `/packageHome/pages/codeActivity/applyList?id=${this.id}`
            },
            'redirectTo'
          )
        })
    },

    // 添加图片
    async addImage(questionList, index) {
      if (this.isDisabled) {
        return
      }
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        success: res => {
          uni.showLoading()
          res.tempFilePaths.forEach(async item => {
            let data = await uploadImgFull(item)
            questionList.splice(index, 1, {
              ...questionList[index],
              fileValue: [...questionList[index].fileValue, data.url]
            })
          })
          uni.hideLoading()
        },
        fail: err => {}
      })
    },

    async addVideo(questionList, index) {
      if (this.isDisabled) {
        return
      }
      uni.chooseVideo({
        count: 1,
        success: async res => {
          uni.showLoading()
          let data = await uploadImgFull(res.tempFilePath)
          questionList.splice(index, 1, {
            ...questionList[index],
            fileValue: [...questionList[index].fileValue, data.url]
          })
          uni.hideLoading()
        },
        fail: err => {}
      })
    },

    // 删除图片
    delImage(questionList, index, idx) {
      questionList[index].fileValue.splice(idx, 1)
      // questionList.splice(index, 1, {...questionList[index], fileValue: files})
    },

    //预览图片
    prevImg(url, urls) {
      uni.previewImage({
        current: url,
        urls: urls
      })
    },

    async getRegionByLatLng(lat, lng) {
      const result = new Promise((resolve, reject) => {
        this.$api
          .post('/lbs/amap/region/query', {
            lat,
            lng
          })
          .then(res => {
            resolve(res.data)
          })
      })
      return result
    },

    // 地图选点
    getLocation() {
      let that = this
      uni.chooseLocation({
        success: async res => {
          // uni.setStorageSync('formData',{name: this.name,phone: this.phone,address: res.address})
          let addressData = await this.getRegionByLatLng(res.latitude, res.longitude)
          that.address = addressData.provinceName + addressData.cityName + addressData.areaName + res.address
        },
        fail: function (res) {
          uni.getSetting({
            success: function (res) {
              if (!res.authSetting['scope.userLocation']) {
                uni.showModal({
                  title: '是否授权当前位置',
                  content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
                  success(tip) {
                    if (tip.confirm) {
                      uni.openSetting({
                        success: function (data) {
                          if (data.authSetting['scope.userLocation'] === true) {
                            that.$successToast('授权成功')
                            setTimeout(() => {
                              that.getLocation()
                            }, 1000)
                          }
                        }
                      })
                    }
                  }
                })
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.swiper-container {
  position: relative;
  .explain {
    position: absolute;
    right: 30rpx;
    top: 30rpx;
    width: 160rpx;
    height: 60rpx;
    border-radius: 60rpx;
    background: #ffffff;
    font-size: 28rpx;
    color: $assist-color;
    border: 1px solid $assist-color;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .banner-swiper {
    height: 600rpx;
    image,
    video {
      height: 600rpx;
      width: 750rpx;
      display: block;
      margin: 0 auto 0;
      overflow: hidden;
    }
  }
  .dots-conatiner {
    position: absolute;
    width: 100%;
    bottom: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    .con {
      border-radius: 4rpx;
      overflow: hidden;
      height: 4rpx;
      background-color: rgba($color: #ffffff, $alpha: 0.3);
    }
    .dot {
      width: 20rpx;
      height: 4rpx;
      background-color: #ffffff;
      transition: all 0.3s;
    }
  }
}

.all-container {
  padding: 0 20rpx 40rpx;
}

.form-container {
  .row {
    display: flex;
    align-items: center;
    margin-top: 40rpx;
    .label {
      font-size: 28rpx;
      font-weight: 500;
      margin-right: 30rpx;
      text {
        color: red;
      }
    }
    .r {
      color: $theme-color;
      margin-left: 12rpx;
    }
  }
}

.input-container {
  margin-top: 40rpx;
  .label {
    font-size: 28rpx;
    font-weight: 500;
    text {
      color: red;
    }
  }
  ::v-deep .u-textarea {
    margin-top: 20rpx;
    background: #f5f5f5;
  }
  .images {
    display: flex;
    flex-wrap: wrap;
    .add {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 146rpx;
      height: 146rpx;
      border: 2rpx dashed #dadada;
      border-radius: 10rpx;
      margin-top: 20rpx;
      .iconfont {
        font-size: 48rpx;
        color: #999999;
      }
      .text {
        font-size: 24rpx;
        color: #999999;
        margin-top: 10rpx;
      }
    }
    .img {
      position: relative;
      margin-right: 20rpx;
      margin-top: 20rpx;
      &:nth-child(4n) {
        margin-right: 0;
      }
      image {
        width: 150rpx;
        height: 150rpx;
        border-radius: 10rpx;
        overflow: hidden;
        display: block;
      }
      video {
        width: 100%;
        height: 240px;
      }
      text {
        position: absolute;
        right: -10rpx;
        top: -10rpx;
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        background: #ff3f42;
        font-size: 24rpx;
        color: #ffffff;
        text-align: center;
        line-height: 40rpx;
        display: block;
      }
    }
  }
}

.picker-container {
  margin-top: 40rpx;
  .label {
    font-size: 28rpx;
    font-weight: 500;
    text {
      color: red;
    }
  }
  .text-list {
    display: flex;
    flex-wrap: wrap;
    .item {
      margin-top: 20rpx;
      margin-right: 20rpx;
      width: calc((100% - 40rpx) / 3);
      height: 60rpx;
      border-radius: 60rpx;
      background: #f5f5f5;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        border: 1px solid $assist-color;
        color: $assist-color;
        background: #ffffff;
      }
    }
  }
  .img-list {
    display: flex;
    flex-wrap: wrap;
    .item {
      margin-top: 20rpx;
      margin-right: 20rpx;
      width: calc((100% - 40rpx) / 3);
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 10rpx;
      image {
        width: 100%;
        height: 120rpx;
      }
      .text {
        font-size: 28rpx;
        margin-top: 12rpx;
      }
      &:nth-child(3n) {
        margin-right: 0;
      }
      &.active {
        border: 1px solid $assist-color;
        .text {
          color: $assist-color;
        }
      }
    }
  }
}

.carousel-container {
  margin-top: 40rpx;
  padding-top: 40rpx;
  border-top: 1px solid #eaeaea;
  .item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    .left {
      .name {
        font-weight: 500;
      }
      .text {
        margin-top: 12rpx;
        font-size: 28rpx;
      }
    }
    .right {
      font-size: 28rpx;
      color: $sec-font;
    }
  }
}
</style>
