import {forwardRef, memo, useCallback, useState} from 'react';
import {ProForm, ProFormSelect} from "@ant-design/pro-components";
import {request} from "../../../../utils/request";

const component = forwardRef(({
  initialValues,
  onFinish,
  submitter,
  options
},ref) => {
  // 数据源ID 数据库名 表名
  const [targetField, setTargetField] = useState([]);

  const onTargetTableChange = useCallback(async (tableName)=>{
    ref?.current?.setFieldsValue({targetFields: null})
    const { data } = await request({
      url: `/semantic/database/getColumns/${options?.sourceId}/${options?.db}/${tableName}`,
      method: "GET",
    })
    setTargetField(data)
  },[])

  const handleFinish=(values)=>{
    const margeTable = {...values,insertFields:targetField}
    console.log(margeTable)
    onFinish(margeTable)
  }
  return (
    <ProForm
      // initialValues={{sourceTable:"1",sourceFields:"2",targetTable:"3",targetFields:"4"}}
      initialValues={initialValues}
      formRef={ref}
      style={{width:500}}
      labelCol={{span:6}}
      wrapperCol={{span:16}}
      layout='horizontal'
      submitter={submitter}
      onFinish={handleFinish}
    >
      <ProFormSelect
        label="主表"
        name="sourceTable"
        placeholder="请选择数据表"
        disabled={true}
        rules={[{ required: true }]}
        options={[options.sourceTable]}
        initialValue={options.sourceTable.value}
      />
      <ProFormSelect
        label="主表字段"
        showSearch
        name="sourceFields"
        placeholder="请选择字段"
        rules={[{ required: true }]}
        options={options.sourceFields}
      />
      <ProFormSelect
        label="从属表"
        name="targetTable"
        showSearch
        placeholder="请选择数据表"
        rules={[{ required: true }]}
        options={options.targetTable}
        onChange={onTargetTableChange}
      />
      <ProFormSelect
        label="连接字段"
        showSearch
        name="targetFields"
        placeholder="请选择字段"
        rules={[{ required: true }]}
        options={targetField.map(item=>({
          label:item.columnName,
          value:item.columnName,
        }))}
      />
      <ProFormSelect
        label="连接类型"
        name="joinType"
        placeholder="请选择连接类型"
        rules={[{ required: true }]}
        valueEnum={{
          leftJoin:'左连接',
          rightJoin:'右连接',
          innerJoin:'内连接',
        }}
      />
      <ProFormSelect
        label="查询字段"
        showSearch
        name="queryFields"
        placeholder="请选择字段"
        rules={[{ required: true }]}
        fieldProps={{
          mode: 'multiple',
          maxTagCount:'responsive',
        }}
        options={
          targetField.map(item=>({
            label:item.columnName,
            value:JSON.stringify(item),
          }))
        }
      />
    </ProForm>
  )
})
export const RelationForm = memo(component);
