<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 filterList"
            :key="item.name + item.usePath"
            :data-prefabUrl="item.usePath + 'prefab'"
            :title="item.name + '(' + item.aliasName + ')'"
          >
            <div class="text">{{ item.aliasName }}</div>
            <i-switch
              :value="activePlugins.includes(item.usePath)"
              @on-change="(e) => change(e, item)"
            ></i-switch>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import API from '@/api'
import storage from '../utils/storage'

export default {
  name: 'SiderMenu',
  props: {
    activePlugins: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      onlinePluginList: [], // 在线预制件列表
      localPluginList: [], // 本地预制件列表
      activeItem: null,
      keyword: '',
    }
  },
  computed: {
    // 预制件全列表（本地预制件在前，在线预制件在后）
    filterList() {
      let onlineArr = []
      let localArr = []
      // 数据排序
      const dataFilter = (arr) => {
        return arr
          .filter((item) => {
            return `${item.name}${item.aliasName}`
              .toLowerCase()
              .includes(this.keyword.toLowerCase())
          })
          .sort((a, b) => (a.name > b.name ? -1 : 1))
      }
      if (!this.keyword) {
        onlineArr = [...this.onlinePluginList].sort((a, b) =>
          a.name > b.name ? -1 : 1
        )
        localArr = [...this.localPluginList].sort((a, b) =>
          a.name > b.name ? -1 : 1
        )
      } else {
        onlineArr = dataFilter([...this.onlinePluginList])
        localArr = dataFilter([...this.localPluginList])
      }
      return localArr.concat(onlineArr)
    },
  },
  methods: {
    change(e, data) {
      if (e) {
        this.activePlugins.push(data.usePath)
      } else {
        this.activePlugins.splice(this.activePlugins.indexOf(data.usePath), 1)
      }

      this.$emit('on-change', {
        isOpen: e,
        data,
        activeList: this.activePlugins,
      })
    },
    async getPluginList() {
      const res = await API.getPluginList({
        page: {
          pageNum: 0,
          pageSize: 1000,
        },
      })
      this.onlinePluginList = res.items.sort((a, b) =>
        a.uploadTime > b.uploadTime ? -1 : 1
      )
    },
    async getLocalPluginList() {
      try {
        const res = await API.getLocalPluginList()
        this.localPluginList = res.items
      } 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)
        }
      })
    },
  },
  async mounted() {
    // await this.getPluginList()
    await this.getLocalPluginList()

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

<style scoped lang="less">
.sider-menu-wrapper {
  // width: 250px;
  width: 150px;
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  z-index: 10;
  background: #1d1e21;
  .search-bar {
    padding: 10px 16px 10px 10px;
  }
  .sider-menu {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .source-list-wrap {
    overflow-y: scroll;
    height: 100%;
    padding: 10px;
  }
}
.source-item {
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
  position: relative;
  cursor: pointer;
  .text {
    width: 50%;
    background: #1d1e21;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    text-align: center;
    padding: 2px;
    float: left;
  }
  .ivu-switch {
    float: right;
  }
}
</style>
