import {Divider, message, Modal} from 'antd';
import React, {useRef, useState} from 'react';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from '@ant-design/pro-table';
import {SorterResult} from 'antd/es/table/interface';
import {TableListItem} from './data.d';
import service from './service';
import UpdateForm from "@/pages/Memory/components/UpdateForm";
import {ExclamationCircleOutlined} from "@ant-design/icons/lib";
import MyQuill from "@/pages/Memory/components/MyQuill";
import styles from './index.less';

/**
 *  删除节点
 * @param fields
 */
const handleRemove = async (fields: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    await service.delete(fields);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


const TableList: React.FC<{}> = () => {
  const [sorter, setSorter] = useState<string>('');
  const [modelVisible, setModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<TableListItem>({
    back: "",
    front: "",
    id: 0,
    period: 0,
    remindTime: new Date(),
    tag: "",
    updateTime: "",
    userId: 0
  });

  const [showVisible, setShowVisible] = useState(false); // 是否查看

  const actionRef = useRef<ActionType>();

  const {confirm} = Modal;

  const deleteMemory = async (record: any) => {
    await handleRemove(record);
    if (actionRef.current) {
      actionRef.current.reload();
    }

  };

  const changeForm = async (record: any) => {
    setFormValues(record);
    setModalVisible(true);
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '正面',
      dataIndex: 'front',
      width: 250,
      // hideInSearch: true,
      render: (text, row) => {
        return (<div className={styles.listHeight}>
          <MyQuill theme="bubble" readonly onChange={() => {
          }} value={text}/>
        </div>);
      }
    },
    {
      title: '背面',
      dataIndex: 'back',
      width: 250,
      hideInSearch: true,
      render: (text, row) => {
        return (<div className={styles.listHeight}>
          <MyQuill theme="bubble" readonly onChange={() => {
          }} value={text}/>
        </div>);
      }
    },
    // {
    //   title: '间隔时间',
    //   dataIndex: 'period',
    //   width: 110,
    //   hideInSearch: true,
    //   hideInForm: true,
    //   render: (text, row) => {
    //     return (<>
    //       <span>{minuteToDay(row.period)}</span>
    //     </>);
    //   }
    // },
    {
      title: '提醒时间',
      dataIndex: 'remindTime',
      valueType: 'dateTime',
      // width: 150,
      hideInSearch: true,
      hideInForm: true,
      sorter: true
    },
    // {
    //   title: '更新时间',
    //   dataIndex: 'updateTime',
    //   valueType: 'dateTime',
    //   width: 150,
    //   hideInSearch: true,
    //   hideInForm: true,
    //   sorter: true
    // },
    {
      title: '操作',
      dataIndex: 'option',
      width: 200,
      valueType: 'option',
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      render: (_, record, index, action) => (
        <>
          <a
            onClick={(e) => {
              e.stopPropagation();
              setFormValues(record);
              setShowVisible(true);
            }}
          >
            查看
          </a>
          <Divider type="vertical"/>
          <a
            onClick={(e) => {
              e.stopPropagation();
              changeForm(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical"/>
          <a
            onClick={async () => {
              confirm({
                title: '确定删除吗?',
                icon: <ExclamationCircleOutlined/>,
                content: '删除后无法恢复',
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                  deleteMemory(record);
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageHeaderWrapper title={false}>
      <ProTable<TableListItem>
        search
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TableListItem>;
          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        pagination={{
          defaultPageSize: 10,
        }}
        params={{
          sorter,
        }}
        request={async (params = {}) => {
          const res = await service.queryList(params);
          return {
            data: res.data.list,
            page: params.current,
            success: true,
            total: res.data.total,
          };
        }}
        columns={columns}
        // rowSelection={{}}
        scroll={{x: 1000}}
      />
      {modelVisible ? (
        <UpdateForm
          onCancel={(refresh) => {
            setModalVisible(false);
            if (refresh && actionRef.current) {
              actionRef.current.reload();
            }
          }}
          modalVisible={modelVisible}
          values={formValues}/>
      ) : null}
      {showVisible ? (
        <Modal
          destroyOnClose
          width={640}
          bodyStyle={{padding: '15px 15px 15px'}}
          title="配置模型"
          visible={showVisible}
          onCancel={() => setShowVisible(false)}
          footer={null}
        >
          正面：
          <p/>
          <MyQuill theme="bubble" readonly onChange={() => {
          }} value={formValues.front}/>
          <p/>
          反面：
          <p/>
          <MyQuill theme="bubble" readonly onChange={() => {
          }} value={formValues.back}/>
        </Modal>
      ) : null}

    </PageHeaderWrapper>
  );
};

export default TableList;
