/**
 * 中间列：显示左侧选中目录的二级目录（树形，可展开子文件夹，有子文件夹前显示三角号）
 */
Vue.component('subfolder-column', {
  props: {
    type: {
      type: String,
      required: true,
      // 支持五个页面：模型 / 材质 / 门型 / 拉手 / 构件
      validator: (value) => ['model', 'material', 'door', 'handle', 'component'].includes(value)
    },
    visible: {
      type: Boolean,
      default: true
    },
    items: {
      type: Array,
      default: () => []
    },
    selectedFolderPath: {
      type: String,
      default: null
    }
  },

  data() {
    return {
      expandedSet: {}, // path -> true 表示已展开
      childrenMap: {}, // path -> 子文件夹数组
      loadingPath: null  // 正在加载子级的路径
    };
  },

  computed: {
    subfolders() {
      if (!this.items || !Array.isArray(this.items)) return [];
      return this.items.filter(
        (item) => item && item.itemType && String(item.itemType).includes('folder')
      );
    },
    title() {
      return this.$root && this.$root.translated ? this.$root.translated('subfolders') : '二级目录';
    }
  },

  watch: {
    items() {
      this.expandedSet = {};
      this.childrenMap = {};
      this.loadingPath = null;
    }
  },

  mounted() {
    window.addEventListener('subfolder-children-loaded', this.onChildrenLoaded);
  },

  beforeDestroy() {
    window.removeEventListener('subfolder-children-loaded', this.onChildrenLoaded);
  },

  template: /*html*/ `
    <div v-show="visible" class="subfolder-column">
      <div class="subfolder-column-list">
        <template v-if="subfolders.length === 0">
          <div class="subfolder-empty">{{ $root.translated('noSubfolders') || '暂无子文件夹' }}</div>
        </template>
        <template v-else>
          <template v-for="(item, index) in subfolders">
            <div
              :key="'row-' + (item.itemPath || index)"
              class="subfolder-item"
              :class="{ 'active': isActive(item) }"
              @click="$emit('browse-subfolder', item.itemPath)"
            >
              <span
                v-if="hasSubfolders(item)"
                class="subfolder-triangle"
                :class="{ 'expanded': isExpanded(item) }"
                @click.stop="toggleExpand(item)"
              >
                <i class="modus-icons">chevron_right</i>
              </span>
              <span v-else class="subfolder-triangle-placeholder"></span>
              <i class="modus-icons subfolder-item-icon">folder</i>
              <span class="subfolder-item-name" :title="item.itemName">{{ item.itemName }}</span>
            </div>
            <template v-if="isExpanded(item)">
              <div
                v-if="loadingPath === item.itemPath"
                :key="'load-' + (item.itemPath || index)"
                class="subfolder-item subfolder-item-nested subfolder-loading"
              >
                <span class="subfolder-triangle-placeholder"></span>
                <span class="subfolder-loading-text">{{ $root.translated('loading') || '加载中...' }}</span>
              </div>
              <template v-else>
                <div
                  v-for="(child, cIdx) in getChildren(item.itemPath)"
                  :key="'child-' + (child.itemPath || cIdx)"
                  class="subfolder-item subfolder-item-nested"
                  :class="{ 'active': isActive(child) }"
                  @click.stop="$emit('browse-subfolder', child.itemPath)"
                >
                  <span
                    v-if="hasSubfolders(child)"
                    class="subfolder-triangle"
                    :class="{ 'expanded': isExpanded(child) }"
                    @click.stop="toggleExpand(child)"
                  >
                    <i class="modus-icons">chevron_right</i>
                  </span>
                  <span v-else class="subfolder-triangle-placeholder"></span>
                  <i class="modus-icons subfolder-item-icon">folder</i>
                  <span class="subfolder-item-name" :title="child.itemName">{{ child.itemName }}</span>
                </div>
              </template>
            </template>
          </template>
        </template>
      </div>
    </div>
  `,

  methods: {
    hasSubfolders(item) {
      if (!item) return false;
      if (item.itemSize === '-') return true;
      const path = item.itemPath;
      if (this.childrenMap[path] && this.childrenMap[path].length > 0) return true;
      return false;
    },
    isExpanded(item) {
      return item && item.itemPath && this.expandedSet[item.itemPath];
    },
    toggleExpand(item) {
      if (!item || !item.itemPath) return;
      const path = item.itemPath;
      if (this.expandedSet[path]) {
        this.$delete(this.expandedSet, path);
      } else {
        this.$set(this.expandedSet, path, true);
        if (!this.childrenMap[path] && this.loadingPath !== path) {
          this.loadChildren(path);
        }
      }
    },
    loadChildren(path) {
      this.loadingPath = path;

      if (typeof sketchup === 'undefined') {
        this.loadingPath = null;
        return;
      }

      if (this.type === 'model' && sketchup.getModelFolderChildren) {
        sketchup.getModelFolderChildren(path);
      } else if (this.type === 'material' && sketchup.getMaterialFolderChildren) {
        sketchup.getMaterialFolderChildren(path);
      } else if (this.type === 'door' && sketchup.getDoorFolderChildren) {
        sketchup.getDoorFolderChildren(path);
      } else if (this.type === 'handle' && sketchup.getHandleFolderChildren) {
        sketchup.getHandleFolderChildren(path);
      } else if (this.type === 'component' && sketchup.getComponentFolderChildren) {
        sketchup.getComponentFolderChildren(path);
      } else {
        this.loadingPath = null;
      }
    },
    getChildren(path) {
      if (!path || !this.childrenMap[path]) return [];
      return this.childrenMap[path];
    },
    onChildrenLoaded(ev) {
      const d = ev && ev.detail;
      if (!d || d.path == null) return;
      this.$set(this.childrenMap, d.path, Array.isArray(d.children) ? d.children : []);
      this.loadingPath = null;
    },
    isActive(item) {
      if (!item || !item.itemPath || !this.selectedFolderPath) return false;
      const a = (item.itemPath || '').replace(/\\/g, '/').replace(/\/$/, '');
      const b = (this.selectedFolderPath || '').replace(/\\/g, '/').replace(/\/$/, '');
      return a === b;
    }
  }
});
