import React, { useEffect, useMemo, useState } from 'react'
import styled from 'styled-components'
import { Tree, Tabs, Table, Input } from 'antd'
import { getTableData, getTableSchema } from '../services'
import PropTypes from 'prop-types'

const { DirectoryTree } = Tree
const { TabPane } = Tabs

const DatasourceWrapper = styled.div`
  display: flex;
  width: 100%;
  height: 700px;
  .datasource__tree {
    width: 30%;
    overflow: auto;
    background: #f3f3f3;
    // margin-top: 40px;
    padding-top: 20px;
  }
  .datasource__table {
    flex: 1;
    height: 100%;
    margin-left: 15px;
    overflow: auto;
  }
`
const { Search } = Input
const DatasourceData = props => {
  const { data, datasourceId } = props

  // 表内容表头
  const [contentCols, setContentCols] = useState([])
  // 表内容表数据
  const [contentData, setContentData] = useState([])
  // 表内容表格Loading状态
  const [contentLoading, setContentLoading] = useState(false)
  // 表结构表头
  const [schemaCols, setScheamCols] = useState([])
  // 表结构表数据
  const [schemaData, setScheamData] = useState([])
  // 表结构表格Loading状态
  const [schemaLoading, setSchemaLoading] = useState(false)
  const [treeData, setTreeData] = useState([])
  const [baseData, setBaseData] = useState([])

  useMemo(() => {
    const treeList = data.map(item => {
      return {
        key: item,
        title: item,
        isLeaf: true,
      }
    })
    setTreeData(treeList)
    setBaseData(treeList)
  }, [data])

  useEffect(() => {
    if (treeData[0]) {
      onSelect(treeData[0].key)
    }
  }, [treeData])

  const onSelect = selectedKeys => {
    const params = {
      id: datasourceId,
      table_name: selectedKeys,
    }
    fetchTableData(params)
    fetchTableSchema(params)
  }

  const fetchTableData = async params => {
    setContentLoading(true)
    const { data } = await getTableData(params)
    if (data.code) {
      handleContent(data.data)
    }
    setContentLoading(false)
  }

  const fetchTableSchema = async params => {
    setSchemaLoading(true)
    const { data } = await getTableSchema(params)
    if (data.code) {
      handleSchema(data.data)
    }
    setSchemaLoading(false)
  }

  const handleContent = contentData => {
    const colsList = contentData?.header?.map(item => {
      return {
        title: item,
        dataIndex: item,
        key: item,
      }
    })
    const dataList = contentData?.content?.map((item, index) => {
      const row = {}
      row['key'] = index + 1
      item.forEach((val, index) => {
        const title = contentData.header[index]
        row[title] = val
      })
      return row
    })
    setContentCols(colsList)
    setContentData(dataList)
  }

  const handleSchema = schemaData => {
    const colsList = [
      {
        title: '序号',
        dataIndex: 'order',
        key: 'order',
      },
      {
        title: '字段',
        dataIndex: 'field',
        key: 'field',
      },
      {
        title: '属性',
        dataIndex: 'attribute',
        key: 'attribute',
      },
    ]
    const dataList = schemaData?.map((item, index) => {
      const row = {}
      row['key'] = index + 1
      const [order, field, attribute] = item.split(':')
      row['order'] = order
      row['field'] = field
      row['attribute'] = attribute
      return row
    })
    setScheamCols(colsList)
    setScheamData(dataList)
  }

  const onSearch = val => {
    const list = [...baseData]
    const filterData = list.filter(item => item.title.indexOf(val) > -1)
    setTreeData(filterData)
  }

  const tree = (
    <div className="datasource__tree">
      <Search
        style={{
          marginBottom: 8,
        }}
        placeholder="Search"
        onSearch={onSearch}
      />

      <DirectoryTree
        treeData={treeData}
        style={{
          background: '#f3f3f3',
        }}
        height={600}
        defaultSelectedKeys={[treeData[0]?.key]}
        onSelect={onSelect}
      />
    </div>
  )

  return (
    <DatasourceWrapper>
      {tree}
      <Tabs className="datasource__table" size={'small'}>
        <TabPane tab="预览表内容" key="content">
          <Table
            columns={contentCols}
            dataSource={contentData}
            bordered
            loading={contentLoading}
            scroll={{ x: 3500 }}
          />
        </TabPane>
        <TabPane tab="预览表结构" key="schema">
          <Table
            columns={schemaCols}
            dataSource={schemaData}
            bordered
            loading={schemaLoading}
            scroll={{ x: 3500 }}
          />
        </TabPane>
      </Tabs>
    </DatasourceWrapper>
  )
}

DatasourceData.propTypes = {
  data: PropTypes.array,
  datasourceId: PropTypes.number,
}

export default DatasourceData
