<template>
  <web-view
    v-show="!controlStore.modal.show"
    ref="faceView"
    id="faceView"
    class="faceView"
    src="/static/face/meeting.html"
    bindmessage="receiveMessage"
    :webview-styles="webviewStyles"
    @message="onMessage"
  >
  </web-view>

  <u-modal
    :show="controlStore.modal.show"
    title="配置服务器"
    :cancelText="'退出应用'"
    :zoom="false"
    :showConfirmButton="true"
    :showCancelButton="true"
    :closeOnClickOverlay="true"
    @confirm="controlStore.modalConfirm(), getMeetingRoomReservationList()"
    @cancel="controlStore.modalCancel()"
    @close="controlStore.modalClose()"
  >
    <view class="slot-content">
      <u-subsection class="mb20" :list="controlStore.subsection.list" :current="controlStore.subsection.value" @change="controlStore.sectionChange"></u-subsection>

      <view v-if="controlStore.subsection.value == 0">
        <view class="mb10 required">服务器地址</view>
        <view class="mb20">
          <u-input v-model="controlStore.form.linkUrl" placeholder="服务器地址（必填）" border="bottom" style="padding: 6px 0px" />
        </view>

        <view class="mb10">服务器端口</view>
        <view class="mb20">
          <u-input v-model="controlStore.form.port" placeholder="服务器端口（非必填）" border="bottom" style="padding: 6px 0px" />
        </view>
      </view>

      <view v-if="controlStore.subsection.value == 1">
        <view class="mb10 required">绑定会议室</view>
        <view class="mb20">
          <u-input
            v-model="controlStore.form.meetingName"
            placeholder="会议室（必选）"
            suffixIcon="arrow-right"
            suffixIconStyle="color: #909399"
            border="bottom"
            style="padding: 6px 0px"
            disabledColor="transparent"
            disabled
            @click="controlStore.handlePicker('绑定会议室')"
          />
        </view>

        <view class="mb10 required">绑定门禁</view>
        <view>
          <u-input
            v-model="controlStore.form.doorName"
            placeholder="门禁（必选）"
            suffixIcon="arrow-right"
            suffixIconStyle="color: #909399"
            border="none"
            disabledColor="transparent"
            disabled
            @click="controlStore.handlePicker('绑定门禁')"
          />
        </view>

        <view class="mb10 required" @click="handleButton()">开启灯光</view>
      </view>
    </view>
  </u-modal>

  <u-picker
    :show="controlStore.picker.show"
    :columns="controlStore.picker.list"
    :title="'请选择' + controlStore.picker.title"
    keyName="name"
    visibleItemCount="6"
    :defaultIndex="[controlStore.picker.defaultIndex]"
    :closeOnClickOverlay="true"
    @close="controlStore.picker.show = false"
    @cancel="controlStore.picker.show = false"
    @confirm="controlStore.pickerConfirm"
  ></u-picker>
</template>
<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import config from "@/config";
import { onLoad, onShow, onReady, onHide, onLaunch, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject, nextTick, watch } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { meetingApi, signOnOut } from "@/api/business/meeting.js";
/*----------------------------------组件引入-----------------------------------*/
/*----------------------------------store引入-----------------------------------*/
import { controlStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
const { proxy } = getCurrentInstance();
const controlStore = controlStores();
/*----------------------------------公共变量-----------------------------------*/
const state = reactive({
  webviewStyles: {
    width: "100%",
    height: "100%",
  },
  inter: {
    interMeeting: null,
  },
});
const { webviewStyles, meetingRoomList, modal, picker, form, inter } = toRefs(state);

// 初始化
function init() {
  controlStore.pageFunction = ["门禁", "会议"];
  controlStore.initCamera();
  controlStore.initNfc();
  controlStore.initData();

  // if (!inter.interMeeting) {
  //   getMeetingRoomReservationList();
  //   inter.interMeeting = setInterval(() => {
  //     getMeetingRoomReservationList();
  //   }, 1000 * 5);
  // }
}

/**
 * @会议室详情列表
 */
function getMeetingRoomReservationList() {
  controlStore.meetingTimeList = [];
  controlStore.meetingReservaList.thisVenueData = [];
  controlStore.meetingReservaList.thisVenueTime = {};
  controlStore.meetingReservaList.nextSceneData = [];
  controlStore.meetingReservaList.nextSceneTime = {};

  for (let i = 0; i <= 23.5; i += 0.5) {
    var time = "";
    if (i % 1 === 0.5) {
      if (i < 10) {
        time = "0" + (i - 0.5) + ":30";
      } else {
        time = i - 0.5 + ":30";
      }
    } else {
      if (i < 10) {
        time = "0" + i + ":00";
      } else {
        time = i + ":00";
      }
    }

    controlStore.meetingTimeList.push({
      startTime: time,
      endTime: time,
      isEnd: 0,
      isHave: 0,
      isReservation: 0,
    });
  }

  meetingApi()
    .GetMeetingRoomReservationList({
      domain: controlStore.form.domain,
      meetingRoomId: controlStore.form.meetingId,
      date: proxy.$dayjs().format("YYYY-MM-DD") + " 00:00:00",
    })
    .then((requset) => {
      if (requset.data.length > 0) {
        controlStore.meetingReservaList.dataAll = requset.data[0];
        controlStore.meetingReservaList.dataAll.dmMeetingList.forEach((e, index) => {
          //判断开始时间和结束时间是否包含当前时间
          if (proxy.$dayjs().isBetween(e.startDate, e.endDate, null, "[]")) {
            controlStore.meetingReservaList.thisVenueData.push(e);
            controlStore.meetingReservaList.thisVenueTime = proxy.$time.timeRestructuring(controlStore.meetingReservaList.dataAll.meetingRoomUsage[index]);
          }
          //判断当前时间是否相同或在其之前
          if (proxy.$dayjs().isSameOrBefore(e.startDate) && controlStore.meetingReservaList.nextSceneData.length < 1) {
            controlStore.meetingReservaList.nextSceneData.push(e);
            controlStore.meetingReservaList.nextSceneTime = proxy.$time.timeRestructuring(controlStore.meetingReservaList.dataAll.meetingRoomUsage[index]);
          }
        });

        controlStore.meetingReservaList.timeList = showTimeSegments(controlStore.meetingTimeList);
        controlStore.handleChildren({
          funcName: "初始化数据",
          data: JSON.stringify(controlStore.meetingReservaList),
        });
      } else {
        controlStore.meetingReservaList.timeList = controlStore.meetingTimeList;
        controlStore.handleChildren({
          funcName: "初始化数据",
          data: JSON.stringify(controlStore.meetingReservaList),
        });
      }
    })
    .catch((err) => {});
}

// 显示时间段的函数
function showTimeSegments(times) {
  const timesXleList = JSON.parse(JSON.stringify(times));

  for (var i = 0; i < timesXleList.length; i++) {
    const timeValue = new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${timesXleList[i].startTime}`);

    controlStore.meetingReservaList.dataAll.meetingRoomUsage.forEach((item) => {
      const timeList = proxy.$time.timeRestructuring(item);
      const startValue = new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${timeList.startTime}`);
      const endValue = new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${timeList.endTime}`);

      if (timeValue.getTime() >= startValue.getTime() && timeValue.getTime() < endValue.getTime()) {
        timesXleList.splice(i--, 1);
      }
    });
  }

  controlStore.meetingReservaList.dataAll.meetingRoomUsage.forEach((item) => {
    const timeList = proxy.$time.timeRestructuring(item);
    const startValue = new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${timeList.startTime}`);
    const endValue = new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${timeList.endTime}`);

    if (proxy.$dayjs().isBetween(startValue, endValue, null, "[]")) {
      timesXleList.push({
        ...timeList,
        isEnd: 0,
        isHave: 1,
        isReservation: 0,
      });
    } else {
      if (proxy.$dayjs().isSameOrAfter(startValue)) {
        timesXleList.push({
          ...timeList,
          isEnd: 1,
          isHave: 0,
          isReservation: 0,
        });
      }
      if (proxy.$dayjs().isSameOrBefore(startValue)) {
        timesXleList.push({
          ...timeList,
          isEnd: 0,
          isHave: 0,
          isReservation: 1,
        });
      }
    }
  });

  var newTimesXleList = proxy.$common
    .uniq(timesXleList, "startTime")
    .sort((a, b) => new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${a.startTime}`) - new Date(`${proxy.$dayjs().format("YYYY-MM-DD")}T${b.startTime}`));
  return newTimesXleList;
}

/**
 * @接收子页面传过来的值
 */
function onMessage(e) {
  controlStore.analysisData(e.detail.data[0]);
}
// #ifdef H5
window.onmessage = function (event) {
  controlStore.analysisData(event.data);
};
// #endif

function testAsyncFunc(imgUrl, index) {
  // 调用异步方法
  testModule.testAsyncFunc(
    {
      imgUrl: imgUrl,
    },
    (ret) => {
      console.log(ret);
    }
  );
}

const device = uni.requireNativePlugin("device");
function handleButton(){
  device.setLed("绿色");
}

onLoad((options) => {
  setTimeout(() => {
    init();
  }, 500);

  // const plugin = uni.requireNativePlugin("temp_plugin");
  // console.log(plugin);

  // console.log("设备名称:", plugin.getDeviceName());

  // plugin.showToast("我是原生插件Toast");


  console.log(device);

  console.log("IP地址:", device.getIpAddress());

  

  // device.invoke1();

  // console.log("序列号:", device.getSerialno());

  // console.log("分区信息:", device.getDeviceCustom(16));
  // device.setLed("蓝色");

  // 假设你已经配置好了uniapp的Android插件
  const main = plus.android.runtimeMainActivity();
  const Intent = plus.android.importClass("android.content.Intent");
  const MyActivity = plus.android.importClass("com.example.device.test"); // 替换为你的包名和Activity名

  // 创建一个Intent来启动你的Activity
  const intent = new Intent(main, MyActivity);

  // 添加需要的额外数据到intent
  intent.putExtra("com.example.device.test.setLed", "绿色");

  // 启动Activity
  main.sendBroadcast(intent);

  // var testModule = uni.requireNativePlugin("opencv_plugin");

  // console.log(testModule);

  // testModule.testAsyncFunc(
  //   {
  //     imgUrl: "https://img0.baidu.com/it/u=3389607,2584865022&fm=253&fmt=auto&app=138&f=PNG?w=449&h=645",
  //   },
  //   (ret) => {
  //     console.log(ret);
  //   }
  // );
});

onShow(() => {});

onUnload(() => {
  clearInterval(inter.interMeeting); //销毁之前定时器
});
</script>
<style>
.faceView {
  width: 100% !important;
  height: 100% !important;
}

iframe {
  width: 100% !important;
  height: 100% !important;
  border-width: 0;
}
</style>
<style lang="scss" scoped>
:deep() {
  .u-modal {
    width: 30rem !important;

    &__title {
      font-size: 18px !important;
    }
    .slot-content {
      font-size: 16px;
      width: 100%;
    }
  }
}
</style>
