<template>
  <div ref="dragRef">
    <div class="camera" v-for="camera in groupSensors" :key="camera.id">
      <div class="IconAndCameraName">
        <div class="cameraIcon">
          <WarningFilled
            class="invalidCameraIcon"
            style="color: red"
            v-if="!carouselList.includes(camera) && playingGroup?.id === cameraGroup.id"
          />
          <img
            class="cameraImg"
            src="@/assets/icons//nine-square-grid/camera.png"
            v-if="!cameraInPlay.includes(camera)"
          />
          <img class="cameraImg" src="@/assets/icons/nine-square-grid/playingCamera.png" v-else />
        </div>

        <div
          class="cameraName"
          :class="{
            playingCamera: cameraInPlay.includes(camera),
            invalidCameraName: !carouselList.includes(camera) && playingGroup?.id === cameraGroup.id,
          }"
        >
          {{ camera.name }}
        </div>
      </div>

      <div class="cameraOperation">
        <img
          class="cameraOperationIcon"
          src="@/assets/icons/nine-square-grid/icon-delete.png"
          @click.stop="handleDelete(cameraGroup, camera)"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { computed, ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import type { ProductionSensorGroup, SensorDeviceViewItem, SensorGroupView } from '@/api/sensor-group/type';
  import { useCameraGroupList } from '@/store/modules/useCameraGroupList';
  import { WarningFilled } from '@element-plus/icons-vue';
  import { ElMessageBox } from 'element-plus';
  import { useDraggable } from 'vue-draggable-plus';
  import {
    deleteSensorFromGroupApi,
    querySensorGroupListApi,
    updateSensorGroupApi,
    updateSensorOrderApi,
  } from '@/api/sensor-group';
  import { userGridType } from '@/store/modules/userGridType';
  import { GridType } from '../../type';

  const props = defineProps<{
    cameraGroup: SensorGroupView;
  }>();
  const dragRef = ref<HTMLElement | null>(null);
  const list = ref<SensorDeviceViewItem[]>([]);
  const groupSensors = computed(() => {
    return props.cameraGroup.details;
  });

  const { carouselList, playingGroup, cameraInPlay, cameraGroupList, isPlaying, isPaused, playIntervalTime } =
    storeToRefs(useCameraGroupList());
  const { restartPlay, setPlayGroup, groupStartPlay } = useCameraGroupList();
  const { changeGridType } = userGridType();

  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,
        children: details,
      } as any;
    });
  }

  function handleDelete(cameraGroup: SensorGroupView, camera: SensorDeviceViewItem) {
    const text = '删除后，传感器数据不可恢复，是否确认删除？';
    ElMessageBox.confirm(text, '提示', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      customClass: 'customMessageBox--warning',
      lockScroll: false,
    })
      .then(async () => {
        await deleteSensorFromGroupApi({ groupId: cameraGroup.id, deviceNo: camera.code });

        const latestGroupList = await querySensorGroupListApi();
        cameraGroupList.value = normalizeSensorGroups(latestGroupList) as any;

        const defaultGroup = cameraGroupList.value.find((x) => x.isDefault === 1) as unknown as SensorGroupView;
        if (defaultGroup) {
          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);
        } else {
          cameraInPlay.value = cameraInPlay.value.map((x) =>
            x.id === camera.id
              ? {
                  ...x,
                  id: -Date.now(),
                  name: '',
                  code: '',
                }
              : x,
          );
          restartPlay();
        }
      })
      .catch(() => {
        return;
      });
  }

  watch(
    groupSensors,
    (children) => {
      list.value = children;
    },
    { immediate: true, deep: true },
  );

  useDraggable(dragRef, list, {
    animation: 150,
    ghostClass: 'ghost',
    onUpdate() {
      // eslint-disable-next-line vue/no-mutating-props
      props.cameraGroup.details = list.value;
      restartPlay();
      updateSensorOrderApi(
        list.value.map((s, idx) => ({
          groupId: props.cameraGroup.id,
          deviceNo: s.code,
          orderNum: idx + 1,
        })),
      );
    },
  });
</script>

<style lang="scss" scoped>
  .camera {
    height: 32px;
    width: 100%;
    white-space: nowrap;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 72px;
    font-size: 14px;
    line-height: 32px;
    color: #333333;
    text-align: left;
    background: #f4f7ff;
    position: relative;
    &:hover {
      background-color: #cdd8ff;
    }
    &:hover .cameraOperation {
      visibility: visible;
      display: flex;
      align-items: center;
    }

    .IconAndCameraName {
      display: flex;
      align-items: center;
      .cameraIcon {
        display: flex;
        align-items: center;
        position: relative;
        .cameraImg {
          height: 24px;
          width: 24px;
          margin-right: 12px;
        }
        .invalidCameraIcon {
          height: 14px;
          color: #dd5869;
          position: absolute;
          right: 6px;
          top: 0px;
        }
      }
      .cameraName {
        width: fit-content;
        position: relative;
      }
      .invalidCameraName {
        color: #999999;
      }
    }

    .cameraOperation {
      visibility: hidden;
      margin-right: 4px;
      .cameraOperationIcon {
        height: 20px;
        width: 20px;
        margin-left: 10px;
        padding: 2px;
        z-index: 999;
        &:hover {
          background-color: rgb(197, 197, 197);
          border-radius: 4px;
          cursor: pointer;
        }
      }
    }
  }
</style>
