import React from 'react';
import { Select, Pagination, Input, Table, Row, Col } from "antd"

import { dispatchLatest } from '../../../../model';

const { Option } = Select;

class ImportMetadata extends React.Component {
  constructor() {
    super();

    this.state = {
      systems: [],
      dbs: [{ value: '', name: '所有数据源' }],
      schemas: [{ value: '', name: '所有Schema' }],
      modelPaths: [
        { value: '', name: '所有类型' },
        { value: 'Catalog,Database,Schema,HanaView', name: 'HANA视图' },
        { value: 'Catalog,Database,Schema,Table', name: '数据表' },
        { value: 'Catalog,Database,Schema,View', name: '数据视图' },
        { value: 'Catalog,Database,Schema,Function', name: '函数' },
        { value: 'Catalog,Database,Schema,Procedure', name: '存储过程' },
      ],
      dataTables: [],
      totalDataTables: 0,
      dataFileds: [],
      system: '',
      db: '',
      schema: '',
      modelPath: '',
      keyboard: '',
      pageNumDataTables: 1,
      pageSizeDataTables: 20,
      loadingDataTable: false,
      loadingDataFiled: false,
      loadingSystem: false,
      loadingDb: false,
      loadingSchema: false,
      selectedDataTableRowKeys: [],
      selectedDataFiledRowKeys: [],
      dataTableColumns: [
        { title: '名称', dataIndex: 'name', key: 'name' },
        { title: '中文名称', dataIndex: 'cnName', key: 'cnName' },
        { title: '描述', dataIndex: 'comment', key: 'comment' },
      ],
      dataFiledColumns: [
        { title: '目标表字段', dataIndex: 'name', key: 'name' },
      ]
    };
  }

  componentDidMount() {

    this.setState({ loadingSystem: true, loadingDb: true }, () => {
      dispatchLatest({
        type: 'datamodel.getAllSystemAndDatabase',
        callback: data => {
          if (data && data.systems && data.systems.length) {
            const _system = data.systems[0].scopeId;
            this.setState({ loadingSystem: false, loadingDb: false, systems: data.systems, system: _system, dbs: data.dbs, db: '', schema: '' }, () => {
              this.fetchAllDataTable();
            })
          } else {
            this.setState({ loadingSystem: false });
          } 
        },
        error: () => {
          this.setState({ loadingSystem: false });
        }
      })
    })
  }

  systemOnChanged = (value) => {

    if (value === '') {
      this.setState({ 
        system: value, 
        dbs: [{ value: '', name: '所有数据源' }],
        schemas: [{ value: '', name: '所有Schema' }],
        db: '',
        schema: ''
      })
    } else {
      
      this.setState({ loadingDb: true, system: value }, () => {
        dispatchLatest({
          type: "datamodel.getAllSystemDatabase",
          payload: {
            sysCodedataTables: value
          },
          callback: dbs => {
            this.setState({ loadingDb: false, dbs: dbs||[], db: '', schema: ''  })
          },
          erorr: () => {
            this.setState({ loadingDb: false });
          }
        });
      });

    }
    
  }

  dbOnChanged = (value) => {

    if (value === '') {
      
      this.setState({ db: value, schemas: [{ value: '', name: '所有Schema' }], schema: '' })
    
    } else {
      
      this.setState({ loadingSchema: true, db: value }, () => {
        dispatchLatest({
          type: "datamodel.getAllScheme",
          payload: {
            db: value
          },
          callback: schemas => {
            this.setState({ loadingSchema: false, schemas, schema: '' });
          },
          error: () => {
            this.setState({ loadingSchema: false });
          }
        });
      })

    }

  }

  schemaOnChanged = (value) => {
    this.setState({ schema: value });
  }

  modelPathOnChanged = (value) => {
    this.setState({ modelPath: value });
  }

  sizeChangeOnDataTable = (pageNum, pageSize=20) => {
    this.setState({ pageNumDataTables: pageNum, pageSizeDataTables: pageSize });
  }

  sizeChangeOnDataField = (pageNum, pageSize=20) => {
    this.setState({ pageNumDataFileds: pageNum, pageSizeDataFileds: pageSize });
  }

  fetchAllDataTable = () => {
    const { system, db, schema, modelPath, pageNumDataTables, pageSizeDataTables, keyboard } = this.state;

    let _db = '';
    if(db !== '' && db.split(',').length > 1) {
      _db = db.split(',')[1];
    }

    this.setState({ loadingDataTable: true }, () => {
      dispatchLatest({
        type: "datamodel.getAllDataTable",
        payload: {
          pageNum: pageNumDataTables,
          pageSize: pageSizeDataTables,
          name: keyboard,
          sysId: system,
          database: _db,
          schema,
          modelPath
        },
        callback: data => {
          this.setState({ loadingDataTable: false, dataTables: (data||[]).content||[], totalDataTables: (data||[]).totalElements||0 })
        },
        error: () => {
          this.setState({ loadingDataTable: false });
        }
      });
    })
  }

  render() {
    const { systems, dbs, schemas, modelPaths, system, db, schema, modelPath, pageNumDataTables, pageSizeDataTables, loadingDataTable, loadingDataFiled, loadingSystem, loadingDb, loadingSchema, dataTables, dataFileds, totalDataTables, dataTableColumns, dataFiledColumns  } = this.state;

    const rowDataTableSelection = {
      type: 'radio',
      onChange: (selectedRowKeys, selectedRows) => {

        this.setState({ selectedDataTableRowKeys: selectedRowKeys, loadingDataFiled: true }, () => {
          dispatchLatest({
            type: "datamodel.getAllFileds",
            payload: {
              parentId: selectedRowKeys[0],
              model:'Column,InterfaceColumn,HanaViewColumn'
            },
            callback: data => {
              this.setState({ loadingDataFiled: false, dataFileds: data||[] })
            },
            error: () => {
              this.setState({ loadingDataFiled: false });
            }
          });
        })

      },
    };

    const rowDataFiledSelection = {
      type: 'radio',
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedDataFiledRowKeys: selectedRowKeys });
      },
    };

    return (
      <>
      <div style={{paddingTop:10}}>
        <Select
          value={system}
          style={{ width: 146 }}
          loading={loadingSystem}
          onChange={this.systemOnChanged}
        >
        {
          systems && systems.map((item, index) => {
            return <Option key={index} value={item.scopeId}>{item.scopeName||''}</Option>;
          })
        }
        </Select>
        <Select
          value={db}
          onChange={this.dbOnChanged}
          loading={loadingDb}
          style={{ width: 150,marginLeft:10 }}
        >
        {
          dbs && dbs.map((item, index) => {
            return <Option key={index} value={item.value===''?'':(item._id+','+item.name)}>{item.name}</Option>;
          })
        }
        </Select>
        <Select
          value={schema}
          loading={loadingSchema}
          onChange={this.schemaOnChanged}
          style={{ width: 150,marginLeft:10 }}
        >
        {
          schemas && schemas.map((item, index) => {
            return <Option key={index} value={item.value===''?'':item.name}>{item.name}</Option>;
          })
        }
        </Select>
        <Select
          value={modelPath}
          onChange={this.modelPathOnChanged}
          style={{ width: 150,marginLeft:10 }}
        >
        {
          modelPaths && modelPaths.map((item, index) => {
            return <Option key={index} value={item.value}>{item.name}</Option>;
          })
        }
        </Select>
      </div>
      <div style={{margin:'10px 0'}}>
        <Input.Search style={{width:180,marginLeft:10}} 
          onChange={e=>{ this.setState({ keyboard: e.target.value })}}
          placeholder={"请输入关键字"}
          enterButton
          onSearch={()=>{this.fetchAllDataTable()}}
        />
      </div>
      <Row gutter={10}>
        <Col span={12}>
          <Table
            columns={dataTableColumns}
            rowKey="_id"
            size="small"
            loading={loadingDataTable}
            dataSource={dataTables}
            pagination={false}
            rowSelection={rowDataTableSelection}
          />
          <Pagination 
            showTotal={total => `共 ${total} 条`} 
            showSizeChanger 
            size="small"
            pageSize={pageSizeDataTables} 
            pageSizeOptions={['20','60','100']} 
            current={pageNumDataTables} 
            onShowSizeChange={this.sizeChangeOnDataTable} 
            onChange={this.sizeChangeOnDataTable} 
            total={totalDataTables} 
            style={{marginTop:10}}
          />
        </Col>
        <Col span={12}>
          <Table
            columns={dataFiledColumns}
            rowKey="_id"
            size="small"
            loading={loadingDataFiled}
            dataSource={dataFileds}
            pagination={false}
            rowSelection={rowDataFiledSelection}
          />
        </Col>
      </Row>
      </>
    )
  }
}

export default ImportMetadata;