<template>
  <view class="task-page">
    <view class="task-header">
      <view class="task-header-title"
        >我的积分<text class="big">{{
          (singInfo && singInfo.total_score) || 0
        }}</text></view
      >
      <view class="task-header-desc">每日签到做任务可领取积分</view>
      <image
        :src="require('@/assets/task/icon-help.png')"
        class="invite-icon"
        @tap="$refs.popup_info.open()"
      ></image>
    </view>
    <view class="task-box">
      <view class="task-box-title">签到得积分</view>
      <template v-if="userInfo && singInfo">
        <view class="task-days">
          <view
            v-for="item in singInfo.data"
            :key="item.date"
            :class="['task-day', { 'task-day-active': !!item.is_signin }]"
          >
            <view class="task-day-integral">{{ item.score }}</view>
            {{ item.day_name }}
          </view>
        </view>
        <button class="task-days-btn" @click="handleSing">
          {{ singInfo.is_current_signin ? "今日已签到" : "立即签到" }}
        </button>
      </template>
      <button v-else class="task-days-btn" @click="handleSing">
        登录签到领积分
      </button>
    </view>
    <view class="task-box">
      <view class="task-box-title">每日任务得积分</view>
      <view v-if="userInfo && singInfo" class="task-list">
        <view
          v-for="item in singInfo.task"
          :key="item.task_id"
          class="task-item"
        >
          <image
            v-if="item.type === 2"
            class="task-item-icon"
            :src="require('@/assets/task/icon-video.png')"
          />
          <image
            v-else
            class="task-item-icon"
            :src="require('@/assets/task/icon-money.png')"
          />
          <view class="task-item-body">
            <view class="task-item-title"
              >{{ item.name
              }}<text class="task-item-label"
                >{{ item.symbol }}{{ item.score }}{{ item.unit }}</text
              ></view
            >
            <view v-if="item.type !== 2" class="task-item-desc"
              >完成 {{ item.finish }}/{{ item.total }}</view
            >
          </view>
          <button
            v-if="item.status === 1"
            class="task-item-btn receive"
            @click="handleReceive(item)"
          >
            去领取
          </button>
          <button v-else-if="item.status === 2" class="task-item-btn disabled">
            已完成
          </button>
          <button v-else class="task-item-btn" @click="handleDoTask(item)">
            去完成
          </button>
        </view>
      </view>
    </view>
    <uni-popup
      ref="popup_info"
      type="center"
      mask-background-color="rgba(0,0,0,0.8)"
      :is-mask-click="true"
    >
      <view class="popup-wrap">
        <view class="popup-content">
          <view class="h1"><text>积分规则</text></view>
          <view class="p" v-html="singInfo.score_info || ''"></view>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="$refs.popup_info.close()"
        ></image>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import api from "@/lib/api/api";
import login from "@/lib/utils/login";
import createShowRewardedVideoAd from "@/lib/utils/showRewardedVideoAd";
import {
  requestSubscribeMessage,
  defaultTemplateIds,
} from "@/lib/utils/wxSubscribe";

export default {
  name: "PageTask",
  data() {
    return {
      userInfo: null,
      singInfo: null,
    };
  },

  onShow() {
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
      this.getTaskInfo();
    }
  },

  methods: {
    async handleShowAd(item) {
      if (!this.showRewardedVideoAd) {
        this.showRewardedVideoAd = createShowRewardedVideoAd();
      }
      try {
        const res = await this.showRewardedVideoAd();

        if (res && res.isEnded) {
          this.adComplete(item);
        }
      } catch (e) {
        uni.showToast({
          icon: "none",
          title: e?.errMsg || "广告播放失败",
          duration: 2e3,
          mask: true,
        });
      }
    },

    async handleSing() {
      if (!this.userInfo || !this.userInfo.session) {
        await this.login();
      }
      if (this.singInfo.is_current_signin) {
        uni.showToast({
          icon: "none",
          title: "今日已签到",
          duration: 2e3,
          mask: true,
        });
        return;
      }
      try {
        // #ifdef MP-WEIXIN
        await requestSubscribeMessage(defaultTemplateIds).catch(() => void 0);
        // #endif

        const data = await api.userNewSingIn({
          session: this.userInfo.session,
        });
        this.singInfo = { ...this.singInfo, ...data };

        if (data.errno === 10000) {
          uni.showToast({
            icon: "success",
            title: "签到成功",
            duration: 2e3,
            mask: true,
          });
        } else {
          uni.showToast({
            icon: "none",
            title: data.errmsg || "签到失败，请重试",
            duration: 2e3,
            mask: true,
          });
        }
      } catch (e) {
        uni.showToast({
          icon: "none",
          title: "签到失败，请重试",
          duration: 2e3,
          mask: true,
        });
      }
    },

    async getTaskInfo() {
      if (!this.userInfo.session) {
        return Promise.reject();
      }
      const data = await api.getTaskInfo(this.userInfo.session);
      data.task = (data.task || []).sort((a, b) => a.sort - b.sort);
      this.singInfo = data;
    },
    login() {
      return new Promise((resolve, reject) => {
        login.wxLogin(async (userInfo) => {
          if (userInfo.session) {
            this.userInfo = userInfo;
            if (userInfo.coupons && userInfo.coupons.is_bind_coupon === 1) {
              uni.showToast({
                icon: "none",
                title: userInfo.coupons.is_bind_info || "登录成功~",
                duration: 2e3,
                mask: true,
              });
              await this.getTaskInfo();

              resolve();
            } else {
              resolve();
            }
          } else reject();
        });
      });
    },
    async adComplete(item) {
      try {
        const data = await api.setAdTask({
          session: this.userInfo.session,
          task_id: `${item.task_id}`,
        });
        if (data.errno === 10000) {
          this.handleReceive(item);
        } else {
          uni.showToast({
            icon: "none",
            title: data.errmsg || "领取失败",
            duration: 2e3,
            mask: true,
          });
        }
      } catch (e) {
        uni.showToast({
          icon: "none",
          title: "领取失败",
          duration: 2e3,
          mask: true,
        });
      }
    },
    handleDoTask(item) {
      if (item.type === 2) {
        this.handleShowAd(item);
      } else {
        uni.switchTab({
          url: "/pages/index/index",
        });
      }
    },
    async handleReceive(item) {
      uni.showLoading({ title: "领取中", mask: true });
      try {
        const data = await api.getTaskScore({
          session: this.userInfo.session,
          task_id: `${item.task_id}`,
        });
        uni.hideLoading();
        if (data.errno === 10000) {
          data.task = (data.task || []).sort((a, b) => a.sort - b.sort);
          this.singInfo = {
            ...this.singInfo,
            ...data,
          };
          uni.showToast({
            icon: "success",
            title: "领取成功",
            duration: 2e3,
            mask: true,
          });
        } else {
          uni.showToast({
            icon: "none",
            title: data.errmsg || "领取失败",
            duration: 2e3,
            mask: true,
          });
        }
      } catch (e) {
        uni.hideLoading();
      }
    },
  },
};
</script>

<style lang="scss">
.task-page {
  width: 100%;
  overflow: hidden;
  background: #f6f6f6;
  min-height: 100vh;

  .task-header {
    box-sizing: border-box;
    width: 830rpx;
    padding: 32rpx 100rpx 148rpx;
    margin-left: -40rpx;
    margin-bottom: -106rpx;
    background: #30303a;
    border-radius: 0 0 148rpx 148rpx;
    box-shadow: 0 0 50rpx rgba($color: #fff, $alpha: 1);
    .task-header-title {
      font-size: 30rpx;
      font-weight: 500;
      color: #ffffff;
      line-height: 52rpx;
      .big {
        font-size: 44rpx;
        font-weight: bold;
        color: #08c2c3;
        margin-left: 10rpx;
      }
    }
    .task-header-desc {
      font-size: 24rpx;
      color: #d1d1d1;
      line-height: 28rpx;
    }
    .invite-icon {
      position: absolute;
      width: 36rpx;
      height: 36rpx;
      right: 36rpx;
      top: 44rpx;
      cursor: pointer;
    }
  }
  .task-box {
    width: 690rpx;
    background: #ffffff;
    margin: 0 auto 20rpx;
    padding: 30rpx;
    box-sizing: border-box;
  }
  .task-box-title {
    height: 54rpx;
    font-size: 42rpx;
    font-family: ysbth;
    color: #000000;
    line-height: 54rpx;
    margin-bottom: 12rpx;
  }
  .task-days {
    display: flex;
    justify-content: space-between;
    padding-top: 50rpx;
    .task-day {
      width: 94rpx;
      height: 96rpx;
      border-radius: 8rpx;
      background: #f9f9f9;
      font-size: 20rpx;
      color: #888888;
      line-height: 23rpx;
      text-align: center;
      box-shadow: inset 0 0 2rpx rgba($color: #000000, $alpha: 0.15);

      .task-day-integral {
        margin: -28rpx auto 14rpx;
        width: 68rpx;
        height: 68rpx;
        background: url(@/assets/task/icon-sign.png) no-repeat;
        background-size: contain;
        display: flex;
        align-items: center;
        justify-content: center;

        font-size: 30rpx;
        font-family: Helvetica Neue-Bold, Helvetica Neue;
        font-weight: bold;
        color: #ffffff;
        line-height: 35rpx;
      }
      &.task-day-active {
        background: linear-gradient(180deg, #fffceb 0%, #fffaf0 100%);
        color: #f2ab24;
        .task-day-integral {
          background-image: url(@/assets/task/icon-signed.png);
          color: #ffffe2;
          text-shadow: 0px 0px 2rpx #c18214;
        }
      }
    }
  }
  .task-days-btn {
    &::after {
      display: none;
    }
    width: 630rpx;
    height: 92rpx;
    background: url(@/assets/task/btn.png) no-repeat;
    background-size: contain;
    font-size: 32rpx;
    font-weight: bold;
    color: #292d3b;
    line-height: 38rpx;
    line-height: 92rpx;
    text-align: center;
    margin: 34rpx auto 0;
  }
  .task-list {
    .task-item {
      padding: 30rpx 0;
      display: flex;
      border-bottom: 2rpx solid #f5f5f5;
      align-items: center;
      &:last-child {
        border-bottom: 0;
        padding-bottom: 0;
      }
      .task-item-icon {
        width: 80rpx;
        height: 80rpx;
        margin-right: 26rpx;
      }
      .task-item-btn {
        box-sizing: border-box;
        width: 130rpx;
        height: 56rpx;
        background: #08c2c3;
        margin-left: 26rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        font-weight: 600;
        color: #292d3b;
        line-height: 28rpx;
        border-radius: 0;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        &::after {
          display: none;
        }
        &.receive {
          background: #ffffff;
          border: 2rpx solid #22c8c9;
          color: #22c8c9;
        }
        &.disabled {
          background: #c8c8c8;
          color: #ffffff;
        }
      }
      .task-item-body {
        flex: 1;
        width: 0;
      }
      .task-item-title {
        height: 40rpx;
        font-size: 28rpx;
        font-weight: 500;
        color: #000000;
        line-height: 40rpx;
      }
      .task-item-label {
        margin-left: 16rpx;
        color: #17c6c7;
      }
      .task-item-desc {
        height: 34rpx;
        font-size: 24rpx;
        font-weight: 400;
        color: #888888;
        line-height: 34rpx;
      }
    }
  }
}
</style>
