<template>
  <div class="page">
    <div class="taskDetail" v-if="showPages">
      <div class="task">
        <h4>{{ info.title }}</h4>
        <p>{{ info.detail }}</p>
        <div class="imgs" v-if="info.files">
          <image :src="item.url" v-for="(item, index) in info.files" :key="index" mode="aspectFill" @click="preview(item.url)" />
        </div>
      </div>

      <div class="info">
        <div class="title">基础信息</div>
        <div class="items">
          <img src="https://cdn.cunwuyun.cn/fengdu/ic-dizhi.png" alt="">
          <div class="items-info">
            <label>活动地点：</label>
            <div class="value">{{ info.address }}</div>
          </div>
          <div class="address" @click="toAddress">
            <img src="https://cdn.cunwuyun.cn/fengdu/ic-daohang.png" alt="">
            <i>导航</i>
          </div>
        </div>
        <div class="item">
          <img src="https://cdn.cunwuyun.cn/fengdu/ic-renwuleixing.png" alt="">
          <div class="item-info">
            <label>任务类型：</label>
            <div class="value">{{ $dict.getLabel('fdIntegralTaskType', info.type) }}</div>
          </div>
        </div>
        <div class="item">
          <img src="https://cdn.cunwuyun.cn/fengdu/ic-jinchangshijian.png" alt="">
          <div class="item-info" v-if="info.intoBegintime && info.intoEndtime">
            <label>{{ info.type == 0 ? '进场时间：' : '报名时间：' }}</label>
            <div class="value">{{ info.intoBegintime.substring(0, 16) }} 至 {{ info.intoEndtime.substring(0, 16) }}</div>
          </div>
        </div>
        <div class="item" v-if="info.type == 0">
          <img src="https://cdn.cunwuyun.cn/fengdu/ic-lichangshijian.png" alt="">
          <div class="item-info" v-if="info.exitBegintime && info.exitEndtime">
            <label>离场时间：</label>
            <div class="value">{{ info.exitBegintime.substring(0, 16) }} 至 {{ info.exitEndtime.substring(0, 16) }}</div>
          </div>
        </div>
      </div>
      <div class="btn-wrapper" v-if="info.type == 1">
        <div class="btn" @click="signUp" hover-class="text-hover" :class="baoming == 1 ? 'opacity' : baoming == 0 ? 'gray' : ''">
          <span v-if="baoming == 2 || baoming == 0">报名得积分<span v-if="baoming == 2">/积分+{{ info.enrollIntegral }}</span></span>
          <span v-if="baoming == 1">已报名</span>
        </div>
      </div>
      <div class="btn-wrapper" v-if="info.type == 0">
        <div class="btn" @click="clockIn" hover-class="text-hover" :class="isClock == 0 ? 'gray' : isClock == 3 ? 'gray' : isClock == 2 ? 'opacity' : isClock == 4 ? 'opacity' : ''">
          <div class="daka">{{ dkqd }}<span v-if="isClock == 1">/积分+{{ intoIntegral }}</span></div>
        </div>
      </div>
    </div>
    <AiLogin ref="login" @success="getAuth()"/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
var QQMapWX = require('./libs/qqmap-wx-jssdk.js')
export default {
  name: "taskDetail",
  appName: "任务详情",
  data() {
    return {
      info: {},
      id: '',
      latitude: '',
      longitude: '',
      address: '',
      qqmapsdk: null,
      distance: 100,
      flag: false,
      showPages: false,
    }
  },
  computed: {
    ...mapState(['user', 'token']),
    intoIntegral() {
      const times = new Date().getTime()
      const inSTimes = new Date(this.info.intoBegintime?.replaceAll('-', '/')).getTime()
      const inETimes = new Date(this.info.intoEndtime?.replaceAll('-', '/')).getTime()
      const outSTimes = new Date(this.info.exitBegintime?.replaceAll('-', '/')).getTime()
      const outETimes = new Date(this.info.exitEndtime?.replaceAll('-', '/')).getTime()

      if (times > inSTimes && times < inETimes) {
        return this.info.intoIntegral
      }

      if (times > outSTimes && times < outETimes) {
        return this.info.exitIntegral
      }

      return 0
    },
    isClock() {
      const times = new Date().getTime()
      const inSTimes = new Date(this.info.intoBegintime?.replaceAll('-', '/')).getTime()
      const inETimes = new Date(this.info.intoEndtime?.replaceAll('-', '/')).getTime()
      const outSTimes = new Date(this.info.exitBegintime?.replaceAll('-', '/')).getTime()
      const outETimes = new Date(this.info.exitEndtime?.replaceAll('-', '/')).getTime()
      // 不符合条件(任务未开始、已经结束..)
      if (times < inSTimes || times > outETimes || (inETimes < times && times < outSTimes)) {
        return 0
      }
      // 在打卡范围内未打卡
      if (this.info.clockRange > this.distance && (!this.info.intoClock && (inSTimes < times && times < inETimes)) || !this.info.exitClock && (outSTimes < times && times < outETimes)) {
        return 1
      }
      // 已打卡(打卡距离内 && 打卡时间内)
      if(this.info.clockRange > this.distance && (this.info.intoClock && (inSTimes < times && times < inETimes)) || (this.info.exitClock && outSTimes < times && times < outETimes)) {
        return 2
      }
      // 没在指定范围
      if(this.distance > this.info.clockRange) {
        return 3
      }
      // 在打卡范围内，没有积分
      if (this.info.clockRange > this.distance && (this.info.intoClock && (inSTimes < times && times < inETimes) && this.info.intoIntegral) || (this.info.exitClock && outSTimes < times && times < outETimes) && !this.info.exitIntegral) {
        return 4
      }
    },
    scope() {
      const times = new Date().getTime()
      const inSTimes = new Date(this.info.intoBegintime?.replaceAll('-', '/')).getTime() // 进场开始
      const inETimes = new Date(this.info.intoEndtime?.replaceAll('-', '/')).getTime() // 进场结束
      const outSTimes = new Date(this.info.exitBegintime?.replaceAll('-', '/')).getTime() // 离场开始
      const outETimes = new Date(this.info.exitEndtime?.replaceAll('-', '/')).getTime() // 离场结束

      if (this.info.clockRange > this.distance && (this.info.intoClock && (inSTimes < times && times < inETimes)) || (this.info.exitClock && outSTimes < times && times < outETimes)) {
        return `无法重复打卡`
      }

      if (this.info.clockRange > this.distance && (!this.info.intoClock && (times > inSTimes && times < inETimes)) || !this.info.exitClock && (times > outSTimes && times < outETimes)) {
        return `符合打卡条件`
      }

      return `未到打卡时间/不在指定位置`
    },
    dkqd() {
      const times = new Date().getTime()
      const inSTimes = new Date(this.info.intoBegintime?.replaceAll('-', '/')).getTime() // 进场开始
      const inETimes = new Date(this.info.intoEndtime?.replaceAll('-', '/')).getTime() // 进场结束
      const outSTimes = new Date(this.info.exitBegintime?.replaceAll('-', '/')).getTime() // 离场开始
      const outETimes = new Date(this.info.exitEndtime?.replaceAll('-', '/')).getTime() // 离场结束
      if (this.info.clockRange > this.distance && (this.info.intoClock && (times > inSTimes && times < inETimes)) || (this.info.exitClock && outSTimes < times && times < outETimes)) {
        return `已打卡`
      }
      if (this.info.clockRange > this.distance && (!this.info.intoClock && (times > inSTimes && times < inETimes) && this.info.intoIntegral) || !this.info.exitClock && (times > outSTimes && times < outETimes) && this.info.exitIntegral) {
        return `打卡签到`
      }

      if (times > outSTimes && times < outETimes && !this.info.exitIntegral) {
        return `已打卡`
      }

      return `打卡签到`
    },
    baoming() {
      const times = new Date().getTime()
      const inSTimes = new Date(this.info.intoBegintime).getTime() // 报名开始
      const inETimes = new Date(this.info.intoEndtime).getTime() // 报名结束
      // 1已报名
      if (this.info.enrollClock) {
        return 1
      }
      // 2可以报名
      if (!this.info.enrollClock && times < inETimes && times > inSTimes) {
        return 2
      }
      // 0不符合条件
      return 0
    }
  },
  methods: {
    ...mapActions(['getUserInfo']),
    toAddress() {
      wx.openLocation({
        latitude: this.info.lat,
        longitude: this.info.lng,
        scale: 18
      })
    },
    preview(url) {
      uni.previewImage({
        urls: this.info.files.map(v => v.url),
        current: url
      })
    },
    getDetail() {
      this.$instance.post(`/app/appintegraltask/queryDetailById?id=${this.id}`).then(res=> {
        if(res?.data) {
          this.info = res.data
          this.$nextTick(() => {
            this.getLocation()
          })
        }
      })
    },
    // 打卡积分
    clockIn() {
      if(!this.user.areaId) {
        return this.$dialog.confirm({
          content: '您只有完成信息认证后，才可进行相关操作。',
          confirmText: '去认证'
        }).then(() => {
          this.$linkTo('/mods/AppMine/userInfo')
        }).catch(() => {
        })
      }
      if (!this.latitude) {
        this.$dialog.alert({
          title: '温馨提示',
          content: '您未授权定位，请先授权！'
        }).then(() => {
          this.getLocation()
        }).catch(() => {
        })

        return false
      }

      if (this.isClock == 0 || this.isClock == 3) {
        return this.$dialog.alert({
          title: '温馨提示',
          content: '不满足打卡条件！'
        }).then(() => {
          this.getLocation()
        }).catch(() => {
        })
      }


      if (this.isClock == 2 || this.isClock == 4) {
        return this.$u.toast(`已打卡，请勿重复打卡！`)
      }

      this.flag = true
      this.daKa()
    },
    // 报名积分
    signUp() {
      if(this.info.enrollClock) return

      if(this.baoming==0) {
        return this.$u.toast('不符合报名条件')
      }

      this.flag = true
      this.daKa()
    },
    daKa() {
      this.$instance.post(`/app/appintegraltask/clock`, {
        address: this.address,
        clockTime: this.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        lat: this.latitude,
        lng: this.longitude,
        openId: this.user.openId,
        realName: this.user.realName,
        taskId: this.id,
        type: this.info.type
      }).then(res => {
        if (res?.code == 0) {
          this.flag = false
          if (this.info.type == 1) {
            this.$u.toast('报名成功！')
          } else {
            this.$u.toast('打卡签到成功！')
          }
          setTimeout(()=> {
            this.getDetail()
          }, 400)
        }
      }).catch(err => this.$u.toast(err))
    },
    getLocation() {
      wx.authorize({
        scope: 'scope.userLocation',
        success: () => {
          uni.getLocation({
            type: 'gcj02',
            success: res => {
              this.latitude = res.latitude
              this.longitude = res.longitude
              this.qqmapsdk.reverseGeocoder({
                location: `${res.latitude},${res.longitude}`,
                success: data => {
                  this.address = data.result.formatted_addresses.recommend
                },
                fail: function (info) {
                  console.log(info)
                }
              })

              this.qqmapsdk.calculateDistance({
                from: {
                  longitude: res.longitude,
                  latitude: res.latitude
                },
                to: [{
                  longitude: this.info.lng,
                  latitude: this.info.lat
                }],
                success: res => {
                  this.distance = res.result.elements[0].distance
                },
                fail: function (error) {
                  console.error(error)
                },
                complete: function (res) {
                }
              })
            },
            fail: e => {
              console.log(e)
            }
          })
        },
        fail: () => {
          this.$dialog.confirm({
            content: '您未授权定位，功能将无法使用'
          }).then(() => {
            uni.openSetting({
              success: res => {
                if (!res.authSetting['scope.userLocation']) {
                  this.$dialog.alert({
                    content: '您未授权定位，功能将无法使用'
                  }).then(() => {
                  })
                } else {
                }
              }
            })
          })
        }
      })
    },
    getAuth() {
      this.$nextTick(() => {
        this.token && this.getUserInfo('qujing')
        this.$nextTick(() => {
          this.toAuth()
        })
      })
    },
    toAuth() {
      if (!this.user.areaId) {
        this.$dialog.confirm({
          content: '您只有完成信息认证后，才可进行相关操作。',
          confirmText: '去认证'
        }).then(() => {
          this.$linkTo('/pages/AppMine/userInfo')
        }).catch(() => {
        })
      } else {
        this.getDetail()
        this.showPages = true
      }
    }
  },
  onLoad(o) {
    this.id = o?.id
    if (decodeURIComponent(o.scene) != 'undefined') {
      this.id = decodeURIComponent(o.scene)
    }
    uni.setNavigationBarTitle({
      title: '任务详情'
    });
    this.qqmapsdk = new QQMapWX({
      key: process.env.NODE_ENV == 'production' ? 'RWWBZ-64BEJ-MVLFJ-FTHLQ-JTR6J-SAB2S' : '3RZBZ-LZUCF-CT6J5-NWKZH-FCWOQ-UUFKY'
    })
    this.$dict.load(['fdIntegralTaskType'])
  },
  onShow() {
    if (!this.token) {
      this.$refs.login.show()
    } else {
      this.toAuth()
    }
  }
}
</script>

<style lang="scss" scoped>
.taskDetail {
  padding-bottom: 400px;
  box-sizing: border-box;
  .task,
  .info {
    margin-top: 24px;
    padding: 32px;
    box-sizing: border-box;
    background: #FFF;
    h4 {
      font-size: 34px;
      font-weight: 500;
    }

    p {
      margin-top: 32px;
      font-size: 28px;
      font-weight: 400;
    }

    .imgs {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding-top: 20px;
      box-sizing: border-box;

      image {
        height: 208px;
        width: 33.33%;
        padding-right: 12px;
        margin-bottom: 12px;
        box-sizing: border-box;

        &:nth-of-type(3n) {
          padding-right: 0;
        }
      }
    }
  }
  .info {
    .title {
      font-size: 34px;
      font-weight: 500;
    }
    .items,
    .item {
      display: flex;
      margin-top: 24px;
      img {
        width: 32px;
        height: 32px;
        align-self: center;
        margin-right: 32px;
      }

      .items-info {
        width: calc(100% - 100px);
      }

      .address {
        width: 60px;
        img {
          width: 60px;
          height: 60px;
        }
        i {
          font-size: 24px;
          font-weight: 400;
          color: #687DA6;
          text-align: center;
        }
      }
      .item-info,
      .items-info {
        font-size: 28px;
        font-weight: 400;
        label {
          color: #666666;
        }
        .value {
          color: #333333;
          margin-top: 8px;
        }
      }
    }
  }
  ::v-deep .btn-wrapper {
    background: #FFF;
  }

  ::v-deep .btn-wrapper .btn {
    height: 80px;
    line-height: 80px;
    border-radius: 40px;
  }

  .opacity {
    opacity: 0.6000000238418579 !important;
  }

  .gray {
    background: #b5b5bcff !important;
  }
  .btn-clock {
    height: 372px;
    width: 100%;
    background: #FFF;
    .btn-circle {
      width: 226px;
      height: 226px;
      background: #2D7DFF;
      border-radius: 50%;
      margin: 40px auto 24px;
      text-align: center;
      .text,
      .daka {
        color: #FFF;
        font-size: 34px;
        font-weight: 500;
      }
      .daka {
        padding-top: 62px;
        box-sizing: border-box;
        font-size: 40px;
        font-weight: 500;
      }
    }

    .opacity {
      opacity: 0.6000000238418579 !important;
    }

    .gray {
      background: #b5b5bcff !important;
    }
    .tips {
      text-align: center;
      color: #666666;
      font-size: 28px;
      font-weight: 400;
    }
  }
}
</style>
