<template>
  <div class="sider-menu-wrapper">
    <div class="sider-menu">
      <div class="search-bar">
        <Input search placeholder="输入关键词..." v-model="keyword" clearable />
      </div>
      <div class="source-list-wrap" @scroll="scroll" ref="sourceList">
        <ul class="source-list">
          <li
            class="source-item"
            v-for="item in filterPrefabList"
            :key="item.name + item.usePath + item.id"
            @mousedown="onMousedown(item, $event)"
            :data-prefabUrl="item.usePath"
            :title="
              item.name + '(' + item.aliasName + ')' + '\r\n' + item.description
            "
            :data-id="item.id"
            :data-usePath="item.usePath"
          >
            <Badge
              :text="item._flag"
              :class="`badge badge_${item._flag}`"
            ></Badge>
            <div class="img-wrap">
              <img
                :src="item.previewPath"
                :alt="item.name"
                v-if="item.previewPath"
              />
            </div>
            <div class="text">{{ item.aliasName }}</div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import API from '@/api'
import storage from '@/utils/storage'
export default {
  name: 'SiderMenu',
  props: {},
  data() {
    return {
      libPrefabList: [], // 旧资源库预制件列表
      resourcePrefabList: [], // studio 预制件列表
      localPrefabList: [], // 本地预制件列表
      activeItem: null,
      keyword: '',
    }
  },
  computed: {
    // 预制件全列表（本地预制件在前，在线预制件在后）
    filterPrefabList() {
      let prefabList = [
        ...this.localPrefabList,
        ...this.resourcePrefabList,
        ...this.libPrefabList,
      ]
      let result = []
      // 数据排序
      const dataFilter = (arr) => {
        return arr.filter((item) => {
          return `${item.name}${item.aliasName}`
            .toLowerCase()
            .includes(this.keyword.toLowerCase())
        })
      }
      if (!this.keyword) {
        result = [...prefabList]
      } else {
        result = dataFilter([...prefabList])
      }
      return result
    },
  },
  methods: {
    onMousedown(item, e) {
      this.$emit('on-drag-start', item)
      e.preventDefault()
    },
    async getLibPrefabList() {
      const res = await API.getLibPrefabList({
        page: {
          pageNum: 0,
          pageSize: 1000,
        },
      })
      this.libPrefabList = res.items
        .map((item) => {
          item._flag = '资源库'
          item.usePath = item.usePath + 'prefab/'
          return item
        })
        .sort((a, b) => {
          return a.uploadTime > b.uploadTime ? -1 : 1
        })
    },
    async getResourcePrefabList() {
      const res = await API.getResourcePrefabList({
        ci_type: 1,
        ci_query: {
          page_num: 1,
          state: 1,
          page_size: 100,
          keyword: '',
          id: 2000073, // 预制件
        },
      })

      this.resourcePrefabList = res.data
        .sort((a, b) => (a.update_time > b.update_time ? -1 : 1))
        .map((item) => {
          item.previewPath = item.imgUrl
          item.aliasName = item.name
          item._flag = '资源平台'

          return item
        })

      // 给列表增加 usePath 字段, 目前需要循环获取
      const fetchList = this.resourcePrefabList.map((item) => {
        return new Promise(async (resolve, reject) => {
          try {
            item.usePath = await API.getResourceStoreOnline(item.resourceId)
            resolve()
          } catch (e) {
            reject()
          }
        })
      })

      return Promise.allSettled(fetchList)
    },
    async getLocalPrefabList() {
      try {
        const res = await API.getLocalPrefabList()
        this.localPrefabList = res.items.map((item) => {
          item._flag = '本地'
          return item
        })
      } catch (e) {
        console.warn(`本地预制件加载失败，可能 prefab-core serve 服务未启动`)
      }
    },
    scroll(e) {
      storage.setItem('prefab-online-source-list-scrolltop', e.target.scrollTop)
    },
    initScrollTop() {
      this.$nextTick(() => {
        const scrollTop = storage.getItem('prefab-online-source-list-scrolltop')
        if (scrollTop) {
          this.$refs.sourceList.scrollTo(0, scrollTop)
        }
      })
    },
  },
  mounted() {
    // this.getLibPrefabList()
    // this.getResourcePrefabList()
    this.getLocalPrefabList()

    this.initScrollTop()
  },
}
</script>

<style scoped lang="less">
.sider-menu-wrapper {
  width: 250px;
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  z-index: 99;
  background: rgba(29, 30, 33, 0.8);
  .search-bar {
    padding: 10px 16px 10px 10px;
  }
  .sider-menu {
    height: 100%;
    display: flex;
    flex-direction: column;
    user-select: none;
  }
  .source-list-wrap {
    overflow-y: scroll;
    height: 100%;
    padding: 10px;
  }
}
.source-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}
.source-item {
  width: 68px;
  // background: hsla(0, 0%, 100%, 0.9);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  position: relative;
  cursor: pointer;
  .text {
    width: 100%;
    background: #1d1e21;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    text-align: center;
    padding: 2px;
  }
  &-local {
    padding: 2px;
    background: #ff9e00;
  }
  .img-wrap {
    width: 68px;
    height: 68px;
    border-radius: 4px;
    overflow: hidden;
  }
  img {
    width: 100%;
    height: 100%;
  }
  /deep/ .badge {
    font-size: 10px;
    position: absolute;
    right: 0;
    top: 0;
    transform: scale(0.8);
    opacity: 0.8;
  }
  /deep/ .badge_本地 {
    .ivu-badge-count-alone {
      background: #5cb85c !important;
    }
  }
  /deep/ .badge_资源平台 {
    .ivu-badge-count-alone {
      background: #ff7f29;
    }
  }
  /deep/ .badge_资源库 {
    .ivu-badge-count-alone {
      background: #9ebbf5;
    }
  }
}
</style>
