import React, { useState, useEffect } from 'react'
import { Form, Select, Input, message } from 'antd'
import { getTableNamesList, getAilabList, getLakeTable } from '../services'

export default function StepOne({
  drawDataForm,
  dataSourceList,
  updateTableStruct,
  updateDrawAilabStruct,
  updateDrawLakeStruct,
}) {
  const [datasourceType, setDatasourceType] = useState(null)

  const [datasources, setDatasources] = useState()

  const [tableList, setTableList] = useState([])

  const [dsType, setDsType] = useState(null)

  // 获取数据源列表
  useEffect(() => {
    if (dataSourceList.length !== 0) {
      setDatasources(
        dataSourceList.map(item => {
          return {
            label: item.datasource_name,
            value: item.key,
          }
        })
      )
    }
  }, [dataSourceList])

  // 初始化表单类型
  useEffect(() => {
    const ds_id = drawDataForm.getFieldValue('datasource_name')
    const table_name = drawDataForm.getFieldValue('datasource_table')
    setDsType(drawDataForm.getFieldValue('datasource_type'))
    if (ds_id) {
      const type = dataSourceList.find(item => item.key === ds_id).datasource
      setDatasourceType(type)
      selectDatasource(ds_id)
      drawDataForm.setFieldValue('datasource_table', table_name)
    }
  }, [])

  // 选择数据源
  const selectDatasource = async val => {
    drawDataForm.setFieldValue('datasource_table', null)
    const type = dataSourceList.find(item => item.key === val)?.datasource
    setDatasourceType(type)
    const { data } = await getTableNamesList(val)
    if (data.code === 200) {
      const list = data.data.map(item => ({
        label: item,
        value: item,
      }))
      setTableList(list)
    } else {
      message.error('数据表加载失败')
    }
  }

  const selectAilab = async () => {
    const { data } = await getAilabList()
    if (data.code === 200) {
      const list = data.data.map((item, index) => {
        return {
          key: index,
          label: item,
          value: item,
        }
      })
      setTableList(list)
    } else {
      message.error(data.msg)
    }
  }

  const selectLake = async () => {
    const { data } = await getLakeTable()
    if (data.code === 200) {
      const list = data.data.map((item, index) => {
        return {
          key: index,
          label: item.table_name,
          value: item.table_name,
          table_path: item.table_path,
        }
      })
      setTableList(list)
    } else {
      message.error(data.msg)
    }
  }

  // 选择表
  const selectTable = val => {
    const currentTable = drawDataForm.getFieldValue('datasource_table')
    switch (dsType) {
      case 'datasource':
        const ds_id = drawDataForm.getFieldValue('datasource_name')
        updateTableStruct(ds_id, val)
        break
      case 'datalake':
        updateDrawLakeStruct(currentTable)
        drawDataForm.setFieldValue(
          'reader_path',
          tableList.find(item => (item.value = currentTable)?.table_path)
        )
        break
      default:
        updateDrawAilabStruct(currentTable)
        break
    }
  }

  const selectDsType = val => {
    setDsType(val)
    switch (val) {
      case 'datasource':
        selectDatasource(drawDataForm.getFieldValue('datasource_name'))
        break
      case 'datalake':
        setDatasourceType('hive')
        selectLake()
        break
      default:
        setDatasourceType('hive')
        selectAilab()
        break
    }
  }

  return (
    <>
      <p
        style={{
          fontWeight: 600,
          borderLeft: '3px solid #1890ff',
          paddingLeft: '12px',
        }}>
        配置提取源
      </p>
      <Form
        name="drawForm"
        form={drawDataForm}
        labelCol={{
          span: 2,
        }}
        wrapperCol={{
          span: 6,
        }}
        initialValues={{
          query_sql: '',
          where_param: '',
          reader_split_pk: '',
          delimiter: '',
        }}>
        <Form.Item
          label="数据源分类"
          name="datasource_type"
          rules={[
            {
              required: true,
              message: '请选择数据源分类!',
            },
          ]}>
          <Select
            allowClear
            options={
              ['1', '2', '3'].includes(sessionStorage.getItem('role'))
                ? [
                    { label: '自添加数据源', value: 'datasource' },
                    { label: 'AIlab', value: 'ailab' },
                    { label: '数据湖', value: 'datalake' },
                  ]
                : [{ label: 'AIlab', value: 'ailab' }]
            }
            onSelect={selectDsType}
            placeholder="请选择数据源分类"
          />
        </Form.Item>
        {dsType === 'datasource' && (
          <Form.Item
            label="选择数据源"
            name="datasource_name"
            rules={[
              {
                required: true,
                message: '请选择数据源!',
              },
            ]}>
            <Select
              showSearch
              optionFilterProp="label"
              allowClear
              options={datasources}
              onSelect={selectDatasource}
              placeholder="请选择数据源"
            />
          </Form.Item>
        )}
        <Form.Item
          label="选择表"
          name="datasource_table"
          rules={[
            {
              required: true,
              message: '请选择表',
            },
          ]}>
          <Select
            showSearch
            optionFilterProp="label"
            options={tableList}
            allowClear
            onSelect={selectTable}
            placeholder="请选择数据表"
          />
        </Form.Item>
        {datasourceType === 'mysql' ? (
          <>
            <Form.Item
              label="query sql"
              name="query_sql"
              wrapperCol={{ span: 10 }}>
              <Input.TextArea
                rows={5}
                placeholder="sql查询，一般用于多表关联查询时才用"
              />
            </Form.Item>
            <Form.Item label="切分主键" name="reader_split_pk">
              <Input placeholder="切分主键" />
            </Form.Item>
            <Form.Item
              label="条件语句"
              name="where_param"
              wrapperCol={{ span: 10 }}>
              <Input.TextArea rows={5} placeholder="where条件" />
            </Form.Item>
          </>
        ) : (
          <>
            <Form.Item
              label="选择路径"
              name="reader_path"
              wrapperCol={{ span: 10 }}
              rules={[
                {
                  required: true,
                  message: '请选择路径!',
                },
              ]}>
              <Input.TextArea rows={5} />
            </Form.Item>
            <Form.Item
              label="HDFS"
              name="reader_default_fs"
              rules={[
                {
                  required: true,
                  message: '请输入HDFS',
                },
              ]}>
              <Input placeholder="Hadoop hdfs文件系统namenode节点地址" />
            </Form.Item>
            <Form.Item
              label="文件类型"
              name="reader_file_type"
              rules={[
                {
                  required: true,
                  message: '请选择文件类型',
                },
              ]}>
              <Select
                options={[
                  { label: 'text', value: 'text' },
                  { label: 'csv', value: 'csv' },
                  { label: 'orc', value: 'orc' },
                ]}
                allowClear
                placeholder="文件的类型"
              />
            </Form.Item>
            <Form.Item
              label="分隔符"
              name="reader_field_delimiter"
              rules={[
                {
                  required: true,
                  message: '请输入分隔符!',
                },
              ]}>
              <Input placeholder="读取字段的分隔符" />
            </Form.Item>
          </>
        )}
      </Form>
    </>
  )
}
