<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"
          node-key="id"
          ref="treeRef"
          show-checkbox
          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>
              <span :class="{ disable: data.disable }" class="title" v-else>
                <el-icon>
                  <LocationInformation />
                </el-icon>
                {{ node.label }}
              </span>
              <span class="oper">
                <template v-if="router.currentRoute.value.name === 'map'">
                  <el-icon color="#409efc" v-if="data.type === 'scene'">
                    <Delete @click.stop="delRelicsScene(data.raw)" />
                  </el-icon>
                  <el-icon v-else color="#409efc">
                    <Edit @click.stop="inputPoint = data.raw" />
                  </el-icon>
                </template>
                <el-icon color="#409efc" style="margin-left: 8px">
                  <Link
                    @click.stop="
                      data.type === 'scene'
                        ? gotoScene(data.raw)
                        : emit('gotoPoint', data.raw)
                    "
                  />
                </el-icon>
              </span>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <el-button
      type="primary"
      :icon="Document"
      style="width: 100%"
      @click="exportFile(getSelectPoints())"
    >
      导出四普数据
    </el-button>

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

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

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

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",
    disable: scene.scenePos.every((pos) => !pos.pos || pos.pos.length === 0),
    raw: scene,
    children: scene.scenePos.map((pos) => ({
      label: pos.name,
      disable: !pos.pos || pos.pos.length === 0,
      id: pos.id,
      type: "point",
      raw: pos,
    })),
  }))
);

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({
    sceneCodes: sceneCodes,
    submit: async (nSceneCodes) => {
      const requests: Promise<any>[] = [];
      for (let i = 0; i < sceneCodes.length; i++) {
        if (!nSceneCodes.includes(sceneCodes[i])) {
          requests.push(delRelicsSceneFetch(relicsId.value, scenes.value[i].id));
        }
      }
      for (let i = 0; i < nSceneCodes.length; i++) {
        if (!sceneCodes.includes(nSceneCodes[i])) {
          requests.push(addSceneHandler(nSceneCodes[i]));
        }
      }

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

const addSceneHandler = async (sceneCode: string) => {
  const sceneTypes = ["SS", "KJ", "SG"];
  if (sceneTypes.every((type) => !sceneCode.startsWith(type))) {
    ElMessage.error("场景码不正确");
    throw "场景码不正确";
  } else {
    await addRelicsSceneFetch(relicsId.value!, sceneCode);
  }
};
</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;
  }
}

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