<template>
  <view class="page_container">
    <custom-nav-bar :title="isUpdate ? '修改会议信息' : '预约会议'" />

    <view class="field_row field_row_input">
      <u--input placeholder="请输入会议主题" border="none" v-model="meetingData.meetingName"></u--input>
    </view>
    <view class="field_row" @click="showDatePicker = true">
      <view>开始时间</view>
      <view class="right_value">{{ showDate }}</view>
      <u-icon name="arrow-right" />
    </view>
    <view class="field_row" @click="showDurationPicker = true">
      <view>会议时长</view>
      <view class="right_value">{{ showDuration }}</view>
      <u-icon name="arrow-right" />
    </view>

    <view class="action_row">
      <u-button type="primary" :text="isUpdate ? '确认修改' : '预约会议'" @click="confirmReserve"></u-button>
    </view>

    <u-datetime-picker :minDate="Date.now()" :show="showDatePicker" v-model="meetingData.startTime" mode="datetime"
      @cancel="showDatePicker = false" @confirm="confirmDate" />

    <u-action-sheet safeAreaInsetBottom :actions="durationList" cancelText="取消" closeOnClickOverlay
      :closeOnClickAction="true" :show="showDurationPicker" @select="confirmDuration"
      @close="showDurationPicker = false" />
  </view>
</template>

<script>
import { mapGetters } from "vuex";
import CustomNavBar from "../../../components/CustomNavBar/index.vue";
import dayjs from "dayjs";
import { toastWithCallback } from "../../../util/common";
import { updateMeeting, bookMeeting } from '../../../api/meeting'

const secondsToTime = {
  1800: "30分钟",
  3600: "1小时",
  5400: "1.5小时",
  7200: "2小时",
};

export default {
  components: {
    CustomNavBar,
  },
  data() {
    return {
      meetingData: {
        meetingName: "",
        startTime: 0,
        duration: 0,
      },
      isUpdate: false,
      showDatePicker: false,
      showDurationPicker: false,
      durationList: [
        {
          name: "30分钟",
          value: 1800,
        },
        {
          name: "1小时",
          value: 3600,
        },
        {
          name: "1.5小时",
          value: 5400,
        },
        {
          name: "2小时",
          value: 7200,
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["storeSelfInfo"]),
    showDate() {
      if (this.meetingData.startTime) {
        return dayjs(this.meetingData.startTime).format("M月D日 HH:mm");
      }
      return "";
    },
    showDuration() {
      if (this.meetingData.duration) {
        return secondsToTime[this.meetingData.duration];
      }
      return "";
    },
  },
  onLoad(options) {
    this.isUpdate = JSON.parse(options.isUpdate);
    if (options.meetingData) {
      const meetingInfo = JSON.parse(options.meetingData);
      this.meetingData = {
        meetingID: meetingInfo?.info?.systemGenerated?.meetingID,
        meetingName: meetingInfo?.info?.creatorDefinedMeeting?.title,
        startTime: meetingInfo?.info?.creatorDefinedMeeting?.scheduledTime * 1000,
        duration: meetingInfo?.info?.creatorDefinedMeeting?.meetingDuration,
      };
    }
  },
  methods: {
    confirmDate(value) {
      console.log(value);
      this.showDatePicker = false;
    },
    confirmDuration({ value }) {
      this.meetingData.duration = value;
      this.showDurationPicker = false;
    },
    confirmReserve() {
      const notEmpty =
        Object.values(this.meetingData).find((field) => !field) === undefined;
      if (!notEmpty && !this.isUpdate) {
        return;
      }

      if (this.isUpdate) {
        const params = {
          meetingID: this.meetingData.meetingID,
          updatingUserID: this.storeSelfInfo.userID,
          title: this.meetingData.meetingName,
          scheduledTime: Math.round(this.meetingData.startTime / 1000),
            meetingDuration: this.meetingData.duration,
            password: "",
            timeZone: "Asia/Shanghai",
            repeatInfo: {
            endDate: 1735664461,
            repeatType: "None",
            uintType: "Week",
            interval: 0,
          },
            canParticipantsEnableCamera: true,
            canParticipantsUnmuteMicrophone: true,
            canParticipantsShareScreen: true,
            disableCameraOnJoin: false,
            disableMicrophoneOnJoin: false,
            canParticipantJoinMeetingEarly: true,
            lockMeeting: false,
            audioEncouragement: true,
            videoMirroring: true,
        };
        console.log('params', params);
        updateMeeting(params)
          .then(() => {
            toastWithCallback("修改成功！", () => uni.$u.route("/pages_im/pages/common/meetingCenter/index"))
          })
          .catch(() => uni.$u.toast("修改失败！"));
        return;
      }

      const params = {
        creatorUserID: this.storeSelfInfo.userID,
        creatorDefinedMeetingInfo: {
          title: this.meetingData.meetingName,
          scheduledTime: Math.round(this.meetingData.startTime / 1000),
          meetingDuration: this.meetingData.duration,
          password: "",
          timeZone: "Asia/Shanghai",
        },
        repeatInfo: {
          endDate: 1735664461,
          repeatType: "None",
          uintType: "Week",
          interval: 0,
        },
        setting: {
          canParticipantsEnableCamera: true,
          canParticipantsUnmuteMicrophone: true,
          canParticipantsShareScreen: true,
          disableCameraOnJoin: false,
          disableMicrophoneOnJoin: false,
          canParticipantJoinMeetingEarly: true,
          lockMeeting: false,
          audioEncouragement: true,
          videoMirroring: true,
        },
      };
      console.log('params', params);
      bookMeeting(params)
        .then(() => {
          toastWithCallback("预约成功！", () => uni.$u.route("/pages_im/pages/common/meetingCenter/index"))
        })
        .catch(() => uni.$u.toast("预约失败！"));
      // IMSDK.asyncApi("signalingCreateMeeting", IMSDK.uuid(), {
      //   meetingName: this.meetingData.meetingName,
      //   meetingHostUserID: this.$store.getters.storeSelfInfo.userID,
      //   startTime: (this.meetingData.startTime / 1000).toFixed() * 1,
      //   meetingDuration: this.meetingData.duration,
      //   inviteeUserIDList: [],
      // })
      //   .then(({ data }) => {
      //     IMSDK.asyncApi("signalingUpdateMeetingInfo", IMSDK.uuid(), {
      //       roomID: data.roomID,
      //       participantCanUnmuteSelf: true,
      //     });
      //     uni.$u.route("/pages/common/meetingDetails/index", {
      //       meetingData: JSON.stringify({
      //         roomID: data.roomID,
      //         meetingName: this.meetingData.meetingName,
      //         hostUserID: this.$store.getters.storeSelfInfo.userID,
      //         startTime: (this.meetingData.startTime / 1000).toFixed() * 1,
      //         endTime:
      //           (this.meetingData.startTime / 1000).toFixed() * 1 +
      //           this.meetingData.duration,
      //         launcher: `发起人：${this.$store.getters.storeSelfInfo.nickname}`,
      //       }),
      //     });
      //   })
      //   .catch((err) => {
      //     console.log(err);
      //     uni.$u.toast("预约失败！");
      //   });
    },
  },
};
</script>

<style lang="scss">
.page_container {
  background-color: #f6f6f6;

  .field_row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx;
    background-color: #fff;
    position: relative;

    .right_value {
      color: #737577;
      margin-right: 48rpx;
    }

    .u-icon--right {
      position: absolute;
      right: 32rpx;
    }

    &_input {
      margin-top: 24rpx;
    }
  }

  .action_row {
    margin-top: 10vh;
    padding: 0 24%;
  }
}
</style>
