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: '确认提示',
      content: '操作后不可更改，确认是否删除？',
      onOk: async () => {
        console.log('record :>> ', record);
        await apiDeleteDraft(record.id);
        message.success('删除成功！');
        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="草稿箱"
      onCancel={onClose}
      maskClosable={false}
      width="1000px"
      footer={[]}
    >
      <Table
        columns={columns(res)}
        pagination={pagination}
        rowKey={record => record.id}
        dataSource={dataSource}
      />
    </Modal>
  );
};

export default DraftModal;
