<template>
  <div>
    <el-dialog
      v-model="visible"
      :title="titleOfUpdatePositionMonitorCamera"
      width="705px"
      align-center
      @close="handleClose"
      class="update-position-monitor-dialog"
    >
      <div v-loading="loading">
        <div class="position-name">
          <div class="position-name-title">部位名称：</div>
          <el-input
            v-model="positionName"
            maxlength="200"
            show-word-limit
            clearable
            style="width: 294px"
            placeholder="请输入部位名称"
          />
        </div>
        <div class="relate-camera">关联相机：</div>
        <div class="camera-select-section">
          <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),
                    }"
                  >
                    <div v-if="data.nodeType === CameraTreeNodeType.camera" class="icons">
                      <VideoCamera
                        class="cameraIcon"
                        :class="{
                          selectedCameraIcon: isSelected(data),
                        }"
                      />
                      <WarningFilled v-if="isInvalid(data)" class="invalidCamera" style="color: red" />
                    </div>
                    <div> {{ node.label }}</div>
                    <Thumbnail
                      v-if="data.nodeType === CameraTreeNodeType.camera"
                      :imageUrl="data.imageUrl"
                      :code="data.code"
                      position="right"
                    >
                      <div class="mask"></div>
                    </Thumbnail>
                  </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>
        </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>
  </div>
</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, ElMessage } from 'element-plus';
  import { VideoCamera, WarningFilled, Search } from '@element-plus/icons-vue';
  import Thumbnail from '@/components/thumbnail/Thumbnail.vue';
  import { usePositionMonitorCameraEdit } from '@/store/modules/usePositionMonitorCameraEdit';
  import { CameraTreeNodeType } from '@/api/camera/camera-preview';
  import { CameraInTree } from '@/api/disaster-overview';

  const positionMonitorCameraEdit = usePositionMonitorCameraEdit();
  const { titleOfUpdatePositionMonitorCamera, allCameraTree, nameOfPosition, selectedCameraIdsOfPosition } =
    storeToRefs(positionMonitorCameraEdit);
  const { getAllCameraTree } = positionMonitorCameraEdit;

  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 loading = ref(false);

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

  const isSelected = (data: CameraInTree) => {
    if (data.nodeType === '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 === '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() {
    // 校验部位名称
    if (!positionName.value || positionName.value.trim() === '') {
      ElMessage.error('请输入部位名称');
      return;
    }

    // 校验关联相机
    if (selectedItems.value.length === 0) {
      ElMessage.error('请至少选择一个关联相机');
      return;
    }

    selectedCameraIdsOfPosition.value = selectedItems.value;
    nameOfPosition.value = positionName.value;
    emits('confirm');
    resetAll();
  }

  // 取消/关闭按钮点击事件
  const handleClose = () => {
    emits('close'); // 更新父组件的 visible 状态
    resetAll();
  };

  function resetAll() {
    searchQuery.value = ''; // 清空搜索框
    selectedItems.value = []; // 清空已选择项
    positionName.value = ''; // 清空部位名称
  }

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

  onMounted(async () => {
    loading.value = true;
    await getAllCameraTree();
    selectedItems.value = JSON.parse(JSON.stringify(selectedCameraIdsOfPosition.value));
    positionName.value = nameOfPosition.value;
    loading.value = false;
  });
</script>

<style scoped lang="scss">
  .position-name {
    display: flex;
    align-items: center;
    margin-bottom: 25px;
  }

  .position-name-title,
  .relate-camera {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
  }

  .position-name-title::before,
  .relate-camera::before {
    content: '*';
    color: #ff4d4f;
    margin-right: 4px;
  }

  .relate-camera {
    margin-bottom: 12px;
  }

  .camera-select-section {
    width: 673px;
    height: 357px;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    display: flex;
    justify-content: space-evenly;
  }

  .camera-items {
    width: 300px;

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

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

  .selectedCamera {
    color: #1777ff;
  }

  .treeNode {
    display: flex;
    align-items: center;

    .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;
      }
    }
  }

  .mask {
    height: 26px;
    width: 100%;
  }

  :deep(.thumb-nail) {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 99;
  }

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

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

  .selected-items {
    width: 300px;

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

    .selected-items-tag {
      max-height: 272px;
      overflow: auto;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }

  :deep(.update-position-monitor-dialog) {
    .el-dialog__header {
      padding: 5px 5px 24px 4px;
    }

    .el-dialog__body {
      min-height: 450px;
    }
  }
</style>
