<template>

  <div :style="{'overflow-y':'auto','height':htSize+'px'}">

    <el-form label-position="top" class="panel" style="text-align:left;">
      <el-form-item v-show="false" :label="$t('common.dataSource')+':'">
        <el-select v-model="selectedBase" size="mini" filterable :placeholder="$t('dataSource.sourcePlaceholder')" style="width:200px;" clearable @change="handleBaseChange">
          <el-option v-for="item in baseList" :key="item.source_id" :label="item.base_alias || item.database" :value="item.source_id" />
        </el-select>
      </el-form-item>

      <!-- 表下拉框 -->
      <!-- label看到的 key=id -->
      <el-form-item label="数据类型：">
        <el-radio-group v-model="selectedTable" @change="handleDataSrcChange">
          <el-radio-button label="trainnumber">车次</el-radio-button>
          <el-radio-button label="barroport">栏舍</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item>
        <el-select v-model="selectedTable" size="mini" filterable :placeholder="$t('dataSource.tablePlaceholder')" style="width:200px;" clearable @change="handleDataSrcChange">
          <el-option v-for="item in tableList" :key="item.table" :label="item.table_alias || item.tablename" :value="item.table" />
        </el-select>
      </el-form-item> -->

      <el-form-item v-show="false" :label="$t('dataSource.table')+':'">
        <span style="font-size: 12px;margin-right: 5px;">{{ selectedTableName }}</span>
        <el-button type="text" size="mini" @click="editDataSrc">
          {{ $t('common.edit') }}
        </el-button>
      </el-form-item>

      <!-- 字段 -->
      <!-- <el-form-item :label="$t('dataSource.fields')+':'">
        <draggable v-model="tableSchema" v-loading="schemaLoading" :group="{name: 'col',pull: 'clone', put: false}" :move="handleMove">
          <div v-for="col in tableSchema" :key="col.Column" class="drag-list-item">
            <i class="el-icon-rank" style="font-size: 12px;color:#409EFF;" /> {{ col.Comment }}
          </div>
        </draggable>
      </el-form-item> -->
      <el-form-item :label="$t('dataSource.fields')+':'">
        <draggable v-if="isEdit == 'edit'" v-model="tableSchema" v-loading="schemaLoading" :group="{name: 'col',pull: 'clone', put: false}" :move="handleMove">
          <div v-for="col in tableSchema" :key="col.Column" class="drag-list-item">
            <i class="el-icon-rank" style="font-size: 12px;color:#409EFF;" /> {{ col.Comment }}
          </div>
        </draggable>

        <div v-if="isEdit == 'view'" v-for="col in tableSchema" :key="col.Column" class="drag-list-item">
          <i class="el-icon-rank" style="font-size: 12px;color:#409EFF;" /> {{ col.Comment }}
        </div>

      </el-form-item>
    </el-form>

  </div>

</template>
<script>
import { sourceList, linkedTablesByBase } from '@/api/source'
import { GetDataByName } from '@/api/common'
import draggable from 'vuedraggable'
import exeSql from '@/api/exeSql'
import store from '../store'

export default {
  components: { draggable },
  props: {
    resultLoading: {
      default: false
    },
    dataSrc: {
      requred: true
    },
    isEdit: "",

  },
  watch: {
    isEdit: function (newValue) {
      console.log('isEdit:', newValue);  //可以看到数据已经拿到
      this.isEdit = newValue
    }
  },
  data() {
    return {
      radio1: '上海',
      schemaLoading: false,
      baseList: [],

      tableList: [],
      selectedTable: undefined,
      tableSchema: undefined,
      dataSrcVisible: true,
      existWarning: null,
      selectedBase: undefined,

    }
  },
  computed: {
    allSelected() {
      return store.state.dimensions.concat(store.state.caculCols).concat(store.state.caculCols2)
    },
    selectedBaseName() {
      const selectedBase = this.baseList.find(item => item.source_id === this.selectedBase)
      if (!selectedBase) return ''
      return selectedBase.base_alias || selectedBase.database
    },
    selectedTableName() {
      const selectedTable = this.tableList.find(item => item.table === this.selectedTable)
      if (!selectedTable) return ''
      return selectedTable.table_alias || selectedTable.table
    }
  },
  created() {
    console.log('this.dataSrc', this.dataSrc)


    console.log('height', document.documentElement.clientHeight)
    var height = document.documentElement.clientHeight - 260


    this.htSize = height
    // this.getBaseList() 

    // this.get_table_list()
  },
  methods: {
    // async getBaseList() {
    //   const { data } = await sourceList()
    //   this.baseList = data
    // },
    get_table_list() {
      var send_data = {
        name: 'getTABLESV2',
        page: 1,
        offset: 1
      }

      GetDataByName(send_data).then(response => {
        console.log('tableList数据', response.data.list)
        if (response.data.list !== null) {
          this.tableList = response.data.list
        } else {
          this.tableList = []
        }
      })
    },

    initWithDataSrc(dataSrc) {
      console.log('dataSrc:', dataSrc)
      if (dataSrc) {
        this.selectedTable = dataSrc.table
        this.selectedBase = dataSrc.source_id
        // this.fetchTables()
        this.fetchSchema()
      } else {

        this.selectedBase = ''
        // this.tableSchema = []
        // this.dataSrcVisible = true


        this.selectedTable = 'trainnumber'
        this.fetchSchema()

        store.setAllColsAction([])
        this.$emit('change', {
          table: this.selectedTable,
          source_id: this.selectedBase

        })
      }
    },
    editDataSrc() {
      this.dataSrcVisible = true
      this.selectedTable = undefined
    },
    handleBaseChange() {
      this.fetchTables()
    },
    // async fetchTables() {
    //   const { data } = await linkedTablesByBase(this.selectedBase)
    //   this.tableList = data
    // },
    // handleDataSrcChange() {
    //   this.dataSrcVisible = false
    //   this.fetchSchema()
    //   store.setAllColsAction([])
    //   this.$emit('change', {
    //     table: this.selectedTable,
    //     source_id: this.selectedBase

    //   })
    // },
    handleDataSrcChange(e) {
      console.log('selectedTable：', this.selectedTable)

      this.dataSrcVisible = false
      this.fetchSchema()
      store.setAllColsAction([])
      this.$emit('change', {
        table: this.selectedTable,
        source_id: this.selectedBase

      })
    },

    // fetchSchema() {
    //   if (!this.selectedTable) {
    //     this.tableSchema = []
    //     return
    //   }
    //   this.schemaLoading = true
    //   exeSql().fetch({ source_id: this.selectedBase, sql: `desc ${this.selectedTable}` }).then(resp => {
    //     this.schemaLoading = false
    //     this.tableSchema = resp.data.map((item, index) => {
    //       return {
    //         Column: item.Field,
    //         Type: item.Type,
    //         id: index
    //       }
    //     })
    //     store.setAllColsAction(this.tableSchema)
    //   })
    // },
    // 字段下拉框
    fetchSchema() {
      console.log('selectedTable：', this.selectedTable)
      // if (!this.selectedTable) {
      //   this.tableSchema = []
      //   return
      // }
      this.schemaLoading = true

      var send_data2 = {
        name: 'getColumnName',
        page: 1,
        offset: 1,

        returntype: 'Map',
        parammaps: {
          table_name: this.selectedTable
        }
      }
      GetDataByName(send_data2).then(resp => {
        console.log('字段数据:', resp.data.list)
        if (resp.data.list !== null) {
          this.schemaLoading = false
          this.tableSchema = resp.data.list.map((item, index) => {
            return {
              Column: item.Field,
              Type: item.Type,
              id: index,
              Comment: item.Comment
            }
          })
          store.setAllColsAction(this.tableSchema)
        } else {
          this.tableSchema = []
        }
        console.log('tableSchema数据:', this.tableSchema)
      })
    },
    handleMove(evt, originalEvent) {
      if (this.allSelected.find(item => item.Column === evt.draggedContext.element.Column)) {
        if (!this.existWarning) {
          this.existWarning = this.$message({
            type: 'warning',
            message: this.$t('chart.fieldExisted'),
            onClose: (instance) => {
              this.existWarning = null
            }
          })
        }
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
body .el-scrollbar__wrap {
  overflow-x: hidden;
}
.panel {
  /deep/ .el-form-item__label {
    line-height: initial;
  }
  /deep/ .el-form-item__content {
    line-height: initial;
  }
}
.drag-list-item {
  line-height: 1.5;
  font-size: 14px;
  color: #606266;
  cursor: -webkit-grab;
}
</style>
