<template>
  <el-dialog
    v-model="visible"
    title="编辑监测区域相机"
    width="700px"
    @close="handleClose"
    class="update-monitor-dialog"
  >
    <div class="camera-items">
      <el-input class="search-bar" v-model="searchQuery" placeholder="请输入搜索内容" clearable :prefix-icon="Search" />
      <div class="tree-container">
        <el-tree
          class="camera-tree"
          ref="treeRef"
          :data="allCameraTree"
          :props="defaultProps"
          node-key="code"
          default-expand-all
          show-checkbox
          :filter-node-method="filterNode"
          @check-change="handleCheckChange"
        >
          <template #default="{ node, data }">
            <div
              class="treeNode"
              :class="{
                selectedCamera: isSelected(data),
              }"
            >
              <Thumbnail
                v-if="data.nodeType === CameraTreeNodeType.camera"
                :imageUrl="data.imageUrl"
                :code="data.code"
                position="right"
              >
                <div class="iconAndCameraName">
                  <div class="icons">
                    <VideoCamera
                      class="cameraIcon"
                      :class="{
                        selectedCameraIcon: isSelected(data),
                      }"
                    />
                    <WarningFilled v-if="isInvalid(data)" class="invalidCamera" style="color: red" />
                  </div>
                  <div class="cameraName">
                    {{ node.label }}
                  </div>
                </div>
              </Thumbnail>
              <template v-else>
                <div class="cameraName">
                  {{ node.label }}
                </div>
              </template>
            </div>
          </template>
        </el-tree>
      </div>
    </div>
    <div class="divider"></div>
    <div class="selected-items">
      <div class="selected-title">已选择：</div>
      <div class="selected-items-tag">
        <el-tag v-for="item in selectedItems" :key="item.id" closable type="primary" @close="handleCloseTag(item)">
          {{ item.name }}
        </el-tag>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, ref, watch } from 'vue';
  import { storeToRefs } from 'pinia';
  import type { TreeInstance } from 'element-plus';
  import { ElDialog, ElInput, ElTree, ElTag, ElButton } from 'element-plus';
  import { VideoCamera, WarningFilled, Search } from '@element-plus/icons-vue';
  import Thumbnail from '@/components/thumbnail/Thumbnail.vue';
  import { useMonitorCameraEdit } from '@/store/modules/useMonitorCameraEdit';
  import { CameraTreeNodeType } from '@/api/camera/camera-preview';
  import { CameraInTree } from '@/api/disaster-overview';

  const monitorCameraEdit = useMonitorCameraEdit();
  const { allCameraTree, selectedCameraIds } = storeToRefs(monitorCameraEdit);
  const { getAllCameraTree } = monitorCameraEdit;

  interface Tree {
    [key: string]: any;
  }

  interface SelectedCameraIds {
    id: number;
    name: string;
    code: string;
  }

  const defaultProps = {
    children: 'children',
    label: 'name',
  };

  const emits = defineEmits(['close', 'confirm']);

  const visible = ref(true);
  const treeRef = ref<TreeInstance>();
  const searchQuery = ref(''); // 搜索框内容
  const selectedItems = ref<SelectedCameraIds[]>([]); // 已选择的相机列表

  const isSelected = (data: CameraInTree) => {
    if (data.nodeType === CameraTreeNodeType.camera) return selectedItems.value.find((x) => x.id === data.id);
  };

  const isInvalid = (data) => {
    if (data.networkingState !== 0) data.disable = true;
    return data.networkingState !== 0;
  };

  watch(searchQuery, (val) => {
    treeRef.value!.filter(val);
  });

  const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.name.includes(value);
  };

  // 处理树节点的勾选变化
  function handleCheckChange(data: CameraInTree, checked: boolean) {
    if (checked && data.nodeType === CameraTreeNodeType.camera) {
      if (!selectedItems.value.find((x) => x.id === data.id)) {
        selectedItems.value.push({
          id: data.id,
          name: data.name,
          code: data.code,
        });
      }
    } else {
      selectedItems.value = selectedItems.value.filter((x) => x.id !== data.id);
    }
  }

  // 处理标签关闭
  function handleCloseTag(camera: SelectedCameraIds) {
    const index = selectedItems.value.find((x) => x.code === camera.code);
    if (index) treeRef.value?.setChecked(camera, false, true);
  }

  // 确认按钮点击事件
  function handleConfirm() {
    emits('confirm', selectedItems.value); // 触发父组件的 confirm 事件
    searchQuery.value = ''; // 清空搜索框
    selectedItems.value = []; // 清空已选择项
  }

  // 取消/关闭按钮点击事件
  const handleClose = () => {
    emits('close'); // 更新父组件的 visible 状态
    searchQuery.value = ''; // 清空搜索框
    selectedItems.value = []; // 清空已选择项
  };

  watch(
    () => selectedCameraIds.value,
    (newVal) => {
      const selectedCodes = newVal.map((item) => item.code);
      nextTick(() => {
        if (!treeRef.value) return;
        treeRef.value.setCheckedKeys(selectedCodes, true);
      });
    },
    {
      immediate: true,
    },
  );

  onMounted(async () => {
    await getAllCameraTree();
    selectedItems.value = JSON.parse(JSON.stringify(selectedCameraIds.value));
  });
</script>

<style scoped lang="scss">
  .camera-items {
    width: 300px;

    .search-bar {
      margin-bottom: 20px;
    }

    .camera-tree {
      max-height: 500px;
      overflow: auto;
    }
  }

  .selectedCamera {
    color: #1777ff;
  }

  .treeNode {
    display: flex;
    align-items: center;
    position: relative;
    width: 100%;

    .iconAndCameraName {
      display: flex;
      align-items: center;
      width: 100%;

      .icons {
        display: flex;
        align-items: center;
        position: relative;

        .cameraIcon {
          height: 18px;
          margin-right: 8px;
          color: rgb(112, 112, 112);
        }

        .selectedCameraIcon {
          color: #1777ff;
        }

        .invalidCamera {
          height: 14px;
          color: #dd5869;
          position: absolute;
          right: 0px;
          top: -5px;
        }
      }

      .cameraName {
        width: fit-content;
        position: relative;
      }
    }

    .cameraName {
      flex: 1;
    }
  }

  :deep(.thumb-nail) {
    display: flex;
    align-items: center;
    flex: 1;
    height: 100%;
  }

  :deep(.thumb-nail > div) {
    width: 100%;
    height: 100%;
  }

  :deep(.el-tree-node__content) {
    position: relative;
  }

  .divider {
    width: 1px;
    background-color: #e0e0e0;
    margin: 0 20px;
  }

  .selected-items {
    width: 300px;

    .selected-title {
      font-size: 16px;
      margin: 3px 0 25px 0;
    }

    .selected-items-tag {
      max-height: 500px;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
</style>

<style lang="scss">
  .update-monitor-dialog .el-dialog__header {
    padding: 5px 5px 20px 6px;
  }

  .update-monitor-dialog .el-dialog__body {
    min-height: 500px;
    display: flex;
    justify-content: space-evenly;
  }
</style>
