<template>
  <div class="right-layout">
    <div class="right-content">
      <el-form :inline="false" v-if="router.currentRoute.value.name === 'map'">
        <!-- <el-form-item v-if="relics">
          <el-input v-model="relicsName" :maxlength="50" placeholder="不可移动文物名称">
            <template #append>
              <el-button type="primary" @click="updateRelics">修改</el-button>
            </template>
          </el-input>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" :icon="Plus" style="width: 100%" @click="addHandler">
            添加场景
          </el-button>
        </el-form-item>
      </el-form>
      <div class="tree-layout">
        <p>全部数据</p>
        <el-tree
          style="max-width: 600px"
          :data="treeNode"
          :props="{ disabled: 'run' }"
          node-key="id"
          ref="treeRef"
          :show-checkbox="router.currentRoute.value.name === 'map'"
          default-expand-all
          :expand-on-click-node="false"
        >
          <template #default="{ node, data }">
            <div
              class="tree-item"
              @click="!data.disable && emit((data.type === 'scene' ? 'flyScene' : 'flyPoint') as any, data.raw)"
            >
              <el-tooltip
                v-if="data.type === 'scene'"
                class="box-item"
                effect="dark"
                :content="data.raw.sceneName + ' ' + node.label"
                placement="top"
              >
                <span :class="{ disable: data.disable }" class="title">
                  <el-icon> <Grid /> </el-icon>
                  {{ data.raw.sceneName }}
                  <span class="tree-scene-name">{{ node.label }}</span>
                </span>
              </el-tooltip>
              <el-tooltip
                v-else
                class="box-item"
                effect="dark"
                :content="node.label"
                placement="top"
              >
                <span :class="{ disable: data.disable }" class="title">
                  <el-icon>
                    <LocationInformation v-if="!data.disable" />
                    <DeleteLocation v-else />
                  </el-icon>
                  {{ node.label }}
                </span>
              </el-tooltip>
              <span class="oper">
                <template v-if="router.currentRoute.value.name === 'map'">
                  <template v-if="data.type === 'scene'">
                    <el-icon color="#409efc" v-if="data.raw.creationMethod !== 2">
                      <Delete @click.stop="delSceneHandler([data.raw])" />
                    </el-icon>
                  </template>
                  <el-icon v-else color="#409efc">
                    <Edit @click.stop="inputPoint = data.raw" />
                  </el-icon>
                </template>
                <el-icon color="#409efc" style="margin-left: 8px">
                  <Link
                    v-if="!data.run"
                    @click.stop="
                      data.type === 'scene'
                        ? gotoScene(data.raw)
                        : emit('gotoPoint', data.raw)
                    "
                  />
                </el-icon>
              </span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <template v-if="router.currentRoute.value.name === 'map'">
      <el-button
        type="primary"
        :icon="Download"
        style="width: 100%"
        @click="exportFile(getSelectPoints(), 2)"
      >
        导出本体边界坐标
      </el-button>
      <el-button
        type="primary"
        :icon="Download"
        style="width: 100%; margin-top: 20px; margin-left: 0"
        @click="exportFile(getSelectPoints(), 1)"
      >
        导出绘制矢量数据
      </el-button>

      <el-button
        type="primary"
        :icon="Download"
        style="width: 100%; margin-top: 20px; margin-left: 0"
        @click="exportImage(getSelectPoints(), relics?.name)"
      >
        下载全景图
      </el-button>
    </template>
  </div>

  <SingleInput
    :visible="!!inputPoint"
    @update:visible="inputPoint = null"
    :value="inputPoint?.name || ''"
    :update-value="updatePointName"
    title="修改点位名称"
  />
</template>

<script setup lang="ts">
import {
  Plus,
  Delete,
  Grid,
  Download,
  LocationInformation,
  DeleteLocation,
  Edit,
  Link,
} from "@element-plus/icons-vue";
import { computed, ref, watchEffect } from "vue";
import {
  Scene,
  scenes,
  ScenePoint,
  updateScenePointName,
  gotoScene,
  relicsId,
  refreshScenes,
} from "@/store/scene";
import { relics } from "@/store/relics";
import SingleInput from "@/components/single-input.vue";
import { router } from "@/router";
import { selectScenes } from "../quisk";
import { addRelicsScenesFetch, delRelicsScenesFetch } from "@/request";
import { exportFile, exportImage } from "./pc4Helper";
import { SceneStatus } from "@/store/scene";

const emit = defineEmits<{
  (e: "flyScene", data: Scene): void;
  (e: "flyPoint", data: ScenePoint): void;
  (e: "gotoPoint", data: ScenePoint): void;
}>();

const inputPoint = ref<ScenePoint | null>(null);
const updatePointName = async (title: string) => {
  await updateScenePointName(inputPoint.value!, title);
};

const relicsName = ref("");
watchEffect(() => (relicsName.value = relics.value?.name || ""));
// const updateRelics = async () => {
//   await updateRelicsName(relicsName.value);
//   ElMessage.success("修改成功");
// };

const treeRef = ref<any>();
const treeNode = computed(() =>
  scenes.value.map((scene) => ({
    label: scene.sceneCode,
    id: scene.id,
    type: "scene",
    run: scene.calcStatus !== SceneStatus.SUCCESS,
    disable: scene.scenePos.every((pos) => !pos.pos || pos.pos.length === 0),
    raw: scene,
    children: scene.scenePos.map((pos) => ({
      label: pos.name,
      run: scene.calcStatus !== SceneStatus.SUCCESS,
      disable: !pos.pos || pos.pos.length === 0,
      id: pos.id,
      type: "point",
      raw: { ...pos, cameraType: scene.cameraType },
    })),
  }))
);

const getSelectPoints = () =>
  treeRef
    .value!.getCheckedNodes(false, false)
    .filter((option: any) => option.type === "point")
    .map((option: any) => option.raw) as ScenePoint[];

const addHandler = async () => {
  const sceneCodes = scenes.value.map((scene) => scene.sceneCode);
  await selectScenes({
    scenes: scenes.value,
    selfScenes: scenes.value.filter((scene) => scene.creationMethod === 2),
    submit: async (nScene) => {
      const requests: Promise<any>[] = [];
      const delScenes = sceneCodes
        .filter((sceneCode) => !nScene.some((scene) => scene.sceneCode === sceneCode))
        .map((sceneCode) => scenes.value.find((scene) => scene.sceneCode === sceneCode)!);

      delScenes.length && requests.push(delRelicsScenes(delScenes));

      const addScenes = nScene.filter(({ sceneCode }) => !sceneCodes.includes(sceneCode));
      addScenes.length && requests.push(addSceneHandler(addScenes));

      await Promise.all(requests);
      requests.length && (await refreshScenes());
    },
  });
};

const delRelicsScenes = (scenes: Pick<Scene, "sceneId" | "sceneCode">[]) =>
  delRelicsScenesFetch(
    relicsId.value,
    scenes.map((item) => ({ sceneCode: item.sceneCode, id: item.sceneId }))
  );

const delSceneHandler = async (scenes: Pick<Scene, "sceneId" | "sceneCode">[]) => {
  await delRelicsScenes(scenes);
  await refreshScenes();
};

const addSceneHandler = async (scenes: Pick<Scene, "sceneId" | "sceneCode">[]) =>
  await addRelicsScenesFetch(
    relicsId.value!,
    scenes.map((item) => ({ sceneCode: item.sceneCode, id: item.sceneId }))
  );
</script>

<style lang="scss" scoped>
.tree-item {
  display: flex;
  width: calc(100% - 50px);
  align-items: center;
  justify-content: space-between;

  .title {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis; //文本溢出显示省略号
    white-space: nowrap; //文本不会换行
  }
  .oper {
    flex: none;
  }
}
.disable {
  pointer-events: all;
}

.tree-layout {
  p {
    color: #303133;
    font-size: 14px;
  }
}
.right-layout {
  display: flex;
  height: 100%;
  flex-direction: column;
  .right-content {
    flex: 1;
    overflow-y: auto;
  }
}
.tree-layout .tree-scene-name {
  font-size: 10px;
  margin: 0;
  color: #999;
}
</style>
