import { request } from "../../utils/request";
import { appId } from "../../env";
import {
  join,
  leave,
  addCustomEventListener,
  removeCustomEventListener,
} from "../../utils/server-sent-events";
interface LiveroomData {
  isPlayback: boolean;
  pluginVisible: boolean;
  roomInfo: any;
  pullUrlInfo: any;
  vodInfo: any;
  watchNum: number;
  productNum: number;
  chatEnhancementApproved: boolean;
}
interface LiveroomProperties {
  joinedGroupId: string;
}
interface LiveroomComponent
  extends WechatMiniprogram.Component.TrivialInstance {
  data: LiveroomData;
  properties: LiveroomProperties;
  _listener?: (data: any) => void;
  onLiveMessage: (data: any) => void;
  init: () => Promise<void>;
  cleanup: () => void;
  handleError: (error?: unknown) => void;
  setChatEnhancementApproval: (approved: boolean) => void;
}

const statusId = "roomId-1";
// components/liveroom/liveroom.ts
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    joinedGroupId: {
      type: String,
      value: "",
      observer: function (
        this: LiveroomComponent,
        newVal: string,
        oldVal: string,
      ) {
        if (newVal && newVal !== oldVal) {
          this.init();
        }
      },
    },
  },
  lifetimes: {
    attached(this: LiveroomComponent) {},
    detached(this: LiveroomComponent) {
      this.cleanup();
    },
  },
  pageLifetimes: {
    show(this: LiveroomComponent) {
      this._listener = this.onLiveMessage.bind(this);
      addCustomEventListener("pushMsg", this._listener);
      join(statusId);
    },
    hide() {
      // @ts-ignore
      removeCustomEventListener("pushMsg", this._listener);
      leave(statusId);
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isPlayback: false,
    pluginVisible: true,
    roomInfo: null,
    watchNum: 0,
    productNum: 0,
    durationInterval: null,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onLiveMessage(data: any) {
      console.log("收到通知：", data);
      const that = this as any;
      if (data.type == "watchNum") {
        that.setData({ watchNum: data.count });
      }

      if (data.type == "productNum") {
        that.setData({ productNum: data.count });
      }
    },

    updateIsPlayback(this: any, bool: boolean) {
      this.isPlayback = bool;
    },
    controlstoggle(this: LiveroomComponent, e: WechatMiniprogram.CustomEvent) {
      const { state } = e.detail;
      if (state && this.data.roomInfo) {
        this.setData({
          roomInfo: {
            ...this.data.roomInfo,
            state,
          },
        });
      }
    },

    async init(this: LiveroomComponent) {
      const app = getApp<IAppOption>();
      if (!app.globalData.isLogin) return;
      const roomId = this.properties.joinedGroupId;
      const params = {
        roomId: roomId,
        appId: appId,
        openId: wx.getStorageSync("openId"),
      };

      try {
        const data = await request({
          options: {
            url: `/app/video-live/details`,
            data: params,
            method: "GET",
          },
        });
        const bool = this.compareTime(data.data.onlineDatetime);
        console.log(bool, "12313");
        this.setData({
          roomInfo: data.data,
          pullUrlInfo: data.data,
          vodInfo: data.data,
          bool,
        });
      } catch (error) {
        this.handleError(error);
      }
    },

    handleError(this: LiveroomComponent) {
      wx.showToast({
        title: "获取直播信息失败",
        icon: "none",
        duration: 2000,
      });
    },

    cleanup(this: LiveroomComponent) {
      this.setData({
        isPlayback: false,
        pluginVisible: true,
        roomInfo: null,
        watchNum: 0,
        productNum: 0,
        chatEnhancementApproved: false,
      });
    },

    compareTime(targetTimeStr: string) {
      const targetTime = new Date(targetTimeStr);
      const currentTime = new Date();
      return targetTime > currentTime;
    },

    startDurationTimer(this: LiveroomComponent) {
      this.durationInterval = setInterval(() => {
        const now = new Date().getTime();
        const startTime = new Date(this.data.roomInfo.onlineDatetime).getTime();
        if (now < startTime) {
          const remainingTime = Math.floor((startTime - now) / 1000);
          const days = Math.floor(remainingTime / (24 * 3600));
          const hours = Math.floor((remainingTime % (24 * 3600)) / 3600);
          const minutes = Math.floor((remainingTime % 3600) / 60);
          const seconds = remainingTime % 60;
          this.setData({
            isLiveStarted: false,
            countdown:
              days > 0
                ? `${days}天${hours.toString().padStart(2, "0")}:${minutes
                    .toString()
                    .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`
                : `${hours.toString().padStart(2, "0")}:${minutes
                    .toString()
                    .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`,
          });
        } else {
          const duration = Math.floor((now - startTime) / 1000);
          const hours = Math.floor(duration / 3600);
          const minutes = Math.floor((duration % 3600) / 60);
          const seconds = duration % 60;
          this.setData({
            isLiveStarted: true,
            duration: `${hours.toString().padStart(2, "0")}:${minutes
              .toString()
              .padStart(2, "0")}:${seconds.toString().padStart(2, "0")}`,
          });
        }
      }, 1000);
    },

    stopDurationTimer(this: LiveroomComponent) {
      if (this.durationInterval) {
        clearInterval(this.durationInterval);
        this.durationInterval = null;
      }
    },
  },
});
