<template>
  <view class="act-deltail-main"
        :style="{paddingBottom: `${footerHeight}rpx`}">
    <network-error />
    <view class="over-view">
      <image class="detail-img"
             :src="detail.imgs"
             mode="aspectFill"></image>
      <view class="detail-over">
        <text class="detail-title u-line-2 u-font-40 line-56 u-tips-color bold">【{{detail.activity_type | activityTyepFilter}}】{{detail.title}}</text>
        <view class="u-flex u-col-bottom u-p-t-24 u-p-b-14 u-border-bottom">
          <text class="u-primary-color u-font-28 line-40">返利：</text>
          <block v-if="detail.activity_type === 1">
            <text class="u-flex-1 u-primary-color u-font-36 line-50 bold">实付全返</text>
          </block>
          <block v-if="detail.activity_type === 2">
            <view class="u-flex-1 u-primary-color bold">
              <text class="u-font-28 line-40">¥</text>
              <text class="u-font-36 line-50">{{(detail.rebate_amount / 100).toFixed(2)}}</text>
            </view>
          </block>
          <text class="u-primary-color u-font-24 line-34">{{detail.join_count - detail.join_number}}</text>
          <text class="u-content-color u-font-24 line-34">剩余名额</text>
        </view>
        <view class="u-flex u-row-between u-p-t-22 line-34">
          <text class="u-content-color">{{detail.join_number}}已参与</text>
          <button class="share-btn u-primary-color u-font-24 line-34"
                  open-type="share">分享活动</button>
        </view>
      </view>
    </view>
    <view class="shop-info u-m-t-16">
      <view class="u-font-36 line-50 u-tips-color bold">店铺信息</view>
      <view class="u-flex">
        <view class="u-flex-1 u-p-r-32">
          <text class="shop-name u-font-28 u-tips-color line-40 u-line-1">【{{detail.plat_type | platFilter}}】{{detail.shop_name}}</text>
          <view class="u-flex"
                @click="openMap">
            <view class="icon-map-wh icon-map"></view>
            <view class="u-content-color u-m-l-8 u-m-r-16">{{(detail.distance / 1000).toFixed(1)}}km</view>
            <text class="shop-address u-flex-1 u-content-color u-line-1">{{detail.shop_address}}</text>
          </view>
        </view>
        <view class="divider-right"></view>
        <block v-if="detail.plat_type === 8">
          <view class="to-btn u-p-l-28"
                @click="openOtherApplte()">
            <view class="icon-mt-wh icon-elm"></view>
            <view class="u-m-t-2 u-font-22 u-content-color line-32">打开饿了么</view>
          </view>
        </block>
        <block v-if="detail.plat_type === 9">
          <view class="to-btn u-p-l-28"
                @click="openOtherApplte()">
            <view class="icon-mt-wh icon-mt"></view>
            <view class="u-m-t-2 u-font-22 u-content-color line-32">打开美团</view>
          </view>
        </block>
      </view>
    </view>
    <view class="act-able-time u-m-t-16">
      <view class="u-font-36 line-50 u-tips-color bold">活动可用时间</view>
      <view class="u-flex">
        <text class="u-flex-1 u-content-color line-40 u-line-2 u-p-r-32">{{businessHours}}营业时间可用（当天参与报名，需当天提交资料才能有效返款）</text>
        <view class="divider-right"></view>
        <button class="to-btn contact-btn u-p-l-28"
                open-type="contact">
          <view class="icon-phone-wh icon-phone"></view>
          <view class="u-m-t-2 u-font-22 u-content-color line-32">联系客服</view>
        </button>
      </view>
    </view>
    <view class="act-desc u-m-t-16">
      <view class="act-tabs u-border-bottom">
        <u-tabs :is-scroll="false"
                :list="[{name: '活动规则'}, {name: '评价要求'}]"
                :current="currentTab"
                height="104"
                font-size="30"
                active-color="#FF6632"
                inactive-color="#111111"
                :bar-style="{
            bottom: '-4rpx',
            marginLeft: '-40rpx',
            width: '120rpx',
            height: '6rpx',
            borderRadius: 0,
            backgroundColor: 'linear-gradient(270deg, #FFB76B 0%, #FE4028 100%)'
          }"
                @change="changeTab">
        </u-tabs>
      </view>
      <view class="u-m-b-18 u-p-t-32 u-p-b-32">
        <block v-if="currentTab === 0">
          <block v-for="(item, index) in detail.content"
                 :key="index">
            <img-text :value="item.content"
                      :type="item.contentType"></img-text>
          </block>
        </block>
        <block v-else>
          <img-text :value="detail.requirement"
                    type="1"></img-text>
        </block>
      </view>
    </view>
    <block v-if="status">
      <fixed-bottom @get-height="getFooterHeight">
        <view class="bottom-footer u-flex">
          <block v-if="status * 1 === 1 || status * 1 === 2">
            <view class="u-flex-1">
              <view class="line-34 bold">距活动结束还有：</view>
              <view class="u-font-20 u-content-color line-28">{{remainingTime}}</view>
            </view>
            <block v-if="status * 1 === 1">
              <button class="sign-up-btn u-font-30 bold line-42"
                      @click="join">我要报名</button>
            </block>
            <block v-if="status * 1 === 2">
              <view class="u-flex">
                <button class="canel-btn u-font-28 line-40"
                        @click="cancelJoin">取消报名</button>
                <button class="submit-btn u-font-28 line-40 u-m-l-16"
                        @click="toSubmiteOrder">提交结果</button>
              </view>
            </block>
          </block>
          <block v-if="status * 1 === 3 || status * 1 === 4">
            <block v-if="status * 1 === 3">
              <view class="u-flex-1">
                <view class="line-34 bold">等待审核：</view>
                <view class="u-font-20 u-content-color line-28">审核通过后将获得返利金额</view>
              </view>
            </block>
            <block v-if="status * 1 === 4">
              <view class="u-flex-1">
                <view class="line-34 bold">审核通过：</view>
                <view class="u-font-20 u-content-color line-28">返利金额将在第二日到账</view>
              </view>
            </block>
            <button class="sign-up-btn u-font-30 bold line-42"
                    disabled>已提交</button>
          </block>
          <block v-if="status * 1 === 5">
            <view class="u-flex-1">
              <view class="line-34 bold">审核驳回：</view>
              <view class="u-font-20 u-content-color line-28">{{detail.reject_reason}}</view>
            </view>
          </block>
          <block v-if="status * 1 === 6">
            <button class="end-btn u-m-l-12"
                    disabled>已结束</button>
          </block>
          <block v-if="status * 1 === 7">
            <button class="end-btn u-m-l-12"
                    disabled>已抢光</button>
          </block>
        </view>
      </fixed-bottom>
    </block>
  </view>
</template>

<script>
import fixedBottom from '@/components/fixedBottom'
import imgText from '@/components/imgText'
import { getActivityDetail } from '@/api/activityApi'
import { editJoinActivity } from '@/api/userApi'
export default {
  components: { fixedBottom, imgText },
  data () {
    return {
      showErr: false,
      errMsg: '',
      nowTime: '',
      timer: null,
      footerHeight: 0,
      currentTab: 0,
      activityId: '',
      recordId: '',
      detail: {
        imgs: '',
        activity_type: '',
        title: '',
        rebate_amount: '',
        join_count: 0,
        join_number: 0,
        plat_type: '',
        shop_name: '',
        distance: 0,
        shop_address: '',
        join_status: '',
        start_time: '',
        end_time: ''
      }
    }
  },
  computed: {
    userId () {
      return this.$store.state.userInfo.token
    },
    businessHours () {
      const date = this.$dayjs(`${this.detail.start_date}`).format('YYYY年MM月DD日')
      const start = this.$dayjs(`${this.detail.start_date} ${this.detail.start_time}`).format('HH:mm')
      const end = this.$dayjs(`${this.detail.end_date} ${this.detail.end_time}`).format('HH:mm')
      return `${date} ${start}-${end}`
    },
    status () {
      if (this.detail.join_status === 1) {
        return 2
      } else if (this.detail.join_status === 2) {
        return 3
      } else if (this.detail.join_status === 3) {
        return 4
      } else if (this.detail.join_status === 4) {
        return 5
      } else if (this.detail.join_status === 5) {
        return 1
      } else if (this.detail.join_status === 6) {
        return 6
      } else if (this.remainingTime === 0) {
        return 6
      } else if (this.detail.join_count === this.detail.join_number && this.detail.join_count) {
        return 7
      } else if (this.detail.join_status === 0) {
        return 1
      } else {
        return 0
      }
    },
    remainingTime () {
      if (!this.detail.end_time) { return }
      const endTime = this.$dayjs(`${this.$dayjs().format('YYYY-MM-DD')} ${this.detail.end_time}`)
      if (isNaN(endTime.diff(this.nowTime, 's'))) { return }
      if (!isNaN(endTime.diff(this.nowTime, 's')) && endTime.diff(this.nowTime, 's') === 0) {
        clearTimeout(this.timer)
        return 0
      }
      return this.$dayjs(endTime.diff(this.nowTime)).subtract(8, 'h').format('HH小时mm分ss秒')
    }
  },
  watch: {
    userId (e) {
      if (!e) {
        uni.navigateTo({
          url: '/pagesSub/other/login'
        })
      }
    }
  },
  onLoad (options) {
    this.activityId = options.id
    this.recordId = options.record_id
  },
  onShow () {
    if (!this.userId) {
      uni.navigateTo({
        url: '/pagesSub/other/login'
      })
      return
    }
    this.getDetailData()
    this.reNowTime()
  },
  onHide () {
    clearTimeout(this.timer)
  },
  onError () {
    clearTimeout(this.timer)
  },
  onPullDownRefresh () {
    clearTimeout(this.timer)
    this.getDetailData()
    this.reNowTime()
  },
  onPageNotFound () {
    clearTimeout(this.timer)
  },
  onShareAppMessage (res) {
    const title = `${this.detail.activity_type === 1 ? '【免费吃】' : '【返利餐】'}${this.detail.title}`
    return {
      title: title,
      path: `/pagesSub/activity/activityDetail?id=${this.detail.id}`,
      imageUrl: this.detail.imgs
    }
  },
  methods: {
    reNowTime () {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.nowTime = this.$dayjs()
        this.reNowTime()
      }, 1000)
    },
    // 获取用户经纬度
    getLocation () {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          success: (res) => {
            resolve(res)
          },
          fail: () => {
            resolve(false)
          }
        })
      })
    },
    // 获取活动详情
    async getDetailData () {
      const location = await this.getLocation()
      if (!location) { return }
      const params = {
        id: this.activityId,
        lng: location.longitude,
        lat: location.latitude
      }
      if (this.recordId) {
        params.record_id = this.recordId
      }
      const { code, data } = await getActivityDetail(params)
      if (code === 200) {
        this.detail = data
      }
      uni.stopPullDownRefresh()
    },
    // 报名活动/取消报名
    async joinActivity (type) {
      const params = {
        id: this.detail.id,
        type: type
      }
      const { code, msg } = await editJoinActivity(params)
      if (code === 200) {
        if (type === 1) {
          uni.navigateTo({
            url: `/pagesSub/activity/signUpOutcome?endTime=${this.detail.end_time}&platType=${this.detail.plat_type}`
          })
        } else {
          this.getDetailData()
        }
      } else {
        uni.showToast({
          title: msg,
          icon: 'none'
        })
      }
    },
    getFooterHeight (h) {
      this.footerHeight = h * 2
    },
    changeTab (index) {
      this.currentTab = index
    },
    openMap () {
      uni.openLocation({
        latitude: this.detail.shop_lat,
        longitude: this.detail.shop_lng
      })
    },
    // 我要报名
    join () {
      // uni.requestSubscribeMessage({
      //   tmplIds: [''],
      //   success: (res) => {
      //     this.joinActivity(1)
      //   }
      // })
      this.joinActivity(1)
    },
    // 取消报名
    cancelJoin () {
      uni.showModal({
        title: '提示',
        content: '确定取消报名',
        confirmColor: '#1677FF',
        cancelColor: '#1677FF',
        success: (res) => {
          if (res.confirm) {
            this.joinActivity(2)
          }
        }
      })
    },
    // 提交结果
    toSubmiteOrder () {
      uni.navigateTo({
        url: `/pagesSub/order/submitOrder?activityId=${this.detail.id}&userActivityId=${this.detail.user_activity_id}`
      })
    },
    openOtherApplte () {
      uni.navigateToMiniProgram({
        appId: this.detail.app_info.appid,
        path: this.detail.app_info.path
      })
    }
  },
  filters: {
    activityTyepFilter (e) {
      const typeList = {
        1: '免费吃',
        2: '返利餐'
      }
      return typeList[e] || ''
    },
    platFilter (e) {
      const platList = {
        8: '饿了么',
        9: '美团'
      }
      return platList[e] || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.act-deltail-main {
  .over-view {
    .detail-img {
      width: 100%;
      height: 424px;
      font-size: 0;
    }
    .detail-over {
      padding: 24px 40px 28px;
      background-color: #fff;
    }
    .detail-title {
      max-width: 670px;
    }
    .share-btn {
      margin: 0;
      padding-right: 0;
      background-color: #fff;
      &::after {
        border-color: transparent;
      }
    }
  }
  .act-able-time,
  .shop-info {
    padding: 32px 40px 28px;
    background-color: #fff;
    .shop-name {
      display: inline-block;
      margin: 16px 0;
      max-width: 510px;
    }
    .shop-address {
      display: inline-block;
      max-width: 396px;
    }
    .to-btn {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .contact-btn {
      padding-right: 0;
      background-color: #fff;
      &::after {
        border-color: transparent;
      }
    }
    .icon-map-wh {
      width: 20px;
      height: 24px;
    }
    .icon-phone-wh,
    .icon-elm-wh,
    .icon-mt-wh {
      width: 56px;
      height: 56px;
    }
    .divider-right {
      width: 2px;
      height: 54px;
      background-color: $u-border-color;
    }
  }
  .act-desc {
    padding: 0 40px;
    background-color: #fff;
  }
  .bottom-footer {
    padding: 16px 40px 16px 28px;
    width: 100%;
    background-color: #fff;
    .sign-up-btn {
      padding: 24px 128px;
      width: 374px;
      height: 88px;
      border-radius: 44px;
      color: #fff;
      background-color: $u-type-primary;
      white-space: nowrap;
    }
    .canel-btn,
    .submit-btn {
      padding: 16px 40px;
      width: 192px;
      height: 72px;
      border-radius: 36px;
    }
    .canel-btn {
      position: relative;
      color: $u-type-primary;
      background-color: #fff;
      &::after {
        content: '';
        display: flex;
        align-items: center;
        width: 200%;
        height: 200%;
        border: 2px solid $u-type-primary;
        border-radius: 72px;
        box-sizing: border-box;
        pointer-events: none;
        transform-origin: 0 0;
      }
    }
    .submit-btn {
      color: #fff;
      background-color: $u-type-primary;
    }
    .end-btn {
      width: 670px;
      height: 88px;
      border-radius: 44px;
    }
  }
}
button[disabled] {
  color: #fff !important;
  background-color: #d3d4d5 !important;
}
button[disabled]::after {
  border-color: transparent;
}
</style>

<style >
.act-tabs >>> .u-tab-item + .u-tab-item {
  margin-left: 42px;
}
</style>
