<template>
  <div class="lighting-box">
    <div class="lighting-img-box" :class="{ lightingImgBox1: thisFloor == '2' }">
      <!-- 左上角，区域切换 -->
      <div class="btn-box">
        <button
          v-for="(item, index) in floorData"
          :key="index"
          class="btn-item"
          :class="{ btnActive: item.dataCode == thisFloor }"
          @click="changeFloor(item.childList, item.dataCode)"
          >{{ item.name }}</button
        >
      </div>
      <!-- 楼层区域 -->
      <div class="area">
        <div
          v-for="(item, index) in treeData"
          :class="computedClass(item.id)"
          @click="changeThisArea([item])"
          :key="index">
          <div v-for="(v, i) in item.childList" :key="i" class="light-group">
            <div class="group-shadow" @click.stop="changeThisArea([item, v])">
              <div :class="computedClass(v.id)" class="shadow-box"></div>
            </div>
          </div>
        </div>
      </div>
      <!-- 照明设备 -->
      <div class="lights">
        <light v-for="(blub, index) in bulbs" :key="index" :blub="blub" />
      </div>
    </div>
    <!-- 右侧抽屉 -->
    <a-drawer
      v-model:visible="visible"
      class="drawer-item"
      width="496"
      :forceRender="preload"
      placement="right"
      :body-style="{ background: 'rgba(0, 0, 0)', opacity: 0.8 }"
      :closable="false"
      id="drawer"
      :maskStyle="{ 'background-color': 'rgba(0, 0, 0, 0)' }">
      <div class="drawer-box-out" @click="toggleDrawer">
        <double-left-outlined v-if="!visible" class="drawer-icon" style="color: white" />
        <double-right-outlined v-else class="drawer-icon" style="color: white" />
      </div>
      <a-tabs v-model:activeKey="activeKey">
        <a-tab-pane key="1" tab="控制面板">
          <tabs1
            ref="tabs1Ref"
            @reset="reset"
            @reload="reload"
            @reset-all="resetDrawer"
            @change-area="changeArea"
            :treeData="treeData" />
        </a-tab-pane>
        <a-tab-pane key="2" tab="计划列表" force-render>
          <tabs2 ref="tabs2Ref" @reset-all="resetDrawer" />
        </a-tab-pane>
        <a-tab-pane key="3" tab="日志">
          <tabs3 ref="tabs3Ref" @reset-all="resetDrawer" />
        </a-tab-pane>
      </a-tabs>
    </a-drawer>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { lightPosition, lightPosition1 } from './lightPosition';
  // 组件
  import light from './light.vue';
  import tabs1 from './tabs1.vue';
  import tabs2 from './tabs2.vue';
  import tabs3 from './tabs3.vue';
  // 请求
  import { http } from '/nerv-lib/util/http';
  import { lightingManage } from '/@/api/IlluminationInfo';
  // ICON
  import { DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons-vue';
  import { message, Modal } from 'ant-design-vue';
  // 全局变量
  import { items } from '/@/store/item';

  // 初始化 =======================================================

  onMounted(() => {
    // 获得分区与线路的结构
    getAllArea();
    // 获得俯视图中的小灯泡
    getBulbs();
  });

  // 获得全局变量
  const state = items();
  // 预加载flag，获得分区数据后，预加载抽屉，防止获取ref报错
  const preload = ref(false);

  // 分层业务 =====================================================

  // 所有楼层的数据
  const floorData = ref([]);
  // 当前选择的楼层
  const thisFloor = ref('1');
  // 左上角分层切换
  const changeFloor = (area: any, floor: string) => {
    if (floor == thisFloor.value) {
      return message.info('已选择此楼层');
    }
    Modal.confirm({
      title: '提示信息',
      content: '切换楼层会放弃已保存的修改内容',
      onOk() {
        // 切换前还原修改内容
        tabs1Ref.value.refresh(false);
        // 清空设备点阵
        bulbs.value = [];
        thisFloor.value = floor;
        getBulbs();
        // 重置数据
        reset();
        // 重置视图
        changeArea(['1']);
        // 切换楼层数据
        treeData.value = area;
        // 默认选择第一项
        treeData.value[0].selected = true;
        tabs1Ref.value.changeArea(treeData.value[0]);
      },
      onCancel() {},
    });
  };

  // 分区业务 =====================================================

  // 分区结构树
  const treeData = ref([]);
  // 当前选中的分区序列 - 用于样式渲染
  const area = ref(['1']);
  // 线路内小灯泡 - 此处位置需前端写死
  const bulbs = ref([]);
  // 由子组件控制的分区与线路切换
  const changeArea = (result: any) => {
    console.log(result, 'changeArea');
    // 数组
    if (Array.isArray(result)) {
      area.value = result;
      // 不是数组
    } else {
      area.value.length = 0;
      area.value[0] = String(result);
    }
  };
  // 由当前组件控制的分区切换
  const changeThisArea = (result: any) => {
    console.log(result, 'changeThisArea');
    // 修改前，将所有选项置空
    reset();
    let level1 = result[0];
    area.value.length = 0;
    // 只选择了分区
    if (result.length === 1) {
      result[0].selected = true;
      area.value.push(result[0].id);
      // 控制子组件按钮区
      tabs1Ref.value.changeArea(result[0]);
      // 选择了分区 + 线路
    } else if (result.length === 2) {
      // 如果没有分区，默认选择第一个
      if (!level1) {
        level1 = treeData.value[0];
      }
      // 选中状态都设为true
      level1.selected = result[1].selected = true;
      area.value.splice(0, 0, level1.id, result[1].id);
      // 控制子组件按钮区
      tabs1Ref.value.changeArea(result[0]);
      tabs1Ref.value.changeLine(result[1]);
    }
  };
  // 重置分区树所有当前选项
  const reset = () => {
    treeData.value.forEach((item: any) => {
      item.selected = false;
      item.childList.forEach((i: any) => {
        i.selected = false;
      });
    });
  };
  // 俯视图分区选中计算函数
  const computedClass = (string: string) => {
    if (area.value.indexOf(string) != -1) {
      return `isActive area-item area${string}`;
    } else {
      return `area-item area${string}`;
    }
  };

  // 获得所有分区
  const getAllArea = (realod = false) => {
    http.get(lightingManage.getTree, { projectId: state.projectId }).then((res) => {
      const data = res.data;
      floorData.value = data;
      /** 只在前端使用的变量
       * @param id 用于判断样式和层级的前端属性
       * @param selected 用于表示是否选中的前端属性
       */
      data.forEach((floor: any) => {
        floor.childList.forEach((item: any, index: number) => {
          if (index == 0) {
            item.selected = true;
          } else {
            item.selected = false;
          }
          item.id = String(index + 1);
          item.childList.forEach((v: any, i: number) => {
            v.selected = false;
            v.id = index + 1 + '-' + (i + 1);
          });
        });
      });
      // 默认展示 线路 1-1,重载则使用thisFloor当前选中的楼层数
      let index = 0;
      if (realod) {
        data.find((item: any, i: number) => {
          if (item.dataCode == thisFloor.value) {
            return (index = i);
          }
        });
      }
      treeData.value = data[index].childList;
      // 反向刷新
      try {
        tabs1Ref.value.setButtons2(treeData.value[0].childList);
      } catch {}
      // 开始预加载
      preload.value = true;
    });
  };
  const reload = () => {
    getAllArea(true);
  };

  // 设备业务 小灯泡 ==============================================

  const getBulbs = () => {
    const floor = thisFloor.value;
    let arr: Array<Object> = [];
    if (floor == '1') {
      arr = lightPosition;
    } else if (floor == '2') {
      arr = lightPosition1;
    }
    http
      .get(lightingManage.getBulbs, {
        floor,
        projectId: state.projectId,
        siteId: state.siteId,
      })
      .then((res) => {
        const data = res.data;
        data.forEach((item: any, index: number) => {
          item.styleText = arr[index];
        });
        bulbs.value = data;
      });
  };

  // 抽屉业务 =====================================================

  // 抽屉 - 当前选择的tab
  let activeKey = ref('1');
  // 抽屉 - 打开状态
  let visible = ref(false);
  // 抽屉 - 开关事件
  const toggleDrawer = () => {
    visible.value = !visible.value;
  };
  // 当其中一个tab产生了数据修改，可以调用该方法重置所有tab
  const resetDrawer = () => {
    // 设备点阵重置
    getBulbs();
    // tab1重置
    reload();
    tabs1Ref.value.refresh();
    // tab2 tab3 可能未加载
    try {
      // tab2重置
      tabs2Ref.value.reset();
    } catch {}
    try {
      // tab3重置
      tabs3Ref.value.reset();
    } catch {}
  };
  // 抽屉tab1组件的引用
  const tabs1Ref = ref();
  // 抽屉tab2组件的引用
  const tabs2Ref = ref();
  // 抽屉tab3组件的引用
  const tabs3Ref = ref();
</script>
<style lang="less" scoped>
  @import './index.less';

  // 当前选中分区的样式
  .isActive {
    border: 3px solid white !important;
  }

  // 抽屉顶部tab按钮样式
  :deep(.ant-tabs-tab-btn) {
    color: white;
  }
</style>
