<template>
  <div class="Activity" v-if="pageShow">
    <div class="section">
      <h2>{{ info.title }}</h2>
      <p>{{ info.detail }}</p>
    </div>
    <div class="section">
      <h2>基础信息</h2>
      <div class="info-wrapper">
        <div class="info-item">
          <h2>活动地点</h2>
          <span class="omit">{{ info.address }}</span>
          <div class="right" @click="toAddress">
            <image src="https://cdn.cunwuyun.cn/wxmp/tianfuxing/dh.png" />
            <i>导航</i>
          </div>
        </div>
        <div class="info-item">
          <h2>进场打卡</h2>
          <div class="right-time">
            <p>{{ info.intoBegintime }}  至</p>
            <p>{{ info.intoEndtime }}</p>
          </div>
        </div>
        <div class="info-item">
          <h2>离场打卡</h2>
          <div class="right-time">
            <p>{{ info.exitBegintime }}  至</p>
            <p>{{ info.exitEndtime }}</p>
          </div>
        </div>
      </div>
    </div>
    <div class="section" v-if="info.intoClock || info.exitClock">
      <h2>打卡信息</h2>
      <div class="info-wrapper">
        <div class="info-item">
          <h2>进场打卡时间</h2>
          <span class="omit">{{ info.intoClock.clockTime || '-' }}</span>
        </div>
        <div class="info-item">
          <h2>离场打卡时间</h2>
          <span>{{ info.exitClock.clockTime || '-' }}</span>
        </div>
      </div>
    </div>
    <div class="signin">
      <div class="top" @click="toSign" :class="[isClock ? '' : 'disable']">
        <h2>打卡签到</h2>
        <span v-if="isClock">积分+{{ intoIntegral }}</span>
      </div>
      <p v-if="isClock">符合打卡条件</p>
      <i v-else>未到打卡时间/不在指定位置</i>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
  var QQMapWX = require('./libs/qqmap-wx-jssdk.js')
  export default {
    name: 'AppActivity',
    appName: '活动',

    data () {
      return {
        id: '',
        info: {},
        qqmapsdk: null,
        pageShow: false,
        latitude: '',
        longitude: '',
        address: '',
        distance: 100000
      }
    },

    computed: {
      ...mapState(['token']),
      isClock () {
        if (!this.info.id) {
          return false
        }

        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 && (times > outSTimes && times < outETimes)) {
          return true
        }

        return false
      },

      intoIntegral () {
        if (!this.info.id) {
          return 0
        }

        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.intoClock && (times > inSTimes && times < inETimes)) {
          return this.info.intoIntegral
        }

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

        return 0
      }
    },

    onShow () {
      this.getInfo()
    },

    onLoad (query) {
      if (decodeURIComponent(query.scene)) {
        this.id = decodeURIComponent(query.scene)
      }

      if (query.id) {
        this.id = query.id
      }

      if (this.token) {
        this.getInfo()
      } else {
        this.autoLogin().then(() => {
          this.getInfo()
        })
      }

      this.qqmapsdk = new QQMapWX({
        key: process.env.NODE_ENV == 'production' ? 'RWWBZ-64BEJ-MVLFJ-FTHLQ-JTR6J-SAB2S' : '3RZBZ-LZUCF-CT6J5-NWKZH-FCWOQ-UUFKY'
      })
    },

    methods: {
      ...mapActions(['autoLogin']),

      getInfo () {
        this.$loading()
        this.$instance.post(`/api/appactivityinfo/queryDetailById?id=${this.id}`).then(res => {
          if (res.code === 0) {
            this.info = res.data

            this.$nextTick(() => {
              this.getLocation()
              this.pageShow = true
            })
          }
        })
      },

      toSign () {
        if (!this.latitude) {
          this.$dialog.alert({
            title: '温馨提示',
            content: '您未授权定位，请先授权！'
          }).then(() => {
            this.getLocation()
          }).catch(() => {
          })

          return false
        }

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

          return false
        }

        this.$loading()
        let type = 0
        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.intoClock && (times > inSTimes && times < inETimes)) {
          type = 0
        }

        if (!this.info.exitClock && (times > outSTimes && times < outETimes)) {
          type = 1
        }
        this.$instance.post(`/api/appactivityinfo/clock`, {
          address: this.address,
          activityId: this.id,
          clockTime: this.$dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),
          lat: this.latitude,
          lng: this.longitude,
          type
        }).then(res => {
          if (res.code === 0) {
            this.$toast('打卡成功')

            this.getInfo()
          }

          this.$hideLoading()
        }).catch(() => {
          this.$hideLoading()
        })
      },

      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 => {
                    console.log(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 {
                  }
                }
              })
            })
          }
        })
      },

      toAddress () {
        wx.openLocation({
          latitude: this.info.lat,
          longitude: this.info.lng,
          scale: 18
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .Activity {
    padding-top: 16px;
    padding-bottom: 80px;

    div {
      box-sizing: border-box;
    }

    .section {
      width: 718px;
      margin: 0 auto 24px;
      padding: 32px;
      background: #FFFFFF;
      border-radius: 32px;
      box-sizing: border-box;

      & > h2 {
        margin-bottom: 24px;
        font-weight: 600;
        font-size: 40px;
        color: #222222;
      }

      p {
        line-height: 1.3;
        font-size: 32px;
        color: #999;
        text-align: justify;
      }

      .info-wrapper {
        .info-item {
          display: flex;
          line-height: 1.2;
          margin-bottom: 24px;

          &:last-child {
            margin-bottom: 0;
          }

          h2 {
            margin-right: 40px;
            color: #999999;
            font-size: 28px;
          }

          span, p {
            flex: 1;
            color: #333333;
            font-size: 28px;
            text-align: justify;
          }

          p {}

          .omit {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap
          }

          .right {
            display: flex;
            align-items: center;
            margin-left: 20px;

            image {
              width: 32px;
              height: 32px;
              margin-right: 8px;
            }

            i {
              color: #687DA6;
              font-size: 28px;
            }
          }
        }
      }
    }

    .signin {
      margin-top: 60px;
      text-align: center;

      p {
        color: #999;
        font-size: 28px;
      }

      i {
        display: block;
        color: #FF883C;
        font-size: 28px;
      }

      .top {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        width: 240px;
        height: 240px;
        margin: 0 auto 48px;
        background-image: linear-gradient(180deg, #75BDFF 0%, #4783FF 100%);
        border: 8px solid #FFFFFF;
        box-shadow: 0 8px 12px -4px rgba(133,196,255,0.65);
        border-radius: 50%;

        &.disable {
          border-color: #D5DCEA;
          background-image: none;

          h2 {
            color: #ADB9D1;
          }
        }

        h2 {
          color: #fff;
          font-size: 40px;
        }

        span {
          margin-top: 20px;
          color: rgba(255, 255, 255, 0.8);
          font-size: 28px;
        }
      }
    }
  }
</style>
