<template>
  <div class="group-settings" app-border dir-right>
    <div class="ui-title-big">场景导航
      <i class="iconfont icon-material_prompt tool-tip-for-editor" v-tooltip="'场景素材包括全景图和三维场景，您可自定义分组及场景的排列顺序。'">
      </i>
    </div>
    <button class="ui-button create-group-btn"
      @click="onRequestForAddLevel1Group"
    >
      <i class="iconfont icon-editor_add"></i>
      新增分组
    </button>

    <div class="scene-group-wrap">
      <InsertPositionTip position-debug="-1" :index="0"></InsertPositionTip>
      <div
        v-for="(item, index) of catalogTopology"
        :key=item.id
      >
        <SceneGroupInEditor
          :groupNode="item"
          :level="1"
          @addGroup="onRequestForAddGroupLevel2"
          @renameScene="onRenameScene"
          @deleteScene="onDeleteScene"
          @renameGroup="onRenameGroup"
          @deleteGroup="onDeleteGroup"
        />
        <InsertPositionTip position-debug="0" :index="index + 1"></InsertPositionTip>
      </div>
    </div>
    <popup v-if="addGroupLevel" :canClose="false">
      <div class="ui-message ui-message-confirm dark add-group-window">
        <div class="ui-message-header">
          <span>新增{{addGroupLevel === 1 ? '一' : addGroupLevel === 2 ? '二' : ''}}级分组</span>
          <span @click="addGroupLevel = 0">
            <i class="iconfont icon_close"></i>
          </span>
        </div>

        <div class="ui-message-main">
          <input
            class="name-input"
            placeholder="请输入分组名称，限15个字"
            v-model.trim="newGroupName"
            maxlength="15"
            @keydown.enter="newGroupName && onConfirmAddingGroup()"
          >
        </div>

        <div class="ui-message-footer">
          <button class="ui-button deepcancel" @click="addGroupLevel = 0">
            取消
          </button>
          <button
            class="ui-button submit"
            :class="{disable: !newGroupName}"
            @click="onConfirmAddingGroup"
          >
            确定
          </button>
        </div>
      </div>
    </popup>
  </div>
</template>

<script>
import SceneGroupInEditor from "@/components/sceneGroupInEditor.vue";
import { mapGetters } from "vuex";
import { deepClone } from "@/utils/other.js";
import Popup from "@/components/shared/popup/index.vue";
import InsertPositionTip from "@/components/insertPositionTipInEditor.vue";

export default {
  components: {
    SceneGroupInEditor,
    Popup,
    InsertPositionTip,
  },
  computed: {
    ...mapGetters({
      info: "info",
      catalogTopology: 'catalogTopology',
    }),
  },
  data() {
    return {
      addGroupLevel: 0, // 0: 没有在新增分组；1：在新增一级分组；2：在新增二级分组
      newGroupName: '',
      parentGroupId: '',
    };
  },
  watch: {
  },
  methods: {
    onRequestForAddLevel1Group() {
      this.newGroupName = ''
      this.addGroupLevel = 1
    },
    onConfirmAddingGroup() { 
      if (this.addGroupLevel === 1) {
        let newGroupLevel2Id = 'c_' + this.$randomWord(true, 8, 8)
        const newGroupLevel1 = {
          id: 'r_' + this.$randomWord(true, 8, 8),
          name: this.newGroupName,
          children: [newGroupLevel2Id],
        }
        this.info.catalogRoot.push(newGroupLevel1)
        this.info.catalogs.push({
          id: newGroupLevel2Id,
          name: '默认二级分组',
        })
      } else if (this.addGroupLevel === 2) {
        let id = 'c_' + this.$randomWord(true, 8, 8)
        let parent = this.info.catalogRoot.find((item) => {
          return item.id === this.parentGroupId
        })
        parent.children.push(id);
        const newGroupLevel2 = {
          id,
          name: this.newGroupName,
        }
        this.info.catalogs.push(newGroupLevel2);
      }
      this.$msg.success("操作成功")
      this.newGroupName = ''
      this.parentGroupId = ''
      this.addGroupLevel = 0
    },
    onRequestForAddGroupLevel2(parentGroupId) {
      this.addGroupLevel = 2
      this.parentGroupId = parentGroupId
    },
    onRenameScene(sceneId, newName) {
      const renameTarget = this.info.scenes.find((item) => {
        return item.id === sceneId
      })
      renameTarget.sceneTitle = newName
    },
    onDeleteScene(sceneId) {
      const deleteTargetIdx = this.info.scenes.findIndex((item) => {
        return item.id === sceneId
      })
      this.info.scenes.splice(deleteTargetIdx, 1)
      this.delFirstScene()
      this.$msg.success("删除成功")
    },
    onRenameGroup(groupId, level, newName) {
      if (level === 1) {
        const target = this.info.catalogRoot.find((item) => {
          return item.id === groupId
        })
        target.name = newName
        this.$msg.success('操作成功')
      } else if (level === 2) {
        const target = this.info.catalogs.find((item) => {
          return item.id === groupId
        })
        target.name = newName
        this.$msg.success('操作成功')
      } else {
        console.error('invalid level!');
      }
    },
    onDeleteGroup(groupId, groupLevel) {
      const deleteGroupLevel2 = (groupId) => {
        // 要删除的二级分组在catalogRoot[x].children中的索引
        let targetGroupIdxLevel2 = null
        // 要删除的二级分组所属的一级分组在catalogRoot中的索引
        let belongGroupIdxLevel1 = null
        // 确定上边两个变量的取值
        for (const [groupIdxLevel1, groupLevel1] of this.info.catalogRoot.entries()) {
          for (const [groupIdxLevel2, childId] of groupLevel1.children.entries()) {
            if (childId === groupId) {
              targetGroupIdxLevel2 = groupIdxLevel2
              break
            }
          }
          if (targetGroupIdxLevel2 !== null) {
            belongGroupIdxLevel1 = groupIdxLevel1
            break
          }
        }
        if (targetGroupIdxLevel2 === null || belongGroupIdxLevel1 === null) {
          console.log(targetGroupIdxLevel2, belongGroupIdxLevel1);
          throw('一级分组列表中没有找到要删除的二级分组！')
        }

        // 删除catalogRoot[x].children中那个二级分组条目
        this.info.catalogRoot[belongGroupIdxLevel1].children.splice(targetGroupIdxLevel2, 1)
        
        // 删除catalogs中那个二级分组条目
        const targetIdx = this.info.catalogs.findIndex((item) => {
          return item.id === groupId
        })
        if (targetIdx < 0) {
          throw('二级分组列表中没有找到要删除的二级分组！')
        }
        this.info.catalogs.splice(targetIdx, 1)

        // 删除场景列表中属于要删除的二级分组的那些场景
        this.info.scenes = this.info.scenes.filter((item) => {
          return item.category !== groupId
        })

        // 如果所属一级分组中没有任何二级分组了，则新增一个默认二级分组
        if (this.info.catalogRoot[belongGroupIdxLevel1].children.length === 0) {
          let newGroupLevel2Id = 'c_' + this.$randomWord(true, 8, 8)
          this.info.catalogRoot[belongGroupIdxLevel1].children.push(newGroupLevel2Id)
          this.info.catalogs.push({
            id: newGroupLevel2Id,
            name: '默认二级分组',
          })
        }

        return
      }

      const backup = deepClone(this.info)
      try {
        if (groupLevel === 1) {
          if (this.info.catalogRoot.length === 1) {
            return this.$alert({
              content: "请至少保留一个分组",
              ok: () => {
                return
              },
            })
          }

          const targetGroupIdx = this.info.catalogRoot.findIndex((groupLevel1) => {
            return groupLevel1.id === groupId
          })
          if (targetGroupIdx < 0) {
            throw('没有找到要删除的一级分组！')
          }
          // 删除该一级分组下的所有二级分组及属于这些二级分组的场景
          for (const childId of this.info.catalogRoot[targetGroupIdx].children) {
            deleteGroupLevel2(childId)
          }
          // 删除该一级分组
          this.info.catalogRoot.splice(targetGroupIdx, 1)
        } else if (groupLevel === 2) {
          deleteGroupLevel2(groupId)
        } else {
          throw('group level invalid!');
        }
        // 酌情清空初始场景设置
        this.delFirstScene()
        this.$msg.success("删除成功")
      } catch(e) {
        console.error(e);
        this.$msg.error('删除失败')
        this.$store.commit("SetInfo", backup)
      }
    },
    delFirstScene(){
        if (this.info.firstScene) {
          let firIdx = this.info.scenes.find(item=>{
            return item.sceneCode == this.info.firstScene.sceneCode
          });
          !firIdx&&(this.info.firstScene='')
        }
    },
  },
  mounted() {
    this.$bus.on('getActive',data=>{
      if (data.type == 1) {
        this.taboneActive = data.willActive
      } else{
        this.tabtowActive = data.willActive
      }
    })
  },
};
</script>

<style lang="less" scoped>
.group-settings {
  display: flex;
  flex-direction: column;
  background: #252526;
  position: relative;
  > .ui-title-big {
    margin-top: 24px;
    margin-left: 20px;
    margin-right: 20px;
    margin-bottom: 0;
    flex: 0 0 auto;
    > .tool-tip-for-editor {
      font-size: 12px;
      cursor: default;
      position: relative;
      top: -1px;
      font-weight: normal;
    }
  }
  > .create-group-btn {
    margin-top: 24px;
    margin-left: 20px;
    margin-right: 20px;
    flex: 0 0 auto;
    > i {
      font-size: 14px;
    }
  }
  > .scene-group-wrap {
    flex: 1 1 auto;
    height: 1px;
    overflow: auto;
    margin-top: 24px;
    padding-left: 20px;
    padding-right: 20px;
  }

  .ui-message {
    > .ui-message-main {
      > .name-input {
        height: 36px;
        background: #252526;
        border-radius: 2px;
        border: 1px solid #404040;
        color: #fff;
        font-size: 14px;
        padding: 0 16px;
        letter-spacing: 1px;
        width: 100%;
        &:focus {
          border-color: #0076F6;
        }
      }
    }
  }
}
</style>
