<template>
  <div class="scene-group">
    <div
      class="top-bar"
      :class="isConfirmingDeletion ? '' : 'show-icons-on-hover'"
      @click="onClickTopBar"
      @dragstart="onDragStart"
      @dragenter.self="onDragEnter"
      @dragend="onDragEnd"
      @dragleave.self="onDragLeave"
      :draggable="isRenaming ? false : true"
      :style="{
        paddingLeft: topBarPaddingLeft,
      }"
    >
      <div class="drag-image" ref="drag-image">
        <i class="iconfont icon-editor_folder_off"></i>
      </div>
      <i class="iconfont icon-edit_input_arrow icon-expand" :class="isExpanded ? '' : 'collapsed'"></i>
      <i v-show="isExpanded" class="iconfont icon-editor_folder_on folder_expanded"></i>
      <i v-show="!isExpanded" class="iconfont icon-editor_folder_off folder_collapsed"></i>
      <template v-if="!isRenaming">
        <span class="group-name" v-title="transTitle(groupNode.name)">
          <!-- {{
            $i18n.t(`zh_key.${groupNode.name}`).indexOf("zh_key") > -1
              ? groupNode.name
              : $i18n.t(`zh_key.${groupNode.name}`)
          }} -->
          {{ transTitle(groupNode.name) }}
          <!-- {{ groupLv1name(groupNode.name) }} -->
        </span>
        <i v-show="level === 1" class="iconfont icon-editor_list_add icon-add" v-tooltip="$i18n.t('navigation.add_two_group')" @click.stop="onRequestForAddGroup"> </i>
        <!-- <i
          class="iconfont icon-editor_list_image icon-image"
          v-tooltip="$i18n.t('navigation.add_pano_or_scene')"
          @click.stop="onRequestForAddScene"
          v-show="
            level === 1 ||
            (level === 0 &&
              (groupNode.children.length === 0 ||
                (groupNode.children.length === 1 && (groupNode.children[0].name === '默认二级分组' || groupNode.children[0].name === $i18n.t('navigation.default_group_two')))))
          "
        >
        </i> -->
        <i
          class="iconfont icon-editor_list_image icon-image"
          v-tooltip="$i18n.t('navigation.add_pano_or_scene')"
          @click.stop="onRequestForAddScene(groupNode)"
          v-show="groupNode.type == 'group' && groupNode.children[0].type != 'group'"
        >
        </i>
        <i class="iconfont icon-editor_list_edit icon-edit" v-tooltip="$i18n.t('navigation.rename')" @click.stop="onClickForRename"> </i>
        <i class="iconfont icon-editor_list_delete icon-delete" v-tooltip="$i18n.t('navigation.delete')" @click.stop="onRequestForDelete"> </i>
        <div class="deletion-confirm-wrap">
          <div class="deletion-confirm" :class="isConfirmingDeletion ? 'show' : 'hide'" v-clickoutside="onRequestForCancelDelete" @click.stop="onConfirmDelete">
            {{ $i18n.t("navigation.delete") }}
          </div>
        </div>
      </template>
      <input
        v-if="isRenaming"
        class="group-title-input"
        v-model.trim="newName"
        ref="input-for-rename"
        maxlength="50"
        :placeholder="$i18n.t('navigation.enter_name')"
        @blur="onInputNewNameComplete"
        @keydown.enter="onInputEnter"
        @click.stop
      />
    </div>

    <div class="group-content" v-if="isExpanded">
      <template v-if="!(groupNode.children.length === 1 && (groupNode.children[0].name === '默认二级分组' || groupNode.children[0].name === $i18n.t('navigation.default_group_two')))">
        <InsertPositionTip position-debug="1" :indentLevel="level + 1" :topologyLevel="level + 1" :parentNode="groupNode" :index="0"></InsertPositionTip>
        <div v-for="(item, index) of groupNode.children" :key="item.id">
          <component
            :is="'SceneGroup'"
            ref="scene-group"
            v-if="!item.type"
            :groupNode="item"
            :level="level + 1"
            @renameScene="onRenameScene"
            @deleteScene="onDeleteScene"
            @renameGroup="onInnerGroupRename"
            @deleteGroup="onInnerGroupConfirmDelete"
          />
          <SceneInGroup
            v-else
            :style="{
              paddingLeft: sceneItemPaddingLeft,
            }"
            :sceneInfo="item"
            @rename="onRenameScene"
            @delete="onDeleteScene"
          />
          
          <InsertPositionTip position-debug="2" :indentLevel="level + 1" :topologyLevel="level + 1" :parentNode="groupNode" :index="index + 1"></InsertPositionTip>
        </div>
      </template>
      <template v-else>
        <!-- 自动生成的默认二级分组不显示，里边的内容显示成直属于一级分组的效果。 -->
        <InsertPositionTip position-debug="3" :indentLevel="level + 1" :topologyLevel="level + 2" :parentNode="groupNode.children[0]" :index="0"></InsertPositionTip>
        <div v-for="(item, index) of groupNode.children[0].children" :key="item.id">
          <SceneInGroup
            :style="{
              paddingLeft: sceneItemPaddingLeft,
            }"
            :sceneInfo="item"
            @rename="onRenameScene"
            @delete="onDeleteScene"
          />
          <InsertPositionTip position-debug="4" :indentLevel="level + 1" :topologyLevel="level + 2" :parentNode="groupNode.children[0]" :index="index + 1"></InsertPositionTip>
        </div>
      </template>
    </div>

    <div class="dialog" style="z-index: 2000" v-if="isShowSelectionWindow">
      <MaterialSelector
        :title="$i18n.t('gather.select_material')"
        @cancel="isShowSelectionWindow = false"
        @submit="onSubmitFromMaterialSelector"
        :selectableType="['pano', '3D']"
        :initialMaterialType="'pano'"
        :isMultiSelection="true"
      />
    </div>
  </div>
</template>

<script>
import SceneInGroup from "@/components/sceneInGroupInEditor.vue";
import MaterialSelector from "@/components/materialSelector.vue";
import InsertPositionTip from "@/components/insertPositionTipInEditor.vue";
import { mapGetters, mapMutations } from "vuex";
import { isUpgradeAdapter } from "@/utils/fixVersion";

export default {
  name: "SceneGroup",
  components: {
    SceneInGroup,
    MaterialSelector,
    InsertPositionTip,
  },
  props: {
    groupNode: {
      type: Object,
      required: true,
    },
    level: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      isExpanded: false,
      isRenaming: false,
      newName: "",
      isConfirmingDeletion: false,
      isShowSelectionWindow: false,
      dragEnterTimerId: null,
      insertTag: null,
    };
  },
  computed: {
    transTitle() {
      return (name) => {
        switch (name) {
          case "默认一级分组":
            return this.$i18n.t("navigation.default_group_one");
          case "默认二级分组":
            return this.$i18n.t("navigation.default_group_two");
          case "一级分组":
            return this.$i18n.t("navigation.group_one");
          case "二级分组":
            return this.$i18n.t("navigation.group_two");
          default:
            return name;
        }
      };
    },
    groupLv1name() {
      return (name) => {
        return name && name.length ? name : this.$i18n.t("navigation.group_one");
      };
    },
    ...mapGetters({
      // info: "info",
      info: "base/baseInfo",
      sceneList: "base/sceneList",
      dragInfo: "editorNavDragInfo",
    }),
    topBarPaddingLeft() {
      return 12 + (this.level - 1) * 12 + "px";
    },
    sceneItemPaddingLeft() {
      return 18 + this.level * 12 + "px";
    },
  },
  methods: {
    ...mapMutations({
      recordDragType: "setEditorNavDragType",
      recordDragNode: "setEditorNavDragNode",
      clearDragInfo: "clearEditorNavDragInfo",
    }),
    onClickTopBar() {
      console.error(1231232)
      if (this.isConfirmingDeletion) {
        return;
      }
      this.isExpanded = !this.isExpanded;
    },

    onRenameScene(...params) {
      this.$emit("renameScene", ...params);
    },
    onDeleteScene(...params) {
      this.$emit("deleteScene", ...params);
    },

    onRequestForAddGroup() {
      this.$emit("addGroup", this.groupNode.id);
    },
    onRequestForAddScene(item) {
      this.insertTag = item;

      this.isShowSelectionWindow = true;
    },
    onClickForRename() {
      this.isRenaming = true;
      console.log(this.groupNode.name);

      if (this.groupNode.name == "默认二级分组") {
        this.newName = this.$i18n.t("navigation.default_group_two");
      } else if (this.groupNode.name == "一级分组") {
        this.newName = this.$i18n.t("navigation.group_one");
      } else {
        this.newName = this.groupNode.name;
      }

      this.$nextTick(() => {
        // this.$refs['input-for-rename'].focus()
        this.$refs["input-for-rename"].select();
        this.$refs["input-for-rename"].scrollIntoView({
          behavior: "smooth",
        });
      });
    },
    onInputNewNameComplete() {
      this.isRenaming = false;
      console.log(this.groupNode.name);
      if (!this.newName.trim()) {
        return;
      }
      if (this.newName !== this.groupNode.name) {
        this.$emit("renameGroup", this.groupNode.id, this.level, this.newName);
      }
      this.newName = "";
    },
    onInputEnter() {
      this.isRenaming = false; // 会导致input blur，进而触发onInputNewNameComplete
    },
    onInnerGroupRename(...params) {
      this.$emit("renameGroup", ...params);
    },

    onRequestForDelete() {
      this.isConfirmingDeletion = true;
    },
    onRequestForCancelDelete() {
      if (!this.isConfirmingDeletion) {
        return;
      }
      // 先保持isConfirmingDeletion不变，因为onClickTopBar可能要用到
      setTimeout(() => {
        this.isConfirmingDeletion = false;
      }, 0);
    },
    onConfirmDelete() {
      this.$emit("deleteGroup", this.groupNode.id, this.level);
      this.isConfirmingDeletion = false;
    },
    onInnerGroupConfirmDelete(...params) {
      this.$emit("deleteGroup", ...params);
    },
    onSubmitFromMaterialSelector(selected) {
      console.error(this.insertTag.level);
      let changeListLength = this.insertTag.children.length || 0;
      let newScenes = [];
      for (const item of selected) {
        if (item.materialType === "pano") {
          newScenes.push({
            fodderId: item.id,
            icon: item.icon,
            sceneCode: item.sceneCode,
            name: item.name,
            // category: this.level === 1 ? this.groupNode.children[0].id : this.groupNode.id,
            type: "pano",
            sort: changeListLength,
            parentId: null,
            level: this.insertTag.level + 1,
            // id: "s_" + this.$randomWord(true, 8, 8),
          });
        } else if (item.materialType === "3D") {
          console.log("item.num", item.num);
          newScenes.push({
            icon: item.thumb,
            sceneCode: item.num,
            name: item.sceneName,
            sort: changeListLength,
            // category: this.level === 1 ? this.groupNode.children[0].id : this.groupNode.id,
            type: "4dkk",
            level: this.insertTag.level + 1,
            version: isUpgradeAdapter(item.isUpgrade), // 'V3' OR 'V4'. 全景看看v1.3新增
            // id: "s_" + this.$randomWord(true, 8, 8),
            // fodderId: item.id,
          });
        }
        changeListLength++;
      }
      console.error(newScenes);
      console.error(this.sceneList);

      let allSuccess = true;
      newScenes.forEach((item, i) => {
        // let temp = this.info.scenes.find((eachScene) => {
        let temp = this.sceneList.find((eachScene) => {
          return eachScene.sceneCode === item.sceneCode;
        });
        if (temp) {
          setTimeout(() => {
            this.$msg.message(
              `${item.type == "4dkk" ? this.$i18n.t("navigation.scene_name") : this.$i18n.t("navigation.pano")}${this.$i18n.t("navigation.already_exists", {
                msg: item.sceneTitle,
              })}`
            );
          }, i * 100);
          allSuccess = false;
          return;
        }
        // this.info.scenes.push(item);
        this.insertTag.children.push(item);
      });

      this.isShowSelectionWindow = false;
      if (allSuccess) {
        this.$msg.success(this.$i18n.t("gather.success"));
      }
    },
    onDragStart(e) {
      if (this.isRenaming) {
        return;
      }
      this.recordDragType(`topologyGroupLevel${this.level}`);
      this.recordDragNode(this.groupNode);
      e.dataTransfer.setDragImage(this.$refs["drag-image"], -10, -18);
    },
    onDragEnter(e) {
      if (e.target.contains(e.relatedTarget) || (this.level === 2 && this.dragInfo.type.includes("Group"))) {
        return;
      }
      this.dragEnterTimerId = setTimeout(() => {
        if (!this.isExpanded) {
          this.isExpanded = true;
        }
      }, 700);
    },
    onDragEnd() {
      this.clearDragInfo();
      clearTimeout(this.dragEnterTimerId);
    },
    onDragLeave(e) {
      if (e.target.contains(e.relatedTarget)) {
        return;
      }
      clearTimeout(this.dragEnterTimerId);
    },
  },
  mounted() {},
  destroyed() {},
};
</script>

<style lang="less" scoped>
.scene-group {
  .top-bar {
    position: relative;
    color: rgba(255, 255, 255, 0.6);
    height: 40px;
    border-radius: 4px;
    display: flex;
    align-items: center;
    margin-left: -12px;
    margin-right: -10px;
    padding-right: 10px;
    &:hover {
      background: #313131;
      > .group-name {
        width: 120px;
      }
    }
    &.show-icons-on-hover:hover {
      > .icon-add,
      .icon-image,
      .icon-edit,
      .icon-delete {
        display: block;
      }
    }
    > .drag-image {
      position: absolute;
      width: 40px;
      height: 40px;
      background: #313131;
      box-shadow: 0px 0px 4px 0px rgba(0, 0, 0, 0.5);
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
      z-index: -1;
      i {
        font-size: 16px;
      }
    }
    > .icon-expand {
      display: inline-block;
      font-size: 12px;
      transform: scale(0.7);
      &.collapsed {
        display: inline-block;
        transform: scale(0.7) rotate(-90deg);
      }
    }
    > .folder_expanded {
      font-size: 16px;
      margin-left: 7px;
    }
    > .folder_collapsed {
      font-size: 16px;
      margin-left: 7px;
    }
    > .group-name {
      margin-left: 6px;
      display: inline-block;
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
      flex: 1 1 auto;
    }
    > .icon-add {
      margin-left: 12px;
      display: none;
      cursor: pointer;
      &:hover {
        color: #0076f6;
      }
    }
    > .icon-image {
      margin-left: 12px;
      display: none;
      cursor: pointer;
      &:hover {
        color: #0076f6;
      }
    }
    > .icon-edit {
      margin-left: 12px;
      display: none;
      cursor: pointer;
      &:hover {
        color: #0076f6;
      }
    }
    > .icon-delete {
      margin-left: 12px;
      display: none;
      cursor: pointer;
      &:hover {
        color: #fa5555;
      }
    }
    > .deletion-confirm-wrap {
      position: absolute;
      top: 0;
      bottom: 0;
      right: 0;
      width: 44px;
      overflow: hidden;
      pointer-events: none;
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      > .deletion-confirm {
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
        background: #fa5555;
        transition: right 0.3s;
        cursor: pointer;
        text-align: center;
        font-size: 12px;
        color: #fff;
        pointer-events: auto;
        &::after {
          content: "";
          height: 100%;
          vertical-align: middle;
          display: inline-block;
        }
        &.show {
          right: 0;
        }
        &.hide {
          right: -44px;
        }
      }
    }
    > .group-title-input {
      margin-left: 6px;
      flex: 1 1 auto;
      width: 1px;
      height: 30px;
      background: #1a1b1d;
      border-radius: 2px;
      border: 1px solid #404040;
      color: #fff;
      font-size: 14px;
      padding: 0 10px 0 16px;
      &:focus {
        border-color: #0076f6;
      }
    }
  }
  .group-content {
  }
}
</style>
