<template>
  <div class="th-provider-panel full">
    <div class="top">
      <div class="top-left">
        <Input search clearable class="search inline" placeholder="请输入关键词筛选" v-model="keyword"/>
        <div class="tools inline">
          <IconButton name="md-refresh" :size="22" title="刷新" @on-click="refreshSource"/>
          <IconButton name="md-return-left" :size="22" title="返回" :disabled="!paths.length" @on-click="back2Pre"/>
          <IconButton name="md-add" :size="22" title="添加数据" @on-click="openDatabaseManager" v-if="sourceScope==='private'"/>
          <IconButton name="md-folder" :size="22" title="创建目录" @on-click="createCatalog" v-if="sourceScope==='private'"/>
        </div>
        <div class="tab-btns inline">
          <IconButton name="ios-apps" title="图标模式" :selected="currentMode==='icon'" :size="22" @on-click="currentMode='icon'"/>
          <IconButton name="md-list" title="列表模式" :selected="currentMode==='list'" :size="22" @on-click="currentMode='list'" />
        </div>
      </div>
      <ThRadioGroup
        v-model="sourceScope"
        :btns="[
          { name: '我的数据', value: 'private' },
          { name: '公共数据', value: 'public' },
        ]"
        @on-change="sourceScopeChange"
        style="width: 150px;float: right;" 
      />
    </div>
    <SourceList class="list inline" :list="displayList" :isprivate="sourceScope==='private'" :selectedId="selectedItem&&selectedItem.catalogId" :mode="currentMode" :paths="paths" @on-select="sourceSelectChange" @on-back="back2Pre" @on-delete="deleteSource" @on-update="updateSource" :style="{width:activeProperties?'calc(100% - 186px)':'100%',borderRight:activeProperties?'1px solid #e8eaec':'none'}"/>
    <!-- 添加数据对话框 -->
    <DataImportModal :paths="paths" @on-add-source="addSource" ref="databaseManagementModal"/>
    <div class="properties inline"  :style="{width:activeProperties?'186px':'0px'}" v-if="activeProperties">
      <ColumnProperties :data="activeProperties" />
    </div>
  </div>
</template>

<script>
import _ from 'lodash'
import util from '../../libs/util'
import {getTableFields, getCatalogList, catalogCreate} from '../../libs/request'
import config from '../../constants/config'
import IconButton from '../icon-button'
import ColumnProperties from './ColumnProperties.vue'
import ThRadioGroup from '../th-radio-group'
import SourceList from '../source-list'
import DataImportModal from '../data-import-modal'
export default {
  props:["editByUrl"],
  components: {IconButton, ColumnProperties, ThRadioGroup, SourceList, DataImportModal},
  methods: {
    sourceSelectChange(item) { // 点击数据或目录
      let {catalogId, name, type} = item
      if (type === 'catalog') {
        this.paths.push({
          catalogId,
          name,
          type
        })
        this.refreshSource()
        this.selectedItem = null
        this.activeProperties=null
      } else {
        this.selectedItem = item
      }
      this.$emit('on-select', this.selectedItem)
    },
    getDisplayList() { // 获取当前路径下的数据源列表
      let list = []
      let parentId = this.getParentId()
      if (this.paths.length) {
        list = this.sourceList.filter(ls => ls.parentId === parentId)
      } else {
        let loginUser = config.USER
        list = this.sourceList.filter(ls => {
          return this.sourceScope==='private' ? (ls.owner === loginUser && !ls.parentId) : (ls.owner === this.publicUser && !ls.parentId)
        })
      }
      return list
    },
    sourceScopeChange() { // 修改数据类型
      this.paths = []
      this.activeProperties=null
      this.refreshSource()
    },
    refreshSource() {
      this.selectedItem = null
      this.activeProperties=null
      let parentId = this.getParentId()
      if (this.sourceScope==='private') {
        let ownerId = config.USER
        this.getSourceList(ownerId, parentId)
      } else if (this.sourceScope==='public') {
        this.getSourceList(this.publicUser, parentId)
      }
    },
    getSourceList(ownerId, parentId) {
      getCatalogList(ownerId, parentId).then(res => {
        let types = ['catalog', 'table', 'point', 'linestring', 'polygon', 'multipoint', 'multilinestring', 'multipolygon', 'geometry']
        let list = res.data.filter(r => types.indexOf(r.type) !== -1)
        this.sourceList = list
      })
    },
    addSource(source) {
      this.sourceList.unshift(source)
    },
    back2Pre() { // 返回上一步
      if (!this.paths.length) {
        return
      }
      let paths = _.cloneDeep(this.paths)
      paths.pop()
      this.paths = paths
      this.refreshSource()
      this.selectedItem=null
      this.activeProperties=null
      this.$emit('on-select', this.selectedItem)
    },
    isNameExist(type, name) { // 检查名称是否重复
      return !!this.displayList.find(ls => ls.type === type && ls.name === name)
    },
    createCatalog() { // 创建文件夹
      let ownerId = config.USER
      let name = '未命名'
      let index = 2
      do {
        if (!this.isNameExist('calalog', name)) {
          break;
        }
        name = '未命名' + index
      } while (index++)
      let parentId = this.getParentId()
      catalogCreate(ownerId, util.generateId(), {
        name: name,
        parentId,
        type: 'catalog'
      }).then(res => {
        this.sourceList.push(res.data)
      })
    },
    openDatabaseManager() { // 打开数据库管理
      this.$refs.databaseManagementModal.show()
    },
    getParentId() {
      let parentId = null
      if (this.paths.length) {
        parentId = this.paths[this.paths.length - 1].catalogId
      }
      return parentId
    },
    async showProperties(node) {
      let {owner, resId} = node
      this.node=node
      let  response = await getTableFields(owner, resId)
      this.activeProperties = response.data
    },
    updateSource({catalogId, data}) {
      let index = this.sourceList.findIndex(l => l.catalogId === catalogId)
      if (index !== -1) {
        this.sourceList.splice(index, 1, data)
      }
    },
    deleteSource(catalogId) {
      let index = this.sourceList.findIndex(l => l.catalogId === catalogId)
      if (index !== -1) {
        this.sourceList.splice(index, 1)
      }
    }
  },
  mounted() {
    this.refreshSource()
  },
  data() {
    return {
      publicUser: config.PUBLIC_COUNT,
      dlg: false,
      selectedItem: null,
      keyword: '',
      currentMode: 'icon',
      selectedMenu: 'source',
      sourceScope: 'private', // 数据类型，私有还是公共
      paths: [],
      menus: [{
        type: 'source',
        icon: 'md-stats',
        name: '数据'
      },{
        type: 'model',
        icon: 'md-cube',
        name: '模型'
      },{
        type: 'service',
        icon: 'md-link',
        name: '服务'
      }],
      activeProperties:null,
      node:null,
      sourceList: []
    }
  },
  computed: {
    displayList() {
      let list = []
      let source=_.cloneDeep(this.getDisplayList())
      if (this.keyword !== '') {
        list = source.filter((s) => s.name.indexOf(this.keyword) > -1)
      } else {
        list = source
      }
      return list
    },
  },
  watch:{
    selectedItem(newV){
      if(newV){
        this.showProperties(newV)
      }
    },
    editByUrl(newV){
      if(newV){
        this.selectedItem=null
        this.activeProperties=null
      }
    },
    keyword(){
      this.selectedItem=null
      this.activeProperties=null
    }
  }
}
</script>