<template>
  <view class="content yfs-page">
    <view v-if="info" class="yfs-wrap">
      <view class="yfs-media">
        <image class="yfs-image" :src="info.img" mode="aspectFill"></image>
        <view v-if="info.play_type !== 3" class="yfs-media-bar">
          <view class="yfs-media-title"
            ><text>&yen;</text
            ><text class="big">{{ info.show_price }}</text></view
          >
          <view
            v-if="
              Number(info.source_price) &&
              Number(info.show_price) < Number(info.source_price)
            "
            class="yfs-media-desc"
            >&yen;{{ info.source_price }}</view
          >
        </view>
      </view>
      <view v-if="info.play_type === 3" class="yfs-body">
        <view class="yfs-title">{{ info.name }}</view>
        <view class="yfs-price">
          <text class="yfs-price-small">&yen;</text>
          <text class="yfs-price-big">{{ info.show_price }}</text>
          <text
            v-if="
              info.source_price &&
              Number(info.source_price) > Number(info.show_price)
            "
            class="yfs-price-origin"
            >{{ info.source_price }}</text
          >
        </view>
        <view class="yfs-media-avatars">
          <view
            v-if="wxsUsers && wxsUsers.data && wxsUsers.data.length"
            class="yfs-queue-avatars"
          >
            <view v-if="wxsUsers.num > 7" class="yfs-queue-more">···</view>
            <image
              v-for="item in wxsUsers.data"
              :key="item.id"
              class="yfs-queue-avatar"
              :src="item.avatar"
            ></image>
          </view>
          <view class="yfs-media-avatars-label">{{ wxsUsers.info }}</view>
        </view>
        <view class="yfs-float-rule" @click="handlePopupShow('popup_rule')"
          >规则说明</view
        >
      </view>
      <view v-else class="yfs-body">
        <view class="yfs-title">{{ info.name }}</view>
        <view class="yfs-control">
          <button
            class="yfs-control-btn"
            :disabled="!info.pre_kuji"
            @click="handleToId(info.pre_kuji)"
          >
            <image
              src="@/assets/icon/icon-prev.png"
              class="yfs-control-icon"
            ></image>
            <text>上一箱</text>
          </button>
          共 {{ info.curr_batch_num }}/{{ info.batch_num }} 箱
          <button
            class="yfs-control-btn"
            :disabled="!info.next_kuji"
            @click="handleToId(info.next_kuji)"
          >
            <text>下一箱</text>
            <image
              src="@/assets/icon/icon-next.png"
              class="yfs-control-icon"
            ></image>
          </button>
        </view>
        <view class="yfs-progress">
          <view class="yfs-progress-innter" :style="progressStyle"></view>
        </view>
        <view class="yfs-bottom">
          <view class="yfs-bottom-left"
            >剩余{{ info.curr_num }}/{{ info.total_num }}发</view
          >
          <view class="yfs-bottom-right" @click="handlePopupShow('popup_rule')"
            >规则说明<image
              src="@/assets/icon/icon-help.png"
              class="yfs-bottom-icon"
            ></image
          ></view>
        </view>
      </view>
    </view>
    <view v-else class="yfs-wrap">
      <view class="yfs-media skeleton"></view>
      <view class="yfs-body">
        <view class="yfs-title skeleton"></view>
        <view class="yfs-control skeleton"></view>
        <view class="yfs-progress skeleton"></view>
        <view class="yfs-bottom">
          <view class="yfs-bottom-left skeleton"></view>
          <view class="yfs-bottom-right skeleton"></view>
        </view>
      </view>
    </view>
    <view class="yfs-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        :class="['yfs-tab', { 'yfs-tab-active': tab.key === currentTab }]"
        @click="handleTabClick(tab.key)"
        >{{ tab.title }}</view
      >
    </view>
    <view v-show="currentTab === 'list'" class="yfs-list">
      <template v-if="info && info.relations && info.play_type === 3">
        <level-item
          v-for="item in info.relations"
          :key="item.level"
          class="level-item"
          :item="item"
          @click="handleShowImages"
        ></level-item>
      </template>
      <template v-else-if="info && info.relations">
        <yfs-item
          v-for="item in info.relations"
          :key="item.id"
          :item="item"
          class="yfs-list-item"
          @click="handleShowImages"
        />
      </template>
      <template v-else>
        <yfs-item v-for="n in 9" :key="n" class="yfs-list-item" />
      </template>
    </view>
    <view v-show="currentTab === 'record'" class="yfs-record-list">
      <template v-if="info.play_type === 3">
        <view class="yfs-lable-tabs">
          <view
            v-for="item in listsArr"
            :key="item.key"
            :class="['yfs-lable-tab', { active: currentList.key === item.key }]"
            @click="handleTagClick(item.key)"
          >
            {{ item.title }}
          </view>
        </view>
        <template v-if="currentList.list.length">
          <yfs-result-item
            v-for="item in currentList.list"
            :key="item.id"
            :item="item"
            :play-type="info.play_type"
            class="yfs-list-item"
          />
        </template>
        <view v-else class="nodata">暂无抽赏记录</view>
      </template>
      <template v-else-if="payList">
        <template v-if="payList.relations.length">
          <yfs-record-item
            v-for="item in payList.relations"
            :key="item.id"
            :item="item"
            class="yfs-list-item"
          />
        </template>
        <view v-else class="nodata">暂无抽赏记录</view>
      </template>
      <template v-else>
        <yfs-record-item v-for="n in 10" :key="n" class="yfs-list-item" />
      </template>
    </view>
    <view v-if="!isLogin" class="yfs-footer">
      <view class="yfs-cd-bar">
        <view class="yfs-cd-main">登录后可查看更多信息</view>
      </view>
      <view class="yfs-footer-main">
        <button class="yfs-login-btn" @click="handleLogin"></button>
      </view>
    </view>
    <view v-else class="yfs-footer">
      <view
        v-if="lineInfo.is_line_up && lineInfo.is_curr_user"
        class="yfs-cd-bar"
      >
        <view class="yfs-cd-main">
          {{ cdText }}<text class="yfs-cd-time">{{ cdTime }}</text>
        </view>
        <button class="yfs-cd-exit" @click="handleRemoveLine">退出队列</button>
      </view>
      <view v-else-if="lineInfo" class="yfs-cd-bar">
        <view class="yfs-cd-main">
          {{ lineInfo.msg || "" }}
        </view>
        <button
          v-if="lineInfo.is_line_up"
          class="yfs-cd-exit"
          @click="handleRemoveLine"
        >
          退出队列
        </button>
      </view>
      <!--  -->
      <buy-btns
        v-if="!lineInfo || !lineInfo.is_queue || lineInfo.is_curr_user"
        class="yfs-footer-main"
        :user-info="userInfo"
        :buy-btns="computedBtns"
        @login="handleUpdateUserInfo"
        @click="handleBtnsClick"
      ></buy-btns>
      <view v-else class="yfs-footer-main">
        <view class="yfs-queue-avatars">
          <view v-if="lineInfo.images.length > 7" class="yfs-queue-more"
            >···</view
          >
          <image
            v-for="item in lineImages"
            :key="item"
            class="yfs-queue-avatar"
            :src="item"
          ></image>
        </view>
        <button
          v-if="!lineInfo.is_line_up"
          class="yfs-queue-btn"
          @click="handleJoin"
        >
          我要排队
        </button>
        <button v-else class="yfs-queue-btn">排队中</button>
      </view>
    </view>
    <view class="yfs-fixed-btns">
      <button
        v-if="
          isLogin &&
          lineInfo &&
          lineInfo.queue_kuji_id !== '0' &&
          lineInfo.queue_kuji_id !== lineInfo.kuji_id
        "
        class="yfs-fixed-btn"
        @click="handleToId(lineInfo.queue_kuji_id)"
      >
        返回排队
      </button>
      <button class="yfs-fixed-btn" @click="refresh(true)">
        <image
          src="@/assets/icon/icon-refresh.png"
          :class="[
            'yfs-icon-refresh',
            {
              'yfs-icon-refresh-anim': loading,
            },
          ]"
        ></image
        >刷新
      </button>
      <button
        class="yfs-fixed-btn"
        @click="handleToLink('/pages/order/unsend')"
      >
        寄存柜
      </button>
      <button class="yfs-fixed-btn" open-type="share">分享</button>
    </view>
    <uni-popup
      ref="popup_rule"
      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="info.play_info || ''"></view>
        </view>
        <image
          class="popup_close"
          :src="require('@/assets/icon/icon-close.png')"
          @click="handlePopupClose('popup_rule')"
        ></image>
      </view>
    </uni-popup>
    <popup-img-detail ref="imgdetail" />
    <paypop
      v-if="info"
      ref="paypop"
      :title="info.name"
      :img="info.img"
      :detail-id="id"
      :type="info && info.play_type ? info.play_type : 1"
      :score-text="info.score_info"
      :is-score="!!info.is_score"
      :cd-text="cdText"
      :cd-time="cdTime"
      @paySuccess="handlePaySuccess"
    />
    <payresult
      v-if="info"
      ref="payresult"
      :type="2"
      :cd-text="cdText"
      :cd-time="cdTime"
      @buy="handleBuy"
    />
    <popup-dialog ref="popupDialog" />
  </view>
</template>

<script>
import Decimal from "decimal.js";
import api from "@/lib/api/api";
import login from "@/lib/utils/login";
import yfsItem from "@/components/yfs-item/yfs-item.vue";
import LevelItem from "@/components/level-item/level-item.vue";
import yfsRecordItem from "@/components/yfs-record-item/yfs-record-item.vue";
import yfsResultItem from "@/components/yfs-result-item/yfs-result-item.vue";
import popupImgDetail from "@/components/popup-img-detail/popup-img-detail.vue";
import popupDialog from "@/components/popup-dialog/popup-dialog.vue";
import buyBtns from "@/components/buy-btns/buy-btns.vue";
import {
  reqSubMsg,
  queueTemplateId,
  reqAcceptSubMsgs,
  defaultTemplateIds,
} from "@/lib/utils/wxSubscribe";
import paypop from "components/paypop/paypop.vue";
import payresult from "components/payresult/payresult.vue";
import jumpToUrl from "@/lib/utils/jumpToUrl";

function resetLists() {
  return {
    all: {
      title: "全部",
      key: "all",
      hasMore: true,
      loading: false,
      status: 0,
      page: 1,
      list: [],
    },
    ssr: {
      title: "SSR/SP",
      key: "ssr",
      hasMore: true,
      loading: false,
      status: 1,
      page: 1,
      list: [],
    },
    sr: {
      title: "SR",
      key: "sr",
      hasMore: true,
      loading: false,
      status: 2,
      page: 1,
      list: [],
    },
    r: {
      title: "R",
      key: "r",
      hasMore: true,
      loading: false,
      status: 3,
      page: 1,
      list: [],
    },
    n: {
      title: "N",
      key: "n",
      hasMore: true,
      loading: false,
      status: 4,
      page: 1,
      list: [],
    },
  };
}

export default {
  name: "PageRewardDetail",
  components: {
    paypop,
    yfsItem,
    yfsRecordItem,
    yfsResultItem,
    popupImgDetail,
    popupDialog,
    buyBtns,
    payresult,
    LevelItem,
  },
  data() {
    return {
      userInfo: null,
      info: null,
      params: null,
      payList: null,
      lists: resetLists(),
      lineInfo: null,
      id: 0,
      buyBtns: [
        { num: 1, title: "买1发" },
        { num: 3, title: "买3发" },
        { num: 5, title: "买5发" },
        { num: 0, title: "全收" },
      ],
      tabs: [
        { title: "赠品一览", key: "list" },
        { title: "抽赏记录", key: "record" },
      ],
      currentTab: "list",
      loading: false,
      serverOffsetTime: 0,
      tiped: false,
      expirateTime: 0,
      cdText: "剩余抽赏时间",
      currentFilter: "all",
      wxsUsers: null,
    };
  },
  computed: {
    currentList() {
      return this.lists[this.currentFilter];
    },
    listsArr() {
      return Object.keys(this.lists).map((key) => this.lists[key]);
    },
    isLogin() {
      return !!this.userInfo && !!this.userInfo.session;
    },
    progressStyle() {
      if (!this.info) return `transform:translateX(-100%)`;

      return `transform:translateX(-${
        (this.info.curr_num / this.info.total_num) * 100
      }%)`;
    },
    lineImages() {
      if (!this.lineInfo || !this.lineInfo.images.length) return [];
      const imgs = [...this.lineInfo.images];

      if (imgs.length > 7) {
        imgs.length = 6;
      }
      return imgs.reverse();
    },
    cdTime() {
      if (
        !this.lineInfo ||
        !this.lineInfo.is_queue ||
        !this.lineInfo.is_curr_user
      ) {
        return "";
      }
      let str = "";
      const d = parseInt(this.expirateTime / 24 / 60 / 60);
      const h = parseInt((this.expirateTime % (24 * 60 * 60)) / 60 / 60);
      const m = parseInt((this.expirateTime % (60 * 60)) / 60);
      const s = this.expirateTime % 60;

      if (d) {
        str += `${d}天`;
      }
      if (h) {
        str += h < 10 ? `0${h}:` : `${h}:`;
      }
      str += m < 10 ? `0${m}:` : `${m}:`;
      str += s < 10 ? `0${s}` : `${s}`;

      return str;
    },
    computedBtns() {
      if (!this.info || !this.info.show_price) return this.buyBtns;
      const price = new Decimal(this.info.show_price);
      return this.buyBtns.map((item) => {
        const data =
          item.num === 0 &&
          this.info?.play_type !== 2 &&
          this.info?.play_type !== 4
            ? { num: 10, title: "买10发" }
            : item;
        return {
          ...data,
          price: price
            .mul(data.num > 0 ? data.num : this.info.curr_num)
            .toNumber(),
        };
      });
    },
  },
  watch: {},
  onLoad(data) {
    this.params = data;
    this.id = data.id;
    const uinfoStr = uni.getStorageSync("userinfo");
    if (uinfoStr) {
      this.userInfo = JSON.parse(uinfoStr);
    }
    this.refresh();
  },
  onShow() {
    reqAcceptSubMsgs(defaultTemplateIds);
  },
  onUnload() {
    clearTimeout(this.timer);
  },
  onShareAppMessage() {
    return {
      title:
        this.info?.name ||
        "各种爆款手办/盲盒，还能0元抽热款～快来试试你的欧气！",
      imageUrl:
        this.info?.img ||
        "https://chujianchaowan.oss-cn-beijing.aliyuncs.com/images/45bfb688e6e9dba557f64fd052e850cc.png",
      path: "/pages/reward/detail?id=" + this.id,
    };
  },
  onShareTimeline() {
    return {
      title:
        this.info?.name ||
        "各种爆款手办/盲盒，还能0元抽热款～快来试试你的欧气！",
      imageUrl:
        this.info?.img ||
        "https://chujianchaowan.oss-cn-beijing.aliyuncs.com/images/45bfb688e6e9dba557f64fd052e850cc.png",
      path: "/pages/reward/detail?id=" + this.id,
    };
  },
  methods: {
    delay(duration = 10000) {
      return new Promise((resolve) => {
        setTimeout(resolve, duration);
      });
    },
    stopCd() {
      this.serverOffsetTime = 0;
      clearTimeout(this.timer);
      // #ifdef MP-WEIXIN
      wx.disableAlertBeforeUnload && wx.disableAlertBeforeUnload();
      // #endif
    },
    runCd() {
      clearTimeout(this.timer);
      this.expirateTime =
        this.lineInfo.expirate_time -
        Math.round(Date.now() / 1000) +
        this.serverOffsetTime;

      if (this.expirateTime <= 0) {
        return;
      }
      // #ifdef MP-WEIXIN
      wx.enableAlertBeforeUnload &&
        wx.enableAlertBeforeUnload({
          message: "您正在购买中，确定要退出吗？",
        });
      // #endif
      this.timer = setTimeout(() => {
        this.expirateTime = Math.max(
          this.lineInfo.expirate_time -
            Math.round(Date.now() / 1000) +
            this.serverOffsetTime,
          0
        );

        if (this.expirateTime <= 10 && !this.tiped) {
          this.tiped = true;
          uni.showToast({
            icon: "none",
            title: "您剩余购买时间不足10秒，超出时间后购买会有被截胡风险。",
            duration: 2e3,
          });
        }
        if (this.expirateTime > 0) {
          this.runCd();
        } else {
          this.getLineUp();
          if (this.$refs.paypop) {
            this.$refs.paypop.closeAll();
          }
          uni.showToast({
            icon: "none",
            title: "当前排队结束",
            duration: 2e3,
          });
        }
      }, 1000);
    },
    loopQueue() {
      if (
        !this.lineInfo ||
        !this.lineInfo.is_queue ||
        !this.lineInfo.is_line_up ||
        (this.lineInfo.is_line_up && this.lineInfo.is_curr_user)
      ) {
        return;
      }

      clearTimeout(this.queueTimer);

      this.queueTimer = setTimeout(() => {
        this.getLineUp();
      }, 3000);
    },
    handleTabClick(key) {
      if (this.currentTab === key) return;

      this.currentTab = key;
      this.handleTagClick("all");
    },
    handleTagClick(key) {
      const item = this.lists[key];
      if (!item) return;
      if (this.currentFilter === key) {
        return;
      }
      this.currentFilter = key;
      if (item.list.length === 0 && item.hasMore) {
        this.getYfsPlayList(item);
      }
    },
    async refresh(useLoading = false) {
      if (this.loading && useLoading) return;
      this.loading = true;
      try {
        await Promise.all([
          this.getDetail(),
          this.getLineUp(),
          this.delay(800),
        ]);
        if (this.info.play_type === 3) {
          this.lists = resetLists();
          this.getWxsUsers();
        }
        await this.getPayList();
      } catch (e) {
        console.log(e);
      }
      this.loading = false;
    },
    async getDetail() {
      // const data = await api.getYfsDetail(this.id);
      const data = await api.getDetail(this.id, this.userInfo?.session || "");

      if (data.errno === 10000) {
        this.info = data.data;
        uni.setNavigationBarTitle({
          title: data.data.name,
        });
      }
    },
    // async getPayList() {
    //   const data = await api.getYfsPayList(this.id);
    //   if (data.errno === 10000) {
    //     this.payList = data.data;
    //   }
    // },
    async getPayList() {
      return this.info.play_type === 3
        ? this.getYfsPlayList(this.currentList)
        : this.getDefaultPlayList();
    },
    async getDefaultPlayList() {
      const data = await api.getYfsPayList(this.id);
      if (data.errno === 10000) {
        this.payList = data.data;
      }
    },
    async getYfsPlayList(item) {
      item.loading = true;
      try {
        const params = {
          status: item.status,
          session: this.userInfo?.session || "",
          lastId:
            item.page > 1 && item.list && item.list.length
              ? item.list[item.list.length - 1].id
              : 0,
        };

        const data = await api.getFudaiPayList(this.id, params);
        if (item.page === 1) {
          item.list = data.data.relations;
        } else {
          item.list = item.list.concat(data.data.relations);
        }

        item.hasMore = item.page * 20 < data.total;
        item.page++;
      } catch (e) {
        console.log(e);
      }
      item.loading = false;
    },
    async getWxsUsers() {
      const data = await api.getWxsUsers(this.id);
      if (data.errno === 10000) {
        this.wxsUsers = data;
      } else {
        this.wxsUsers = null;
      }
    },
    async getLineUp() {
      if (!this.userInfo || !this.userInfo.session) {
        this.lineInfo = null;
        return;
      }
      const data = await api.getLineUp(this.id, this.userInfo.session);
      if (data.errno === 10000) {
        const oldLineInfo = this.lineInfo ? { ...this.lineInfo } : null;
        this.lineInfo = data.data;

        this.tiped = false;
        if (data.data.is_queue && data.data.is_curr_user) {
          const now = Math.round(Date.now() / 1000);
          this.serverOffsetTime = now - data.data.curr_time;
          this.runCd();
          if (!oldLineInfo || !oldLineInfo.is_curr_user) {
            await this.getDetail();
            this.getPayList();
          }
        } else {
          this.stopCd();
          this.loopQueue();
        }
      } else {
        this.lineInfo = null;
        this.stopCd();
      }
    },
    async handleRemoveLine() {
      const data = await api.removeLineUp({
        session: this.userInfo.session,
        kuji_id: this.id,
      });

      if (data.errno === 10000) {
        await this.getLineUp();
      } else {
        uni.showToast({
          icon: "none",
          title: data.errmsg || "退出失败，请重试~",
          duration: 2e3,
        });
      }
    },
    async handleJoin() {
      const hasQueue =
        this.lineInfo.queue_kuji_id &&
        this.lineInfo.queue_kuji_id !== "0" &&
        this.lineInfo.queue_kuji_id !== this.id;

      if (hasQueue) {
        const confirm = await this.$refs.popupDialog
          .open("您在其它一番赏有排队，点击确认将退出其它队列")
          .then(() => true)
          .catch(() => false);
        if (!confirm) return;
      }
      await reqSubMsg(queueTemplateId).catch((e) => console.log(e));

      const data = await api.addLineUp({
        session: this.userInfo.session,
        kuji_id: this.id,
        status: hasQueue ? "1" : "0",
      });

      if (data.errno === 10000 || data.errno === 10002) {
        await this.getLineUp();
      } else {
        uni.showToast({
          icon: "none",
          title: data.errmsg || "加入失败，请重试~",
          duration: 2e3,
        });
      }
    },
    handleToId(id) {
      if (!id) return;
      this.id = id;
      this.refresh();
    },
    handleLogin() {
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      return login.wxLogin((userInfo) => {
        this.userInfo = userInfo;
        const msg =
          userInfo.coupons && userInfo.coupons.is_bind_coupon === 1
            ? userInfo.coupons.is_bind_info
            : "";

        this.refresh().finally(() => {
          uni.hideLoading();
          if (msg) {
            uni.showToast({
              icon: "none",
              title: msg || "登录成功~",
              duration: 2e3,
            });
          }
        });
      });
    },
    async handleBuy(num, useLoading = true) {
      if (this.info.is_end) {
        uni.showToast({
          icon: "none",
          title: "当前赏箱已抽完，请换箱购买",
          duration: 2e3,
        });
        return;
      }
      if (this.info.total_num > 0 && this.info.curr_num < num) {
        uni.showToast({
          icon: "none",
          title: " 当前赏箱数量不足，请减少购买数量",
          duration: 2e3,
        });
        return;
      }
      const n = !num ? this.info.curr_num : num;
      const originPrice = new Decimal(this.info.show_price).mul(n).toNumber();
      this.$refs.paypop.buy(n, originPrice, useLoading);
    },
    handlePopupShow(popup_ref) {
      this.$refs[popup_ref].open();
    },
    handlePopupClose(popup_ref) {
      this.$refs[popup_ref].close();
    },
    handlePaySuccess(data) {
      this.refresh();
      if (this.$refs.payresult) {
        this.$refs.payresult.open(data);
      } else {
        uni.showToast({
          icon: "success",
          title: "购买成功",
          duration: 2e3,
        });
      }
    },
    handleUpdateUserInfo(data, item, useLoading = true) {
      this.userInfo = data;
      if (item) {
        this.handleBuy(item.num, useLoading);
      }
    },
    handleBtnsClick(item) {
      this.handleBuy(item.num);
    },
    handleShowImages(item) {
      this.$refs.imgdetail.open({
        title: item.name,
        list: item.long_img ? item.long_img : [item.big_img],
      });
    },
    handleToLink(url) {
      jumpToUrl(url);
    },
  },
};
</script>

<style lang="scss">
@import "./detail.scss";
</style>
