<template>
  <u-sticky class="shadow-default" bgColor="#fff" style="top: 0">
    <u-navbar :titleStyle="{ color: '#000' }" :autoBack="true" title="会议预约" :placeholder="true" :safeAreaInsetTop="true" bgColor="#fff">
      <template #left>
        <view class="u-navbar__content__left__item">
          <u-icon name="arrow-left" size="20" color="#000"></u-icon>
        </view>
      </template>
      <template #right>
        <view class="u-navbar__content__right__item">
          <u-icon name="more-dot-fill" size="19" color="#000" @click="handleSheet(true, 'rightMore')"></u-icon>
        </view>
      </template>
    </u-navbar>

    <view class="flex plr10">
      <u--input
        style="width: 100%"
        v-model="form.meetingRoomName"
        placeholder="搜索会议室"
        prefixIcon="search"
        prefixIconStyle="font-size: 22px;color: #909399"
        customStyle="height:35px;background-color:#f5f6fa; "
        @confirm="init()"
        clearable
      ></u--input>
    </view>

    <switchSlot
      :form="form"
      :form-data="formData"
      :activeColor="proxy.$settingStore.themeColor.color"
      disabledColor="#999999"
      @changeSheet="1"
      @reset="resetSwitch()"
      @handleInit="init()"
    ></switchSlot>
  </u-sticky>

  <oa-scroll
    customClass="record-container scroll-height"
    :isSticky="true"
    :customStyle="{
      //#ifdef APP-PLUS || MP-WEIXIN
      height: `calc(100vh - (44px + 35px + 50px + ${proxy.$settingStore.StatusBarHeight}))`,
      //#endif
      //#ifdef H5
      height: 'calc(100vh - (44px + 35px + 50px))',
      //#endif
    }"
    :pageSize="pageSize"
    :total="total"
    :refresherLoad="false"
    :refresherEnabled="true"
    :refresherDefaultStyle="'none'"
    :refresherThreshold="44"
    :refresherBackground="'#f5f6f7'"
    @refresh="refresh"
    :data-theme="'theme-' + proxy.$settingStore.themeColor.name"
  >
    <template #default>
      <u-loading-page :loading="state.loading" fontSize="16" style="z-index: 99"></u-loading-page>
      <view class="content-area bg-white radius flex flex-wrap m10 p10" v-for="room in dataList" :key="room" @click="handlePopup(true, 'aboutMeeting', room)">
        <view class="mr10 mtb-auto">
          <u-image v-if="room.imgPath" :show-loading="true" :src="room.imgPath" width="50px" height="50px" radius="5px"></u-image>
          <u-image v-else :show-loading="true" src="@/static/images/defaultImg.jpg" width="50px" height="50px" radius="5px"></u-image>
        </view>
        <view class="mtb-auto">
          <view class="font16 text-black mb5">{{ room.roomName }}</view>
          <view class="font12 text-gray">可容纳{{ room.capacity || 0 }}人</view>
        </view>
        <view class="mt10" style="width: 100%">
          <timeSlot :currentDay="form.date" :aboutTimeData="room.dmMeetingList" :activeColor="proxy.$settingStore.themeColor.color" />
        </view>
      </view>
    </template>
  </oa-scroll>

  <u-popup :show="popup.show" mode="bottom" bgColor="#fff" :round="10" @close="popup.show = false">
    <view
      :style="{
        borderTopLeftRadius: '10px',
        borderTopRightRadius: '10px',
        overflow: 'hidden',
      }"
    >
      <view v-if="popup.type === 'aboutMeeting'">
        <view class="flex p15 font16">
          <view class="mtb-auto"> {{ popup.list.roomName }}</view>
          <view class="mtb-auto ml-auto" @click="handleSheet(true, 'popupMore')">
            <u-icon name="info-circle" size="16" label="更多" labelSize="14" labelColor="#333" color="#333"></u-icon>
          </view>
        </view>
        <u-gap height="10" bgColor="#f5f6f7"></u-gap>
        <scroll-view scroll-y="true" :scroll-into-view="scrollIntoView" style="height: 42vh">
          <u-checkbox-group v-model="checkboxValue" placement="column" shape="circle" :borderBottom="true" @change="checkboxChange">
            <view :id="'item' + item.id" v-for="(item, index) in checkboxList" :key="index">
              <u-checkbox
                :customStyle="{ padding: '15px', margin: '0', backgroundColor: `${item.isDisabledColor}30` }"
                :label="item.timeSlot"
                :name="item.startTime"
                :disabled="item.isDisabled || item.isAbout === '已预约'"
                :activeColor="proxy.$settingStore.themeColor.color"
              >
                <template #label>
                  <view class="font15 mtb-auto" :style="{ color: item.isDisabled || item.isAbout === '已预约' ? '#c8c9cc' : '#333333' }"> {{ item.timeSlot }}</view>
                  <view class="font15 mtb-auto ml-auto" :style="{ color: item.isDisabled || item.isAbout === '已预约' ? '#c8c9cc' : '#333333' }"> {{ item.isAbout }}</view>
                </template>
              </u-checkbox>
            </view>
          </u-checkbox-group>
        </scroll-view>
        <u-gap height="10" bgColor="#f5f6f7"></u-gap>
        <view class="p10" style="overflow: hidden">
          <u-button type="primary" @click="handleSubmit('下一步')" text="下一步" style="width: 100px; float: right"></u-button>
        </view>
      </view>
    </view>
  </u-popup>

  <u-action-sheet
    :actions="sheet.actions"
    :show="sheet.show"
    cancelText="取消"
    :round="10"
    :wrapMaxHeight="'50vh'"
    :closeOnClickOverlay="true"
    :safeAreaInsetBottom="true"
    @close="sheet.show = false"
    @select="changeSheet"
  ></u-action-sheet>
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import { onLoad, onShow, onReady, onHide, onLaunch, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { MeetingRoomList, MeetingRoomReservationList } from "@/api/business/meeting.js";
import { doorApi } from "@/api/business/door.js";
/*----------------------------------组件引入-----------------------------------*/
import timeSlot from "./components/timeSlot.vue";
import switchSlot from "./components/switchSlot.vue";
/*----------------------------------store引入-----------------------------------*/
import { useStores, systemStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
const useStore = useStores();
const systemStore = systemStores();
/*----------------------------------变量声明-----------------------------------*/
const state = reactive({
  loading: false,
  dataList: [],
  pageSize: 20,
  total: 0,
  form: {
    date: proxy.$dayjs().format("YYYY-MM-DD"),
    meetingRoomName: "",
  },
  formData: [
    {
      type: "switchTime",
      prop: "date",
      label: "时间",
      fontSize: "16",
      data: [],
    },
  ],
  popup: {
    show: false,
    type: "",
    list: {},
  },
  sheet: {
    show: false,
    title: "",
    actions: [],
  },
  checkboxValue: [],
  checkboxList: [],
  scrollIntoView: "",
});

const { loading, dataList, pageSize, total, form, formData, popup, sheet, checkboxValue, checkboxList, scrollIntoView } = toRefs(state);

/** 初始化 */
function init() {
  state.checkboxValue = [];
  state.checkboxList = [];

  state.loading = true;
  MeetingRoomReservationList({
    date: state.form.date + " 00:00:00",
    meetingRoomName: state.form.meetingRoomName,
  })
    .then((requset) => {
      if (requset.status === "SUCCESS") {
        state.dataList = requset.data;
        state.total = requset.data.length;
        state.loading = false;
      }
    })
    .catch((err) => {
      state.loading = false;
    });
  state.checkboxList = getAllTimesDay(state.form.date, 30);
}

/** 获取当天时间 */
function getAllTimesDay(day, min) {
  let defaultList = [];
  // 获取当天开始的时间
  const startOfDay = proxy.$dayjs(day).startOf("day");
  const endOfDay = proxy.$dayjs(day).endOf("day");

  // 循环半小时直到当天结束
  for (let currentTime = startOfDay; currentTime.isBefore(endOfDay); currentTime = currentTime.add(min, "minute")) {
    let isAfter = currentTime.add(min, "minute").isAfter(endOfDay); //当前时间是否在结束时间之后（true|false）
    let startTime = currentTime.add(0, "minute").format("YYYY-MM-DD HH:mm:ss"); //获取开始时间
    let endTime = isAfter ? endOfDay.format("YYYY-MM-DD HH:mm:ss") : currentTime.add(min, "minute").format("YYYY-MM-DD HH:mm:ss"); //获取结束时间
    let timeSlot = proxy.$dayjs(startTime).format("HH:mm") + " - " + proxy.$dayjs(endTime).format("HH:mm"); //获取开始时间和结束时间“时、分”

    const array = {
      id: defaultList.length + 1,
      startTime: startTime,
      endTime: endTime,
      timeSlot: timeSlot,
      isDisabled: false,
      isAbout: "",
      isDisabledColor: "#FFFFFF",
      isDisabledFontColor: "#333333",
    }; //此返回值（不可删除）可叠加

    //判断当前时间是否相同或在其之后
    if (proxy.$dayjs().isSameOrAfter(startTime)) {
      array.isAbout = "不可预约";
      array.isDisabled = true;
    }
    defaultList.push(array);
  }
  return defaultList;
}

/** 复选框改变事件 */
function checkboxChange(e, index) {
  if (e.length > 1) {
    const startOfDay = proxy.$dayjs(e[0]);
    const endOfDay = proxy.$dayjs(e[e.length - 1]);

    for (let currentTime = startOfDay; currentTime.isBefore(endOfDay); currentTime = currentTime.add(30, "minute")) {
      if (!e.includes(currentTime.format("YYYY-MM-DD HH:mm:ss"))) {
        e.push(currentTime.format("YYYY-MM-DD HH:mm:ss"));
      }
    }
  }

  state.checkboxValue = e.sort((a, b) => new Date(`${proxy.$dayjs(a).format("YYYY-MM-DD HH:mm:ss")}`) - new Date(`${proxy.$dayjs(b).format("YYYY-MM-DD HH:mm:ss")}`));
}

/** 点击预约 */
function handleSubmit() {
  if (!state.checkboxValue.length) {
    proxy.$modal.msg("请先选择时间");
    return false;
  }

  systemStore.meetingList.form = {
    roomId: state.popup.list.roomId, //房间Id
    roomName: state.popup.list.roomName, //会议室名称
    startDate: state.checkboxValue[0], //会议开始时间
    endDate: state.checkboxValue[state.checkboxValue.length - 1], //会议结束时间
    meetingName: useStore.nickName + "预约的会议", //会议名称
    initiatorUser: {
      contacts: useStore.phonenumber, //联系方式
      deptId: useStore.deptId,
      email: useStore.email,
      id: useStore.userId,
      isApprover: false,
      name: useStore.nickName, //验证人名称
      sex: useStore.sex,
    }, //发起人信息
    meetingDescribe: "", //会议介绍
    users: [], //参会人信息
    meetingMode: 0, //会议模式
    sendType: ["站内信"], //通知类型(短信)
    remark: "", //备注
    room: state.popup.list, //会议室信息
    meetingFileList: [], //会议文件信息
  };

  proxy.$tab.navigateTo(`/pages/business/meeting/new/index`);
  state.popup.show = false;
}

/** 操作菜单 */
function changeSheet(e) {
  if (e.name == "会议室详情") {
    proxy.$tab.navigateTo(`/pages/business/meeting/detailed/index?roomId=${state.popup.list.roomId}`).then(() => {});
  } else if (e.name == "门禁开门") {
    openDoor(e);
  } else if (e.name == "我的会议") {
    proxy.$tab.navigateTo(`/pages/business/meeting/my/index`).then(() => {});
  }
}

/**
 * @门禁开门
 */
function openDoor(e) {
  doorApi()
    .control({
      productCode: "502_USKY",
      deviceUuid: e.deviceUuid,
      commandCode: "door_onoff",
      commandValue: 1,
    })
    .then((item2) => {
      proxy.$modal.msg("开门成功");
    })
    .catch((err) => {
      console.log(err);
    });
}

/** 操作菜单 */
function handleSheet(show, type) {
  state.sheet.show = show;
  if (type === "rightMore") {
    state.sheet.actions = [
      {
        name: "我的会议",
        value: "",
        type: "meeting-my",
      },
    ];
  } else if (type === "popupMore") {
    state.sheet.actions = [
      {
        name: "门禁开门",
        value: "",
        type: "meeting-room",
      },
      {
        name: "会议室详情",
        value: "",
        type: "meeting-details",
      },
    ];
  }
}

/** 操作弹窗 */
function handlePopup(show, type, list) {
  state.popup.show = show;
  state.popup.type = type;
  state.popup.list = list;

  if (type === "aboutMeeting") {
    list.dmMeetingList.forEach((e) => {
      let startTime = proxy.$dayjs(e.startDate).add(0, "minute").format("YYYY-MM-DD HH:mm:ss");
      let endTimeNum = e.endDate.indexOf("59") != -1 ? -29.59 : -30;
      let endTime = proxy.$dayjs(e.endDate).add(endTimeNum, "minute").format("YYYY-MM-DD HH:mm:ss");

      state.checkboxList.forEach((f) => {
        if (proxy.$dayjs(f.startTime).isBetween(startTime, endTime, null, "[]")) {
          f.isDisabledColor = proxy.$settingStore.themeColor.color;
          f.isDisabledFontColor = "#FFFFFF";
          f.isAbout = "已预约";
        }
      });
    });

    state.scrollIntoView = "";
    setTimeout(() => {
      state.checkboxList.some((e) => {
        if (e.isDisabled === false) {
          state.scrollIntoView = "item" + e.id;
          return true;
        }
        return false;
      });
    });
  }
}

/** 操作重置 */
function resetSwitch() {
  state.form = {
    date: proxy.$dayjs().format("YYYY-MM-DD"),
    meetingRoomName: "",
  };
  init();
}

/**
 * @scrollView刷新数据
 */
function refresh() {
  init();
}

onReady(() => {});

onShow(() => {
  //调用系统主题颜色
  proxy.$settingStore.systemThemeColor([1]);
  init();
});

onLoad((options) => {});

onUnload(() => {});
</script>

<style lang="scss" scoped>
.content-area {
  color: #000000;
}
</style>
