import React, { useState } from 'react';
import {
  Button,
  DatePicker,
  Form,
  InputNumber,
  Radio,
  RadioChangeEvent,
  Select,
  Space
} from 'antd';
import { IDatasource } from './api/datasource';
import arrowImgUrl from '../style/img/arrow.png';
import deleteImgUrl from '../style/img/delete.png';

type FreqUnit = 'day' | 'week' | 'month';

interface ISyncMeta {
  startTime: Date;
  frequency: number;
  freqUnit: FreqUnit;
}

interface ISyncMapping {
  srcDatasource: IDatasource;
  srcTableName: string;
  dstDatasource: IDatasource;
  dstTableName: string;
}

export interface ISyncData {
  mapping: ISyncMapping;
  meta: ISyncMeta;
}

interface IProps {
  datasourceList: IDatasource[];
  tableListFetcher: (ds: IDatasource) => Promise<string[]>;
  onConfirm: (data: ISyncData[]) => void;
  onCancel: () => void;
}

const DatasyncForm: React.FunctionComponent<IProps> = props => {
  const [srcDatasource, setSrcDatasource] = useState<IDatasource | null>(null);
  const [srcTableName, setSrcTableName] = useState<string | null>(null);
  const [srcTableList, setSrcTableList] = useState<string[]>([]);
  const [dstDatasource, setDstDatasource] = useState<IDatasource | null>(null);
  const [dstTableName, setDstTableName] = useState<string | null>(null);
  const [dstTableList, setDstTableList] = useState<string[]>([]);
  const [mappingList, setMappingList] = useState<ISyncMapping[]>([]);
  const [form] = Form.useForm();

  const onFinish = (meta: any) => {
    // startTime = moment(startTime).toDate();
    const results = mappingList.map(mapping => {
      return {
        mapping,
        meta: {
          startTime: meta.startTime.toDate(),
          frequency: Math.max(parseInt(meta.frequency), 0),
          freqUnit: meta.freqUnit as FreqUnit
        }
      };
    });
    props.onConfirm(results);
  };

  const sourceDatasourceChange = (sourcename: string) => {
    const ds = props.datasourceList.find(
      item => item.sourcename === sourcename
    )!;
    setSrcDatasource(ds);
    setSrcTableName(null);
    setSrcTableList([]);
    void props.tableListFetcher(ds).then(lst => {
      setSrcTableList(lst);
    });
  };

  const destDatasourceChange = (sourcename: string) => {
    const ds = props.datasourceList.find(
      item => item.sourcename === sourcename
    )!;
    setDstDatasource(ds);
    setDstTableName(null);
    setDstTableList([]);
    void props.tableListFetcher(ds).then(lst => {
      setDstTableList(lst);
    });
  };

  const sourceTableChange = (e: RadioChangeEvent) => {
    setSrcTableName(e.target.value as string);
  };

  const destTableChange = (e: RadioChangeEvent) => {
    setDstTableName(e.target.value as string);
  };

  const addMapping = () => {
    if (!srcDatasource || !srcTableName || !dstDatasource || !dstTableName) {
      return;
    }
    if (
      mappingList.find(
        item =>
          item.srcDatasource.sourcename === srcDatasource.sourcename &&
          item.srcTableName === srcTableName &&
          item.dstDatasource.sourcename === dstDatasource.sourcename &&
          item.dstTableName === dstTableName
      )
    ) {
      return;
    }
    setMappingList([
      ...mappingList,
      {
        srcDatasource,
        srcTableName,
        dstDatasource,
        dstTableName
      }
    ]);
  };

  const deleteMapping = (mapping: ISyncMapping) => {
    setMappingList(mappingList.filter(item => item !== mapping));
  };

  const freqUnitSelector = (
    <Form.Item
      name="freqUnit"
      rules={[{ required: true, message: '请输入同步频次单位' }]}
      noStyle
    >
      <Select style={{ width: 100 }}>
        <Select.Option value="day">天</Select.Option>
        <Select.Option value="week">周</Select.Option>
        <Select.Option value="month">月</Select.Option>
      </Select>
    </Form.Item>
  );

  return (
    <div>
      <Form
        form={form}
        name="datasyncForm"
        onFinish={onFinish}
        style={{ width: '800px' }}
      >
        <div style={{ display: 'flex' }}>
          <Form.Item style={{ width: '25%' }}>
            <Form.Item
              name="srcDatasource"
              noStyle
              // rules={[{ required: true, message: '请选择数据源' }]}
            >
              <Select
                placeholder="选择数据源"
                onChange={sourceDatasourceChange}
              >
                {props.datasourceList.map(item => {
                  return (
                    <Select.Option
                      value={item.sourcename}
                      key={item.sourcename}
                    >
                      {item.databasename}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>

            <Form.Item
              name="srcTableName"
              // rules={[{ required: true, message: '请选择源数据表' }]}
              noStyle
            >
              <div className="plane">
                <Radio.Group value={srcTableName} onChange={sourceTableChange}>
                  <Space direction="vertical">
                    {srcTableList.map(item => {
                      return (
                        <Radio value={item} key={item}>
                          {item}
                        </Radio>
                      );
                    })}
                  </Space>
                </Radio.Group>
              </div>
            </Form.Item>
          </Form.Item>
          <div className="arrow">
            <img
              src={arrowImgUrl}
              alt=""
              onClick={addMapping}
              style={{ width: '20px', height: '20px', cursor: 'pointer' }}
            />
          </div>
          <Form.Item style={{ width: '25%' }}>
            <Form.Item
              name="dstDatasource"
              // rules={[{ required: true, message: '请选择同步目标' }]}
              noStyle
            >
              <Select
                placeholder="选择同步目标"
                onChange={destDatasourceChange}
              >
                {props.datasourceList.map(item => {
                  return (
                    <Select.Option
                      value={item.sourcename}
                      key={item.sourcename}
                    >
                      {item.databasename}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
            <Form.Item
              name="dstTableName"
              // rules={[{ required: true, message: '请选择目标数据表' }]}
              noStyle
            >
              <div className="plane">
                <Radio.Group value={dstTableName} onChange={destTableChange}>
                  <Space direction="vertical">
                    {dstTableList.map(item => {
                      return (
                        <Radio value={item} key={item}>
                          {item}
                        </Radio>
                      );
                    })}
                  </Space>
                </Radio.Group>
              </div>
            </Form.Item>
          </Form.Item>
          <div className="line"></div>
          <div className="mappings">
            <p className="mappings__title">同步映射</p>
            <div className="mappings__content">
              {mappingList.map(item => {
                const key = `${item.dstDatasource.sourcename}-${item.dstTableName}-${item.srcDatasource.sourcename}-${item.srcTableName}`;
                return (
                  <p key={key}>
                    <span>{item.srcTableName}</span>
                    <img
                      src={arrowImgUrl}
                      alt=""
                      style={{
                        width: '10px',
                        height: '10px',
                        margin: '0 50px'
                      }}
                    />
                    <span>{item.dstTableName}</span>
                    <img
                      src={deleteImgUrl}
                      alt=""
                      onClick={() => {
                        deleteMapping(item);
                      }}
                      style={{
                        width: '10px',
                        height: '10px',
                        marginLeft: '30px',
                        cursor: 'pointer'
                      }}
                    />
                  </p>
                );
              })}
            </div>
          </div>
        </div>
        <Form.Item
          label="开始时间"
          name="startTime"
          rules={[{ required: true, message: '请选择开始时间' }]}
        >
          <DatePicker placeholder="请选择日期" style={{ width: '50%' }} />
        </Form.Item>
        <Form.Item label="同步频次" required>
          <span style={{ lineHeight: '32px' }}>每</span>
          <Form.Item
            name="frequency"
            rules={[{ required: true, message: '请输入同步频次' }]}
            noStyle
          >
            <InputNumber
              addonAfter={freqUnitSelector}
              style={{ width: '47%', margin: '0 1%' }}
            />
          </Form.Item>
          <span style={{ lineHeight: '32px' }}>/次</span>
        </Form.Item>
        <Form.Item style={{ display: 'flex', justifyContent: 'center' }}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ marginRight: '40px' }}
          >
            确定
          </Button>
          <Button htmlType="button" onClick={props.onCancel}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default DatasyncForm;
