<template>
  <view class="page_container">
    <custom-nav-bar title="视频会议" />

    <view class="action_row">
      <view class="action_item" @click="joinMeeting">
        <image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/meeting_join.png" mode="" />
        <text>加入会议</text>
      </view>
      <view class="action_item" @click="createQuickMeeting">
        <image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/meeting_quick.png" mode="" />
        <text>快速会议</text>
      </view>
      <view class="action_item" @click="reserveMeeting">
        <image src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/meeting_reserve.png" mode="" />
        <text>预约会议</text>
      </view>
    </view>

    <view v-if="!isLoading" class="record_list">
      <view class="record_item" v-for="item in records" :key="item.info.systemGenerated.meetingID"
        @click="toDetals(item)">
        <view class="title_row">
          <view class="title">
            {{ item.info.creatorDefinedMeeting.title }}
          </view>
          <view class="icon" :style="{
            'background-color':
              item.state * 1000 ? '#0089FF' : '#FFB300',
          }">
            {{ item.state * 1000 ? '未开始' : '已开始' }} </view>
        </view>
        <view class="sub_title">
          <text>{{ item.startTime + "-" + item.endTime }}</text>
          <text>{{ ' 发起人:' + item.info.systemGenerated.creatorNickname }}</text>
        </view>
      </view>
    </view>
    <view v-else class="loading">
      <u-loading-icon></u-loading-icon>
    </view>
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import CustomNavBar from "../../../components/CustomNavBar/index.vue";
import IMSDK from "openim-uniapp-polyfill";
import dayjs from "dayjs";
import { meetingModule } from "../../../util/imCommon";
import { getMeetings, createImmediateMeeting } from '../../../api/meeting'
import config from "../../../common/config";

export default {
  components: {
    CustomNavBar,
  },
  data() {
    return {
      isRequestMeeting: false,
      isLoading: false,
      records: [],
    };
  },
  computed: {
    ...mapGetters(["storeSelfInfo"]),
  },
  onShow() {
    this.getMeetingRecords();
    IMSDK.subscribe("dismiss", this.getMeetingRecords);
  },
  methods: {
    getMeetingRecords() {
      this.isLoading = true
      getMeetings({
        userID: this.storeSelfInfo.userID,
        status: ["Scheduled", "In-Progress"],
      })
        .then(async (data) => {
          console.log('getMeetings', data)
          let meetingDetails = data.meetingDetails
          meetingDetails = (meetingDetails ?? []).filter((item) =>
            Boolean(item.info?.creatorDefinedMeeting?.hostUserID),
          );
          if (meetingDetails.length > 0) {
            const { data } = await IMSDK.asyncApi(
              IMSDK.IMMethods.GetUsersInfo,
              IMSDK.uuid(),
              meetingDetails.map(
                (item) => item.info?.creatorDefinedMeeting?.hostUserID,
              ),
            );
            meetingDetails.map((meeting) => {
              const findUser = data.find(
                (user) =>
                  user.userID === meeting.info?.creatorDefinedMeeting?.hostUserID,
              );
              meeting.hostFaceURL = findUser?.faceURL;
              meeting.startTime = dayjs(meeting.info?.creatorDefinedMeeting
                ?.scheduledTime * 1000).format("M-DD HH:mm");
              meeting.endTime = dayjs((meeting.info?.creatorDefinedMeeting
                ?.scheduledTime + meeting.info?.creatorDefinedMeeting
                  ?.meetingDuration) * 1000).format("HH:mm");
              meeting.state = Date.now() < meeting.info?.creatorDefinedMeeting?.scheduledTime * 1000
            });
            this.records = meetingDetails;
            console.log('meetingDetails', meetingDetails)
          }
        })
        .finally(() => {
          this.isLoading = false
        })
    },
    toDetals(record) {
      uni.$u.route("/pages_im/pages/common/meetingDetails/index", {
        meetingData: JSON.stringify(record)
      });
    },
    reserveMeeting() {
      uni.$u.route("/pages_im/pages/common/reserveMeeting/index", {
        isUpdate: false,
      });
    },
    joinMeeting() {
        uni.$u.route("/pages_im/pages/common/joinMeeting/index");
    },
    createQuickMeeting() {
      if (this.isRequestMeeting) return;
      this.isRequestMeeting = true;
      const params = {
        creatorUserID: this.storeSelfInfo.userID,
        creatorDefinedMeetingInfo: {
          title: this.storeSelfInfo.nickname + '发起的视频会议',
          scheduledTime: dayjs().unix(),
          meetingDuration: 3600,
          password: "",
        },
        setting: {
          canParticipantsEnableCamera: true,
          canParticipantsUnmuteMicrophone: true,
          canParticipantsShareScreen: true,
          disableCameraOnJoin: true,
          disableMicrophoneOnJoin: true,
        },
      };
      createImmediateMeeting(params).then((data) => {
        const meetingData = {
          liveURL: data.liveKit?.url,
          token: data.liveKit?.token,
          roomID: data.detail?.info?.systemGenerated?.meetingID,
          imToken: uni.getStorageSync("IMToken"),
          baseURL: config.getApiUrl()
        };
        meetingModule.startMeeting(meetingData);
        setTimeout(() => {
          this.getMeetingRecords();
        }, 500);
      }).finally(() => {
        this.isRequestMeeting = false
      })
    },
  },
  onBackPress(options) {
    uni.switchTab({
      url: "/pages_im/pages/conversation/conversationList/index",
    });
    return true;
  },
};
</script>

<style lang="scss" scoped>
.page_container {
  .action_row {
    display: flex;
    justify-content: space-between;
    margin: 0 32rpx;
    padding: 48rpx 0 32rpx;
    border-bottom: 1px solid rgba(126, 134, 142, 0.16);

    .action_item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #16191c;

      image {
        width: 50px;
        height: 50px;
        margin-bottom: 12rpx;
      }
    }
  }

  .record_list {
    flex: 1;

    .record_item {
      padding: 24rpx 42rpx;

      .title_row {
        display: flex;
        align-items: center;
        margin-bottom: 12rpx;

        .title {
          @include nomalEllipsis();
          max-width: 50vw;
        }

        .icon {
          padding: 0 12rpx;
          height: 40rpx;
          line-hight: 40rpx;
          font-size: 24rpx;
          color: #fff;
          margin-left: 16rpx;
          text-align: center;
          border-radius: 8rpx;
        }
      }

      .sub_title {
        font-size: 24rpx;
        color: #666;

        text:first-child {
          margin-right: 24rpx;
        }
      }
    }
  }

  .loading {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
