import React from 'react';
import { FormContainer, IStepForm, Select, useWizard } from './form';
import { FormDndSortList, IMapping, PlaceHolderItem } from './FormDndSortList';
import { Step1 } from './StepOneForm';
import { Step2 } from './StepTwoForm';
import { ITableSchemaResponse, useTableSchema } from './service';

export namespace Step3 {
  export const KEY = 'step3';
  export const TITLE = '配置转换规则';

  export interface IForm {
    mapping: IMapping<ITableSchemaResponse>[];
    mode: string;
  }

  interface IWizardData {
    [Step1.KEY]?: Partial<Step1.IForm>;
    [Step2.KEY]?: Partial<Step2.IForm>;
  }

  export const Form: React.FunctionComponent<IStepForm<IForm>> = props => {
    const retVal = useWizard({
      ...props,
      defaultValues: { mapping: [] }
    });
    const formProps = retVal.formProps;
    const wizardData: IWizardData = retVal.wizardData;

    const ds1 = wizardData[Step1.KEY]?.dataSource;
    const tn1 = wizardData[Step1.KEY]?.detail?.tableName;
    const ds2 = wizardData[Step2.KEY]?.dataSource;
    const tn2 = wizardData[Step2.KEY]?.detail?.tableName;

    const { data: sourceSchema } = useTableSchema(ds1, tn1);
    const { data: destSchema } = useTableSchema(ds2, tn2);

    const createRowId = (
      sourceSchema?: ITableSchemaResponse | PlaceHolderItem,
      destSchema?: ITableSchemaResponse,
      idx?: number
    ): { sourceId: string; destId: string; rowId: string } => {
      let sourceId: string;
      if (sourceSchema instanceof PlaceHolderItem) {
        sourceId = `${ds1}-${tn1}-${sourceSchema.id}`;
      } else if (sourceSchema) {
        sourceId = `${ds1}-${tn1}-${sourceSchema.field}`;
      } else {
        sourceId = `${ds1}-${tn1}-source${idx}`;
      }
      const destId = destSchema
        ? `${ds2}-${tn2}-${destSchema.field}`
        : `${ds2}-${tn2}-dest${idx}`;
      const rowId = `${sourceId}-${destId}`;
      return { sourceId, destId, rowId };
    };

    const formatItemName = (
      schema: ITableSchemaResponse,
      tableName?: string
    ): string => {
      return `${tableName || ''}${schema.field}.${schema.type}`;
    };

    const matchField = (
      sourceSchema?: ITableSchemaResponse | PlaceHolderItem,
      destSchema?: ITableSchemaResponse
    ): boolean => {
      return (
        !!sourceSchema &&
        !!destSchema &&
        !(sourceSchema instanceof PlaceHolderItem) &&
        sourceSchema.type === destSchema.type &&
        sourceSchema.length === destSchema.length
      );
    };

    return (
      <FormContainer formProps={formProps}>
        <div className="form-group">
          <p className="form-hint">拖拽提取源数据表中的字段，与加载源数据表</p>
        </div>
        <FormDndSortList<ITableSchemaResponse, IForm>
          initSourceList={sourceSchema || []}
          initDestList={destSchema || []}
          sourceName={tn1 || ''}
          destName={tn2 || ''}
          matchFn={matchField}
          createRowId={createRowId}
          formatItemName={(value, isSource) =>
            formatItemName(value, isSource ? tn1 : tn2)
          }
          name="mapping"
          required
        />
        <Select<IForm>
          label="写入模式"
          name="mode"
          options={[
            { label: '追加', value: 'append' },
            { label: '覆盖', value: 'overwrite' }
          ]}
          required
        />
      </FormContainer>
    );
  };
}
