<template>
  <div class="pt-3 d-flex flex-column" style="height: 100%">
    <div class="px-3">
      <v-text-field
        v-model="queryData.name_zh"
        label="数据资源名称查找"
        placeholder="请输入数据资源名称"
        dense
        hide-details
        outlined
        clearable
        append-icon="mdi-magnify"
        @click:append="handleSearch"
        @keydown.enter.native="handleSearch"
        @click:clear="handleClear"
      ></v-text-field>
    </div>
    <div class="contentBox pa-3">
      <div v-if="!items.length" class="d-flex justify-center align-center grey--text pt-3">暂无数据</div>
      <v-expansion-panels v-model="showPanels">
        <v-expansion-panel
          v-for="(item, index) in items"
          :key="item.id"
          readonly
          @click="handleOpen(index, item)"
        >
          <v-expansion-panel-header>
            <div class="d-flex justify-space-between align-center">
              <div>
                <!-- <v-chip v-if="!item.relation">无血缘关系</v-chip> -->
                {{ item.name_zh }}
                <v-chip
                  v-if="item.count"
                  class="ml-2"
                  color="error"
                  small
                >
                  {{ item.count }}
                </v-chip>
              </div>
              <div>
                <v-btn
                  :disabled="item.metaNode.length > 0 && item.metaNode.every(e => e.used)"
                  text
                  color="primary"
                  small
                  @click.stop="handleSelectAll(item)">全选</v-btn>
              </div>
            </div>

            <template v-slot:actions>
              <v-progress-circular
                v-if="item.loading"
                indeterminate
                color="primary"
                size="24"
                width="2"
              ></v-progress-circular>
              <v-icon v-else>mdi-chevron-down</v-icon>
            </template>
          </v-expansion-panel-header>

          <v-expansion-panel-content>
            <v-divider></v-divider>
            <v-list>
              <v-list-item
                v-for="node in item.metaNode"
                :key="node.id + '-' + item.id"
              >
                <v-list-item-content>
                  <v-list-item-title>
                    <div class="d-flex justify-space-between align-center">
                      <div class="text-truncate flex-shrink-1">{{ node.name_zh }}</div>
                      <v-btn
                        v-if="node.used"
                        disabled
                        text
                        small
                      >
                        已使用
                      </v-btn>
                      <v-btn
                        v-else
                        text
                        color="primary"
                        small
                        @click="handleUse(node, item)"
                      >
                        点击使用
                      </v-btn>
                    </div>
                  </v-list-item-title>
                </v-list-item-content>
              </v-list-item>
            </v-list>
          </v-expansion-panel-content>
        </v-expansion-panel>
      </v-expansion-panels>
      <div class="d-flex justify-center align-center pa-3">
        <v-btn v-if="total > items.length" color="primary" @click="handlePage" text :loading="loading">加载更多</v-btn>
        <div class="grey--text text-subtitle-2" v-else>没有更多了</div>
      </div>
    </div>
  </div>
</template>

<script>
import { api } from '@/api/dataGovernance'
export default {
  name: 'data-list',
  components: {
  },
  props: {
    selected: {
      type: Array,
      default: () => []
    },
    isModel: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      showPanels: false,
      loading: false,
      show: false,
      queryData: {
        name_zh: null
      },
      items: [],
      orders: [],
      pageInfo: {
        size: 30,
        current: 1
      },
      total: 0,
      isRelation: undefined
    }
  },
  watch: {
    isModel () {
      this.handleClear()
    }
  },
  created () {
    this.init()
  },
  methods: {
    initUsed () {
      this.items.forEach(item => {
        item.metaNode.forEach(node => {
          node.used = this.selected.findIndex(_item => _item.id === node.id) > -1
        })
      })
    },
    async init () {
      this.loading = true
      const query = {
        ...this.pageInfo,
        ...this.queryData
      }
      if (this.isModel) {
        Object.assign(query, {
          type: 'structure'
        })
      }
      try {
        const toApi = this.isModel ? api.getModelList : api.getResourceList
        const { data } = await toApi({
          ...query
        })
        this.items.push(...data.records.map(e => {
          return {
            loading: false,
            name_zh: e.name_zh,
            id: e.id,
            type: e.type,
            metaNode: []
          }
        }))
        this.total = data.total
      } catch (error) {
        this.$snackbar.error(error)
      } finally {
        this.loading = false
      }
    },
    handleUse (node) {
      node.used = true
      this.$emit('use', node)
    },
    async handleSelectAll (item) {
      if (!item.metaNode.length) {
        await this.getMetadata(item)

        if (!item.metaNode.length) {
          this.$snackbar.error('该数据模块没有元数据')
          return
        }
      }
      const nodes = []
      item.metaNode.forEach(e => {
        if (!e.used) {
          nodes.push(e)
          e.used = true
        }
      })
      this.$emit('useAll', nodes)
    },
    handlePage () {
      this.pageInfo.current++
      this.init()
    },
    handleSearch () {
      this.items = []
      this.pageInfo.current = 1
      this.init()
    },
    handleClear () {
      this.pageInfo.current = 1
      this.items = []
      this.queryData.name_zh = null
      this.init()
    },
    async getMetadata (item) {
      // const query = { id: item.id }
      // if (this.isModel) {
      //   Object.assign(query, {
      //     type: 'model'
      //   })
      // }
      const subApi = this.isModel ? api.getModelDetails : api.getResourceDetails
      try {
        const { data } = await subApi({ id: item.id })
        if (this.isModel) {
          item.metaNode = data.data_model.resource_selected.reduce((res, v) => {
            res.push(...v.meta_ids.map(_v => {
              return {
                used: this.selected.findIndex(item => item.id === _v.id) > -1,
                ..._v,
                master_data: {
                  id: data.data_model.id,
                  name_zh: data.data_model.name_zh
                },
                originId: data.data_model.id,
                originName: data.data_model.name_zh
              }
            }))
            res = res.reverse() // 反转数组
            // res = res.sort((a, b) => a.name.localeCompare(b.name)) // 升序排序A-Z
            // res = res.sort((a, b) => b.name.localeCompare(a.name)) // 降序排序Z-A
            return res
          }, [])
          return
        }
        const res = data.parsed_data.map(_e => {
          const used = this.selected.findIndex(item => item.id === _e.id) > -1
          return {
            ..._e,
            used,
            master_data: {
              id: data.id,
              name_zh: data.name_zh
            },
            originId: data.id,
            originName: data.name_zh
          }
        })
        item.metaNode = res.reverse() // 反转数组
      } catch (error) {
        this.$snackbar.error(error)
      }
    },
    async handleOpen (index, item) {
      if (this.showPanels === index) {
        this.showPanels = null
        return
      }
      if (item.metaNode.length) {
        this.showPanels = index
        return
      }
      item.loading = true
      try {
        await this.getMetadata(item)
        this.showPanels = index
      } finally {
        item.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.contentBox {
  height: 0;
  flex: 1;
  overflow: auto;
}
</style>
