<template>
  <div class="toolbar">
    <div class="control-row">
      <div style="display: flex">
        <div class="grid-switch">
          <el-tooltip effect="dark" content="一屏" placement="bottom">
            <img
              :src="currentGrid === GridType.oneGrid ? oneGrid_selected : oneGrid"
              class="grid-icon"
              :class="{ selected: currentGrid === GridType.oneGrid }"
              @click="handleChange(GridType.oneGrid)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="四屏" placement="bottom">
            <img
              :src="currentGrid === GridType.fourGrids ? fourGrids_selected : fourGrids"
              class="grid-icon"
              :class="{ selected: currentGrid === GridType.fourGrids }"
              @click="handleChange(GridType.fourGrids)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="九屏" placement="bottom">
            <img
              :src="currentGrid === GridType.nineGrids ? nineGrids_selected : nineGrids"
              class="grid-icon"
              :class="{ selected: currentGrid === GridType.nineGrids }"
              @click="handleChange(GridType.nineGrids)"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="十六屏" placement="bottom">
            <img
              :src="currentGrid === GridType.sixteenGrids ? sixteenGrids_selected : sixteenGrids"
              class="grid-icon"
              :class="{ selected: currentGrid === GridType.sixteenGrids }"
              @click="handleChange(GridType.sixteenGrids)"
            />
          </el-tooltip>
        </div>

        <div class="play-control">
          <div class="lock-btn" @click="handleClickLock">
            <el-tooltip effect="dark" :content="isPaused ? '恢复轮播' : '取消轮播'" placement="bottom">
              <img v-if="isPaused" src="@/assets/icons/nine-square-grid/lock.png" />
              <img v-else src="@/assets/icons/nine-square-grid/unlock.png" />
            </el-tooltip>
          </div>

          <div v-show="isPlaying && !isPaused" class="interval-input">
            <span>轮播间隔</span>
            <el-input
              v-model="playIntervalTime"
              ref="inputRef"
              placeholder="默认60"
              class="input"
              @blur="handelStartPlay"
              @keyup.enter="handelStartPlay"
            >
              <template #append>
                <div>秒</div>
              </template>
            </el-input>
          </div>
        </div>
      </div>

      <div style="display: flex">
        <div class="control-round">
          <div
            class="previous-round"
            :class="displayCurrentRound <= 1 ? 'disable-change-round' : ''"
            @click="playPreviousRound"
          >
            <el-tooltip effect="dark" content="上一轮" placement="bottom">
              <ArrowLeft />
            </el-tooltip>
          </div>

          <div class="rounds">
            <div class="current-round">{{ displayCurrentRound }}</div>
            <div class="total-round">/{{ displayTotalRound }}</div>
          </div>

          <div
            class="next-round"
            :class="displayCurrentRound >= displayTotalRound ? 'disable-change-round' : ''"
            @click="playNextRound"
          >
            <el-tooltip effect="dark" content="下一轮" placement="bottom">
              <ArrowRight />
            </el-tooltip>
          </div>
        </div>

        <div class="full-screen" @click="isFullScreen ? exitFullscreen() : fullScreen('video-grid', 'all')">
          <el-tooltip effect="dark" content="全屏" placement="bottom">
            <img src="@/assets/icons/nine-square-grid/fullScreen2.png" class="full-screen-icon" />
          </el-tooltip>
        </div>
      </div>
    </div>

    <div class="stats-row">
      <div class="stats">
        <div class="stat stat-blue">
          <div class="label">● 在线率</div>
          <div class="value">{{ groupStats.onlineRate }}</div>
        </div>
        <div class="stat stat-orange">
          <div class="label">● 异常</div>
          <div class="value">{{ groupStats.exceptionCount }}</div>
        </div>
        <div class="stat stat-green">
          <div class="label">● 离线</div>
          <div class="value">{{ groupStats.outlineCount }}</div>
        </div>
        <div class="stat stat-red">
          <div class="label">● 故障</div>
          <div class="value">{{ groupStats.failureCount }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, toRefs, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import { ElInput, ElTooltip } from 'element-plus';
  import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
  import { userSplitScreenFullScreen } from '@/store/modules/userSplitScreenFullScreen';
  import { useCameraGroupList } from '@/store/modules/useCameraGroupList';
  import { updateSensorGroupApi } from '@/api/sensor-group';
  import oneGrid from '@/assets/icons/nine-square-grid/oneGrid.png';
  import oneGrid_selected from '@/assets/icons/nine-square-grid/oneGrid-selected.png';
  import fourGrids from '@/assets/icons/nine-square-grid/fourGrids.png';
  import fourGrids_selected from '@/assets/icons/nine-square-grid/fourGrids-selected.png';
  import nineGrids from '@/assets/icons/nine-square-grid/nineGrids.png';
  import nineGrids_selected from '@/assets/icons/nine-square-grid/nineGrids-selected.png';
  import sixteenGrids from '@/assets/icons/nine-square-grid/sixteenGrids.png';
  import sixteenGrids_selected from '@/assets/icons/nine-square-grid/sixteenGrids-selected.png';

  export type LocalGridType = 1 | 4 | 9 | 16;

  const GridType = {
    oneGrid: 1,
    fourGrids: 4,
    nineGrids: 9,
    sixteenGrids: 16,
  } as const;

  const props = defineProps<{
    currentGrid: LocalGridType;
    isPlaying: boolean;
    isPaused: boolean;
    playIntervalTime: number;
    currentRound: number;
    totalRound: number;
  }>();

  const { currentGrid, isPlaying, isPaused, currentRound, totalRound } = toRefs(props);

  const emit = defineEmits<{
    (event: 'update:currentGrid', value: LocalGridType): void;
    (event: 'update:playIntervalTime', value: number): void;
    (event: 'prev-round'): void;
    (event: 'next-round'): void;
    (event: 'toggle-pause'): void;
  }>();

  const inputRef = ref();

  const { isFullScreen } = storeToRefs(userSplitScreenFullScreen());
  const { fullScreen, exitFullscreen } = userSplitScreenFullScreen();
  const { playingGroup, cameraGroupList } = storeToRefs(useCameraGroupList());

  function syncGroupState(payload: { refreshIntervalSec?: number; isPaused?: 0 | 1 }) {
    if (!playingGroup.value?.id) return;

    Object.assign(playingGroup.value as any, payload);
    const target = (cameraGroupList.value as any[]).find((x) => x.id === playingGroup.value?.id);
    if (target) {
      Object.assign(target, payload);
    }
  }

  const groupStats = computed(() => {
    const g = playingGroup.value as any;
    return {
      onlineRate: g?.onlineRate ?? '--',
      exceptionCount: g?.exceptionCount ?? '--',
      outlineCount: g?.outlineCount ?? '--',
      failureCount: g?.failureCount ?? '--',
    };
  });

  const playIntervalTime = computed({
    get: () => props.playIntervalTime,
    set: (value: number | string) => {
      const numValue = Number(value);
      emit('update:playIntervalTime', Number.isNaN(numValue) ? 60 : numValue);
    },
  });

  function handleChange(value: LocalGridType) {
    emit('update:currentGrid', value);
  }

  async function handelStartPlay() {
    if (playIntervalTime.value === null || playIntervalTime.value === 0 || !Number(playIntervalTime.value)) {
      inputRef.value?.blur();
      emit('update:playIntervalTime', 60);
      return;
    }

    if (playingGroup.value?.id) {
      const interval = Number(playIntervalTime.value);
      await updateSensorGroupApi({
        groupId: playingGroup.value.id,
        refreshIntervalSec: interval,
      });
      syncGroupState({ refreshIntervalSec: interval });
    }

    inputRef.value?.blur();
    emit('update:playIntervalTime', Number(playIntervalTime.value));
  }

  async function handleClickLock() {
    if (playingGroup.value?.id && isPlaying.value) {
      const nextIsPaused = (isPaused.value ? 1 : 0) as 0 | 1;
      await updateSensorGroupApi({
        groupId: playingGroup.value.id,
        isPaused: nextIsPaused,
      });
      syncGroupState({ isPaused: nextIsPaused });
    }
    emit('toggle-pause');
  }

  function playPreviousRound() {
    emit('prev-round');
  }

  function playNextRound() {
    emit('next-round');
  }

  watch(
    () => isPlaying.value,
    (value) => {
      if (value) {
        inputRef.value?.focus();
        inputRef.value?.select();
      }
    },
  );

  const displayCurrentRound = computed(() => (currentRound.value <= 0 ? 1 : currentRound.value));
  const displayTotalRound = computed(() => (totalRound.value <= 0 ? 1 : totalRound.value));
</script>

<style lang="scss" scoped>
  .toolbar {
    min-height: 148px;
    width: 100%;
    background: #f4f7ff;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    gap: 10px;
    padding: 10px 12px;
    border-radius: 4px 4px 0 0;

    .control-row {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-height: 46px;
      border: 1px solid #d8e3f6;
      border-radius: 4px;
      background: linear-gradient(180deg, #ffffff 0%, #fbfdff 100%);
      padding: 0 10px;
    }

    .grid-switch {
      display: flex;
      align-items: center;
      gap: 12px;

      .grid-icon {
        width: 24px;
        height: 24px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.2s;
      }

      .grid-icon:hover,
      .grid-icon.selected {
        outline: 1px solid #1777ff;
        background: #f2f7ff;
      }
    }

    .play-control {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-left: 20px;

      .lock-btn {
        display: flex;
        align-items: center;
        cursor: pointer;

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

      .interval-input {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #355a9b;

        .input {
          width: 130px;
        }
      }
    }

    .control-round {
      display: flex;
      align-items: center;
      gap: 8px;

      .previous-round,
      .next-round {
        width: 18px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #3a4f73;
        border-radius: 4px;
        cursor: pointer;

        &:hover {
          background-color: #eef5ff;
        }
      }

      .disable-change-round {
        color: #b7c2d6;
        pointer-events: none;
      }

      .rounds {
        display: flex;
        align-items: baseline;
        min-width: 58px;
        justify-content: center;

        .current-round {
          color: #1777ff;
          font-weight: 600;
          font-size: 16px;
        }

        .total-round {
          color: #9aacbf;
          font-size: 14px;
        }
      }
    }

    .full-screen {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 20px;
    }

    .full-screen-icon {
      width: 22px;
      height: 22px;
    }

    .stats-row {
      width: 100%;
    }

    .stats {
      display: flex;
      gap: 10px;

      .stat {
        width: 160px;
        height: 78px;
        border: 1px solid #d8e3f6;
        border-radius: 4px;
        padding: 10px 14px;
        background: linear-gradient(180deg, #ffffff 0%, #f7fbff 100%);
        box-shadow: 0 1px 6px rgba(23, 119, 255, 0.06);

        .label {
          font-size: 16px;
          line-height: 1;
          font-weight: 500;
          margin-bottom: 8px;
        }

        .value {
          font-size: 30px;
          line-height: 1;
          font-weight: 600;
        }
      }

      .stat-blue {
        color: #4b84ff;
      }

      .stat-orange {
        color: #f4a13e;
      }

      .stat-green {
        color: #1fb45a;
      }

      .stat-red {
        color: #ff5f5f;
      }
    }
  }

  @media screen and (max-width: 1380px) {
    .toolbar {
      .stats {
        flex-wrap: wrap;
      }

      .control-row {
        flex-wrap: wrap;
        height: auto;
        padding: 8px 10px;
        gap: 8px;
      }
    }
  }
</style>
