<template>
  <div class="cameraGroups__decoration"></div>

  <div class="cameraGroups">
    <div class="createGroup" @click="handleCreateGroup">
      <div class="createGroupIcon">
        <img src="@/assets/icons/nine-square-grid/add.png" />
      </div>
      <div>添加监控区域</div>
    </div>

    <div class="createGroupInput" v-show="showCreateGroupInput">
      <img class="folderIcon" src="@/assets/icons/nine-square-grid/folder-white.png" />
      <el-input
        v-model="inputNewGroupName"
        class="GroupNameInput"
        placeholder="为此区域命名"
        maxlength="15"
        show-word-limit
        ref="groupNameInputRef"
        @blur="handleEnterGroupName()"
        @keyup.enter="$event.target.blur()"
      />
    </div>

    <div class="groupList">
      <el-scrollbar>
        <el-collapse v-model="activeGroup">
          <div ref="groupDragRef">
            <div v-for="cameraGroup in groupListData" :key="cameraGroup.id">
              <CameraGroup :cameraGroup="cameraGroup" :activeGroup="activeGroup" />
            </div>
          </div>
        </el-collapse>
      </el-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, nextTick, onMounted, computed, watch } from 'vue';
  import { ElInput, ElScrollbar, ElCollapse, ElMessage } from 'element-plus';
  import CameraGroup from './CameraGroup.vue';
  import { useCameraGroupList } from '@/store/modules/useCameraGroupList';
  import {
    addSensorGroupApi,
    querySensorGroupListApi,
    updateSensorGroupApi,
    updateSensorGroupOrderApi,
  } from '@/api/sensor-group';
  import type { ProductionSensorGroup, SensorGroupView, SensorDeviceViewItem } from '@/api/sensor-group/type';
  import { storeToRefs } from 'pinia';
  import { userGridType } from '@/store/modules/userGridType';
  import { GridType } from '../../type';
  import { useDraggable } from 'vue-draggable-plus';

  const activeGroup = ref(['']);
  const showCreateGroupInput = ref(false);
  const inputNewGroupName = ref('');
  const groupNameInputRef = ref();
  const groupDragRef = ref<HTMLElement | null>(null);
  const groupListData = ref<SensorGroupView[]>([]);
  const { cameraGroupList, isPlaying, isPaused, playIntervalTime } = storeToRefs(useCameraGroupList());
  const { setPlayGroup, groupStartPlay } = useCameraGroupList();
  const { changeGridType } = userGridType();
  const sensorGroupList = computed(() => cameraGroupList.value as unknown as SensorGroupView[]);

  watch(
    sensorGroupList,
    (val) => {
      groupListData.value = val;
    },
    { immediate: true, deep: true },
  );

  useDraggable(groupDragRef, groupListData, {
    animation: 150,
    ghostClass: 'ghost',
    onUpdate() {
      cameraGroupList.value = groupListData.value as any;
      updateSensorGroupOrderApi(groupListData.value.map((g, idx) => ({ id: g.id, orderNum: idx + 1 })));
    },
  });

  function normalizeSensorGroups(list: ProductionSensorGroup[]): SensorGroupView[] {
    return (list || []).map((group) => {
      const details: SensorDeviceViewItem[] = (group.details || []).map((detail) => ({
        id: detail.sensorId,
        code: detail.deviceNo,
        name: detail.deviceName,
        status: detail.status,
      }));

      return {
        ...group,
        isPaused: group.isPaused ?? 1,
        details,
        // store 的 carouselList 通过 .children 读取播放列表，必须同步
        children: details,
      } as any;
    });
  }

  async function loadSensorGroupList() {
    const res = await querySensorGroupListApi();
    cameraGroupList.value = normalizeSensorGroups(res) as any;

    // 查找 isDefault === 1 的分组并自动播放
    const defaultGroup = cameraGroupList.value.find((x) => x.isDefault === 1) as unknown as SensorGroupView;
    if (defaultGroup) {
      activeGroup.value = [defaultGroup.groupName];
      // 自动启动播放
      await updateSensorGroupApi({
        groupId: defaultGroup.id,
        isDefault: 1,
      });

      isPlaying.value = true;
      setPlayGroup({ ...(defaultGroup as any), children: defaultGroup.details } as any);
      playIntervalTime.value = defaultGroup.refreshIntervalSec || 60;
      isPaused.value = !defaultGroup.isPaused;
      changeGridType(GridType.nineGrids);
      groupStartPlay(playIntervalTime.value);
    }
  }

  function handleCreateGroup() {
    showCreateGroupInput.value = !showCreateGroupInput.value;
    if (showCreateGroupInput.value) {
      checkGroupName();

      nextTick(() => {
        groupNameInputRef.value.focus();
      });
    }
  }

  async function handleEnterGroupName() {
    checkGroupName();
    const groupName = inputNewGroupName.value.trim();
    if (!groupName) {
      showCreateGroupInput.value = false;
      return;
    }
    if (cameraGroupList.value.find((x) => x.groupName === groupName)) return;

    try {
      const res = await addSensorGroupApi({ groupName });
      const newGroup = {
        id: (res as any).data,
        groupName,
        isDefault: 0,
        isPaused: 1,
        refreshIntervalSec: 60,
        details: [],
        children: [],
      } as unknown as SensorGroupView;
      cameraGroupList.value = [newGroup, ...(cameraGroupList.value as any)] as any;
      inputNewGroupName.value = '';
      showCreateGroupInput.value = false;
    } catch (error) {
      ElMessage({ message: '新建分组失败', type: 'error' });
    }
  }

  function checkGroupName() {
    if (inputNewGroupName.value === '') {
      let maxSuffix = 0;
      cameraGroupList.value.map((x) => {
        if (x.groupName.startsWith('新建区域')) {
          const suffix = Number(x.groupName.replace('新建区域', ''));
          // 过滤区域名后缀不是数字的区域
          if (!isNaN(suffix)) {
            if (suffix > maxSuffix) {
              maxSuffix = suffix;
            }
          }
        }
      });

      if (maxSuffix !== 0) {
        const newDefaultGroupNameIndex = maxSuffix + 1;

        inputNewGroupName.value = '新建区域' + newDefaultGroupNameIndex;
      } else {
        inputNewGroupName.value = '新建区域1';
      }
    }
  }

  onMounted(() => {
    loadSensorGroupList();
  });
</script>

<style lang="scss" scoped>
  .cameraGroups__decoration {
    height: 5px;
    margin-bottom: 20px;
    border-radius: 8px 8px 0 0;
    background-color: #1777ff;
  }

  .cameraGroups {
    height: calc(100% - 25px);
    color: #333333;
    padding: 0px 16px;
    padding-right: 4px;
    transition: all 0.3s ease;

    .createGroup {
      height: 24px;
      width: 120px;
      display: flex;
      margin-right: 12px;
      margin-bottom: 12px;
      color: #333333;
      font-size: 14px;
      line-height: 24px;
      cursor: pointer;

      .createGroupIcon {
        margin-right: 12px;
        position: relative;

        img {
          height: 24px;
          width: 24px;
        }

        &::after {
          content: '+';
          position: absolute;
          top: -1px;
          left: 0;
          right: 0;
          font-size: 20px;
          font-weight: 500;
          color: #1777ff;
          text-align: center;
        }
      }
    }

    .createGroupInput {
      height: 32px;
      display: flex;
      align-items: center;
      background-color: #1677ff;
      border-radius: 4px;
      margin-bottom: 12px;
      padding-right: 6px;
      color: #333333;
      font-size: 14px;
      line-height: 24px;
      .folderIcon {
        height: 24px;
        margin-right: 12px;
      }
      .GroupNameInput {
        height: 24px;
      }
    }
    .groupList {
      height: 80%;

      padding: 0 0px;
      overflow: auto;
    }
  }

  :deep(.el-collapse) {
    border: 0px;
  }
  :deep(.el-collapse-item__arrow) {
    margin-right: 12px;
    color: #333333;
  }

  :deep(.el-collapse-item__wrap) {
    background: transparent;
    border-bottom: transparent;
  }
  :deep(.el-collapse-item__content) {
    padding: 0px;
    margin-right: 10px;
  }
  :deep(.el-collapse-item__header) {
    background: #f4f7ff;
    border: 0px;
    flex-direction: row-reverse;
    padding-left: 12px;
    margin-right: 10px;
  }
</style>
