import {PlusOutlined} from '@ant-design/icons';
import {Button, Divider, message, Modal, Radio} 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';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    await service.addModel({...fields});
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: TableListItem) => {
  const hide = message.loading('正在配置');
  try {
    await service.updateModel(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    message.error('配置失败请重试！');
    return false;
  }

};

/**
 *  删除节点
 * @param fields
 */
const handleRemove = async (fields: TableListItem) => {
  const hide = message.loading('正在删除');
  try {
    await service.removeModel(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({});
  const actionRef = useRef<ActionType>();
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '模型类型',
      dataIndex: 'modelType',
      hideInSearch: true,
      rules: [
        {
          required: true,
          message: '模型类型为必填项',
        },
      ],
      renderFormItem: () => {
        return (
          <Radio.Group>
            <Radio value={0}>albert</Radio>
            <Radio value={1}>Blstm</Radio>
          </Radio.Group>
        );
      },
      valueEnum: {
        0: {text: 'albert'},
        1: {text: 'Blstm'}
      },
    },
    {
      title: '模型名称',
      dataIndex: 'modelName',
      rules: [
        {
          required: true,
          message: '模型名称为必填项',
        },
      ],
    },
    {
      title: '模型文件',
      dataIndex: 'modelFile',
      hideInSearch: true,
      rules: [
        {
          required: true,
          message: '模型名称为必填项',
        },
      ],
    },
    {
      title: '词向量文件',
      dataIndex: 'vocabFile',
      hideInSearch: true,
      rules: [
        {
          required: true,
          message: '词向量文件为必填项',
        },
      ],
    },
    {
      title: '标签文件',
      dataIndex: 'labelFile',
      hideInSearch: true,
      rules: [
        {
          required: true,
          message: '标签文件为必填项',
        },
      ],
    },
    {
      title: '必包含',
      dataIndex: 'mustTag',
      hideInSearch: true,
    },
    {
      title: '必不包含',
      dataIndex: 'mustTag',
      hideInSearch: true,
    },
    {
      title: '纯文本',
      dataIndex: 'onlyWord',
      hideInSearch: true,
      renderFormItem: () => {
        return (
          <Radio.Group>
            <Radio value="true">是</Radio>
            <Radio value="false">否</Radio>
          </Radio.Group>
        );
      },
      valueEnum: {
        "true": {text: '是'},
        "false": {text: '否'}
      },
    },

    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setModalVisible(true);
              setFormValues(record);
              console.log(record)
            }}
          >
            配置
          </a>
          <Divider type="vertical"/>
          <a
            onClick={() => {
              handleRemove(record);
              console.log(record)
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  const [searchForm,setSearchForm] = useState({});

  return (
    <PageHeaderWrapper>
      <ProTable<TableListItem>
        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,
        }}
        /* eslint-disable */
        toolBarRender={(action, {selectedRows}) => [
          <Button type="primary" onClick={() => {
            setModalVisible(true);
            setFormValues({});
          }}>
            <PlusOutlined/> 新建
          </Button>
        ]}
        request={(params) => service.queryModel(params)}
        columns={columns}
        rowSelection={{}}
      />
      <Modal
        destroyOnClose
        title={"id" in formValues ? "编辑" : "新建"}
        visible={modelVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
      >
        <ProTable<TableListItem, TableListItem>
          onSubmit={async (value) => {
            let success = false;
            if (value.id) {
              success = await handleAdd(value);
            } else {
              success = await handleUpdate(value);
            }

            if (success) {
              setModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="key"
          type="form"
          columns={columns}
          rowSelection={{}}
          form={{initialValues: formValues}}
        />
      </Modal>

    </PageHeaderWrapper>
  );
};

export default TableList;
