import React, { useState, useEffect } from 'react';
import { Modal, Table, message } from 'antd';
import { columns } from './staticdata';
import { apiDraftList, apiDraftDetail, apiDeleteDraft } from '../service';

const DraftModal = props => {
  const [pageInfo, setPageInfo] = useState({
    current: 1,
    pageSize: 4,
  });
  const [total, setTotal] = useState(0);
  const [dataSource, setdataSource] = useState([]);

  const onClose = () => props.onCancel();

  const onEdit = async record => {
    const res = await apiDraftDetail(record.id);
    if (res && res.data) {
      const data = JSON.parse(res.data.content);
      data.id = record.id;
      props.onToDetail(data);
      onClose();
    }
  };

  const getDraftList = async params => {
    const res = await apiDraftList(params);
    if (res && res.data && res.data.records) {
      setdataSource(res.data.records);
      setTotal(res.data.total);
    }
  };
  const onRefresh = () => {
    getDraftList({
      pageSize: pageInfo.pageSize,
      pageNo: pageInfo.current,
    });
  };

  const onDel = record => {
    Modal.confirm({
      title: $t('confirmation.prompt'),
      content: $t('action.irreversible.confirm.deletion'),
      onOk: async () => {
        console.log('record :>> ', record);
        await apiDeleteDraft(record.id);
        message.success($t('deleted.successfully'));
        onRefresh();
      },
    });
  };

  const onChange = (current, pageSize) => {
    const json = {
      current,
      pageSize,
    };
    setPageInfo(json);
    json.pageNo = current;
    getDraftList(json);
  };

  const pagination = {
    ...pageInfo,
    total,
    showTotal: t => `共 ${t} 项数据`,
    onChange,
    pageSizeOptions: [4, 20, 50, 100],
    showSizeChanger: !0,
    onShowSizeChange: onChange,
  };

  useEffect(() => {
    if (props.visible) {
      onRefresh();
    }
  }, [props.visible]);

  const res = {
    onDel,
    onEdit,
  };

  return (
    <Modal
      visible={props.visible}
      title={$t('drafts')}
      onCancel={onClose}
      maskClosable={false}
      width="1000px"
      footer={[]}
    >
      <Table
        columns={columns(res)}
        pagination={pagination}
        rowKey={record => record.id}
        dataSource={dataSource}
      />
    </Modal>
  );
};

export default DraftModal;
