import React, { useCallback } from 'react';
import { Button, Field, Table, Card, Pagination, Message, Dialog } from '@alifd/next';
import { useFusionTable, useSetState } from 'ahooks';
import EmptyBlock from './EmptyBlock';
import ExceptionBlock from './ExceptionBlock';
import DialogOperation from './DialogOperation';
import styles from './index.module.css';

const getTableData = ({ current, pageSize }, formData) => {
  if (!formData.status || formData.status === 'normal') {
    let query = `page=${current}&size=${pageSize}`;
    Object.entries(formData).forEach(([key, value]) => {
      if (value) {
        query += `&${key}=${value}`;
      }
    });
    return fetch(`https://randomuser.me/api?results=${pageSize}&${query}`)
      .then((res) => res.json())
      .then((res) => ({
        total: 55,
        list: res.results.slice(0, 10),
      }));
  }

  if (formData.status === 'empty') {
    return Promise.resolve([]);
  }

  if (formData.status === 'exception') {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('data exception'));
      }, 1000);
    });
  }

  return Promise.resolve([]);
};

const defaultColumnWidth = {
  name: 140,
  email: 500,
  phone: 500,
  gender: 140,
  operation: 150,
};

const DialogTable = () => {
  const [state, setState] = useSetState({
    columnWidth: defaultColumnWidth,
    optCol: null,
    actionType: 'preview',
    actionVisible: false,
  });
  const { actionVisible, columnWidth, optCol } = state;
  const field = Field.useField([]);
  const { paginationProps, tableProps, search, error, refresh } = useFusionTable(getTableData, {
    field,
  });
  const { reset } = search;

  const onResizeChange = (dataIndex, width) => {
    const newWidth = { ...columnWidth };
    newWidth[dataIndex] += width;
    setState({
      columnWidth: newWidth,
    });
  };

  const operationCallback = useCallback(
    ({ actionType, dataSource }) => {
      setState({
        actionType,
        optCol: dataSource,
        actionVisible: true,
      });
    },
    [setState],
  );
  const handleCancel = useCallback(() => {
    setState({
      actionVisible: false,
    });
  }, [setState]);
  const handleOk = useCallback(() => {
    const { actionType } = state;

    if (actionType === 'preview') {
      handleCancel();
      return;
    }

    Message.success(actionType === 'add' ? '添加成功!' : '编辑成功!');
    reset();
    handleCancel();
  }, [handleCancel, reset, state]);
  const handleDelete = useCallback(
    (data) => {
      if (!data) {
        return;
      }

      Dialog.confirm({
        title: '删除提醒',
        content: `确定删除 ${data.name.last} 吗`,

        onOk() {
          Message.success(`${data.name.last} 删除成功!`);
          reset();
        },
      });
    },
    [reset],
  );

  const cellOperation = (...args) => {
    const record = args[2];
    return (
      <div>
        <Button
          text
          type="primary"
          onClick={() =>
            operationCallback({
              actionType: 'edit',
              dataSource: record,
            })
          }
        >
          编辑
        </Button>
        &nbsp;&nbsp;
        <Button text type="primary" onClick={() => handleDelete(record)}>
          删除
        </Button>
        &nbsp;&nbsp;
        <Button
          text
          type="primary"
          onClick={() =>
            operationCallback({
              actionType: 'preview',
              dataSource: record,
            })
          }
        >
          查看
        </Button>
      </div>
    );
  };

  return (
    <div className={styles.dialogTable}>
      <Card free>
        <Card.Content>
          <Table
            {...tableProps}
            onResizeChange={onResizeChange}
            emptyContent={error ? <ExceptionBlock onRefresh={refresh} /> : <EmptyBlock />}
            primaryKey="email"
          >
            <Table.Column title="name" dataIndex="name.last" resizable width={columnWidth.name} />
            <Table.Column title="email" dataIndex="email" resizable width={columnWidth.email} />
            <Table.Column title="phone" dataIndex="phone" resizable width={columnWidth.phone} />
            <Table.Column title="gender" dataIndex="gender" resizable width={columnWidth.gender} />
            <Table.Column title="操作" resizable width={columnWidth.operation} cell={cellOperation} />
          </Table>
          <Pagination
            style={{
              marginTop: 16,
              textAlign: 'right',
            }}
            totalRender={(total) => (
              <>
                共{' '}
                <Button text type="primary">
                  {total}
                </Button>{' '}
                个记录
              </>
            )}
            {...paginationProps}
          />
        </Card.Content>
      </Card>
      <DialogOperation
        visible={actionVisible}
        actionType={state.actionType}
        dataSource={optCol}
        onOk={handleOk}
        onClose={handleCancel}
        onCancel={handleCancel}
      />
    </div>
  );
};

export default DialogTable;
