import React, { useState, useEffect } from 'react';
import { Table, Card, message, Button, Popconfirm, Form, Input, Row, Col, Select } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { history } from 'umi';
import { PaginationProps } from 'antd/lib/pagination';
import { queryRule, removeRule, updateRule } from './service';
import './index.less';
import { TableListItem } from './data';
import { queryAllCategory } from '../Category/service';
import { queryAllLevel } from '../level/service';

const { Option } = Select;

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');

  if (!fields.id) {
    // eslint-disable-next-line no-param-reassign
    delete fields.id;
    try {
      const msg = await updateRule({ ...fields });
      hide();
      if (msg.retcode) {
        message.success('添加成功');
        return true;
      }
      message.error('添加失败请重试！');
      return false;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  } else {
    try {
      const msg = await updateRule({ ...fields });
      hide();
      if (msg.retcode) {
        message.success('保存成功');
        return true;
      }
      message.error('保存失败请重试！');
      return false;
    } catch (error) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }
};

/**
 * 删除节点
 * @param id
 */
const handleRemove = async (id?: number) => {
  const hide = message.loading('正在删除');
  if (!id) return false;

  try {
    const msg = await removeRule({
      ids: [id],
    });
    hide();
    if (msg.retcode) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败，请重试');
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 *
 * @param id
 * @returns
 */
const handleRemoveIds = async (ids: any) => {
  const hide = message.loading('正在删除');
  if (!ids || ids.length < 1) {
    message.warning('请选择删除项');
    return false;
  }

  try {
    const msg = await removeRule({
      ids,
    });
    hide();
    if (msg.retcode) {
      message.success('删除成功，即将刷新');
    } else {
      message.error('删除失败，请重试');
    }
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

// eslint-disable-next-line consistent-return
const getCategoryList = async () => {
  const msg = await queryAllCategory();
  if (msg.retcode) {
    return msg.data || [];
  } else {
    return []
  }
};

// eslint-disable-next-line consistent-return
const getLevelList = async () => {
  const msg = await queryAllLevel();
  if (msg.retcode) {
    return msg.data || [];
  } else {
    return []
  }
};

const handleTableChange = async (params: any, value: any) => {
  const param = {
    ...value,
    pageSize: params.pageSize,
    pageNum: params.current,
  };
  // eslint-disable-next-line no-restricted-syntax
  for (const key in param) {
    if (!param[key]) {
      // eslint-disable-next-line no-delete-var
      delete param[key];
    }
  }
  const msg = await queryRule(param);
  return {
    data: msg.data?.list,
    total: msg.data.total,
    success: msg.retcode,
  };
};

const UserList: React.FC<{}> = () => {
  const [data, handleDataChange] = useState<TableListItem[]>([]);
  const [loading, handleLoadChange] = useState<boolean>(false);
  const [page, handlePageChange] = useState<PaginationProps>({
    showQuickJumper: true,
    total: 0,
    pageSize: 10,
    current: 1,
    pageSizeOptions: ['10'],
    showTotal: (total: number) => {
      return `共 ${total} 条`;
    },
  });
  const [form] = Form.useForm();
  const [catecoryList1, setList1Vals] = useState<any[]>([]);
  const [catecoryList2, setList2Vals] = useState<any[]>([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [formVals, setSearchValues] = useState({
    title: '',
    version: '',
    keywords: '',
    categoryId: null,
    currentStatus: null,
    levelId: null,
  });
  const handleChange = async (pagination: any, value: any) => {
    handleLoadChange(true);
    const res = await handleTableChange(pagination, value);
    handleLoadChange(false);
    handleDataChange(res.data);
    handlePageChange({
      showQuickJumper: true,
      total: res.total,
      pageSize: pagination.pageSize,
      current: pagination.current,
      pageSizeOptions: ['10'],
      showTotal: (total: number) => {
        return `共 ${total} 条`;
      },
    });
  };

  const onSelectChange = (rowKeys: any) => {
    setSelectedRowKeys(rowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const onFinish = (value: any) => {
    setSearchValues(value);
    handleChange(page, value);
  };

  const getCatecoryList = async () => {
    const arr1 = await getCategoryList();
    setList1Vals(arr1);
    const arr2 = await getLevelList();
    setList2Vals(arr2);
  };

  const columns: ColumnsType<TableListItem> = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
      width: 400,
    },
    {
      title: '文号版本',
      dataIndex: 'version',
      key: 'version',
    },
    {
      title: '类型',
      dataIndex: 'categoryName',
      key: 'categoryName',
    },
    {
      title: '关键字',
      dataIndex: 'keywords',
      key: 'keywords',
      width: 400,
    },
    {
      title: '状态',
      dataIndex: 'state',
      key: 'state',
      render: (text: number) => (text === 1 ? '启用' : '禁用'),
    },
    {
      title: '级别',
      dataIndex: 'levelName',
      key: 'levelName',
    },
    {
      title: '现行状态',
      dataIndex: 'currentStatus',
      key: 'currentStatus',
      render: (text: number) => (text === 1 ? '现行' : '废止'),
    },
    {
      title: '实施日期',
      dataIndex: 'implementationDate',
      render: (text: string) => text ? text.substring(0,10) : ''
    },
    {
      title: '操作',
      key: 'action',
      width: '120px',
      fixed: 'right',
      render: (text, record) => (
        <span>
          <a
            style={{ marginRight: 8 }}
            onClick={() => {
              history.push(`/article/article-page/update/${record.id}`);
            }}
          >
            编辑
          </a>
          <Popconfirm
            title={record.state === 1 ? '确定禁用该标准?' : '确定启用该标准?'}
            onConfirm={async () => {
              const state = record.state === 1 ? 2 : 1;
              const success = await handleUpdate({
                ...record,
                state
              });
              if (success) handleChange(page, formVals);
            }}
          >
            <a style={{ marginRight: 8 }}>{record.state === 1 ? '禁用' : '启用'}</a>
          </Popconfirm>
          <Popconfirm
            title="确定删除该标准?"
            onConfirm={async () => {
              const success = await handleRemove(record.id);
              if (success) handleChange(page, formVals);
            }}
          >
            <a style={{ color: 'red' }}>删除</a>
          </Popconfirm>
        </span>
      ),
    },
  ];
  useEffect(() => {
    async function fetchData() {
      getCatecoryList();
      handleLoadChange(true);
      const res = await handleTableChange(page, formVals);
      handleLoadChange(false);
      page.total = res.total;
      handleDataChange(res.data);
    }
    fetchData();
  }, []);
  return (
    <PageHeaderWrapper>
      <Card bordered={false}>
        <div id="components-table-demo-basic">
          <Row justify="space-between">
            <Col span={18}>
              <Form layout="inline" form={form} initialValues={formVals} onFinish={onFinish}>
                <Form.Item name="title" style={{ marginBottom: 10, textAlign: 'left' }}>
                  <Input placeholder="请输入名称" />
                </Form.Item>
                <Form.Item name="version" style={{ marginBottom: 10, textAlign: 'left' }}>
                  <Input placeholder="请输入版本" />
                </Form.Item>
                <Form.Item name="keywords" style={{ marginBottom: 10, textAlign: 'left' }}>
                  <Input placeholder="请输入关键字" />
                </Form.Item>
                <Form.Item name="categoryId" style={{ marginBottom: 10, width: 100 }}>
                  <Select allowClear style={{ width: '100%' }} placeholder="类型">
                    {catecoryList1.map((item: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.categoryName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item name="currentStatus" style={{ marginBottom: 10 }}>
                  <Select allowClear style={{ width: '100%' }} placeholder="现行状态">
                    <Option key={1} value={1}>
                      现行
                    </Option>
                    <Option key={2} value={2}>
                      废止
                    </Option>
                  </Select>
                </Form.Item>
                <Form.Item name="levelId" style={{ marginBottom: 10, width: 100 }}>
                  <Select allowClear style={{ width: '100%' }} placeholder="级别">
                    {catecoryList2.map((item: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.levelName}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
                <Form.Item shouldUpdate>
                  {() => (
                    <Button type="primary" htmlType="submit">
                      搜索
                    </Button>
                  )}
                </Form.Item>
              </Form>
            </Col>
            <Col span={6}>
              <div style={{ textAlign: 'right' }}>
                <Button
                  style={{ marginBottom: 15, marginRight: 10 }}
                  type="primary"
                  onClick={() => {
                    history.push('/article/article-page/update');
                  }}
                >
                  新增
                </Button>
                <Popconfirm
                  title="确定删除所选标准?"
                  onConfirm={async () => {
                    const success = await handleRemoveIds(selectedRowKeys);
                    if (success) handleChange(page, formVals);
                  }}
                >
                  <Button style={{ marginBottom: 15 }} type="primary">
                    批量删除
                  </Button>
                </Popconfirm>
              </div>
            </Col>
          </Row>
          <Table
            columns={columns}
            rowKey="id"
            size="small"
            rowSelection={rowSelection}
            dataSource={data}
            pagination={page}
            loading={loading}
            onChange={async (pagination) => {
              handleChange(pagination, formVals);
            }}
          />
        </div>
      </Card>
    </PageHeaderWrapper>
  );
};

export default UserList;
