import { ReactVisualEditorTableProp } from './../ReactVisualEditor.props';
import { Button, Input, Modal, Table, Tag } from 'antd';
import { PlusSquareOutlined } from '@ant-design/icons';
import ReactDOM from 'react-dom';
import { defer } from './../../utils/defer';
import React,{ useState } from 'react';
import deepcopy from 'deepcopy';

const nextKey = (() => {
  let start = Date.now();
  return () => start++;
})();

export const TablePropEditor: React.FC<{
  value?: any[];
  config: ReactVisualEditorTableProp;
  onChange?: (val?: any[]) => void;
}> = (props) => {
  const methods = {
    openEdit: async () => {
      const newVal = await TablePropEditService({
        config: props.config,
        value: props.value,
      });
      !!props.onChange && props.onChange(newVal);
    },
  };

  let render: any;
  if (!props.value || props.value.length === 0) {
    render = (
      <Button onClick={methods.openEdit}>
        <PlusSquareOutlined />
        <span>编辑</span>
      </Button>
    );
  } else {
    render = props.value.map((item, index) => {
      return (
        <Tag key={index} onClick={methods.openEdit}>
          {item.value}
        </Tag>
      );
    });
  }

  return <div className="table-prop-editor">{render}</div>;
};

interface TablePropEditServiceOption {
  config: ReactVisualEditorTableProp;
  value?: any[];
  onConfirm?: (val?: any[]) => void;
}

const TablePropEditModal: React.FC<{
  option: TablePropEditServiceOption;
  onRef: (ins: { show: (opt: TablePropEditServiceOption) => void }) => void;
}> = (props) => {
  const [option, setOption] = useState(props.option);
  const [showFlag, setShowFlag] = useState(false);
  const [editData, $setEditData] = useState([] as any[]);

  const setEditData = (val: any[]) => {
    $setEditData(
      val.map((d) => {
        !d.key && (d.key = nextKey());
        return d;
      }),
    );
  };

  const methods = {
    show: (opt: TablePropEditServiceOption) => {
      setOption(opt);
      setEditData(deepcopy(opt.value || []));
      setShowFlag(true);
    },
    close: () => {
      setShowFlag(false);
    },
    save: () => {
      !!option.onConfirm && option.onConfirm(editData);
      methods.close();
    },
    add: () => {
      setEditData([ ...editData,{}]);
    },
    reset: () => {
      setEditData(option.value || []);
    },
  };

  props.onRef(methods);

  return (
    <Modal
      visible={showFlag}
      footer={
        <>
          <Button onClick={methods.close}>取消</Button>
          <Button type="primary" onClick={methods.save}>
            保存
          </Button>
        </>
      }
      onCancel={methods.close}
      width="800px"
    >
      <div className="table-prop-editor-dialog-buttons">
        <Button onClick={methods.add} type="primary" style={{ marginRight: '8px' }}>
          添加
        </Button>
        <Button onClick={methods.reset}>重置</Button>
      </div>
      <div className="table-prop-editor-dialog-table">
        <Table dataSource={editData}>
          <Table.Column
            key="index"
            dataIndex={''}
            title={'#'}
            render={(_1, _2, index) => {
              return index + 1;
            }}
          />
          {(option.config.columns || []).map((col, index) => (
            <Table.Column
              title={col.name}
              dataIndex={col.field}
              key={index}
              render={(_1, row: any, index) => {
                return (
                  <Input
                    key="input"
                    value={row[col.field]}
                    onChange={(e) => {
                      row = { ...row, [col.field]: e.target.value };
                      editData[index] = row;
                      setEditData([...editData]);
                    }}
                  />
                );
              }}
            />
          ))}
          <Table.Column
            title="操作栏"
            key="operator"
            render={(_1, _2, index) => {
              return (
                <Button
                  onClick={() => {
                    editData.splice(index, 1);
                    setEditData(editData);
                  }}
                  type={'text'}
                >
                  删除
                </Button>
              );
            }}
          />
        </Table>
      </div>
    </Modal>
  );
};

export const TablePropEditService = (() => {
  let ins: any;
  return (option: Omit<TablePropEditServiceOption, 'onConfirm'>): Promise<undefined | any[]> => {
    const dfd = defer<undefined | any[]>();
    option = {
      ...option,
      onConfirm: dfd.resolve,
    } as TablePropEditServiceOption;
    if (!ins) {
      const el = document.createElement('div');
      document.body.appendChild(el);
      ReactDOM.render(<TablePropEditModal option={option} onRef={(i) => (ins = i)} />, el);
    }
    ins.show(option);

    return dfd.promise;
  };
})();
