import React, { useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { Button, notification } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { connect } from 'umi';
import { ROLE_MANAGE } from '@/../config/permission.config';
import { deleteRole, getRoleList } from '../service';

// data
import { getColumns } from './data';

const Role = props => {
  const { permissions } = props;
  const actionRef = useRef();
  const formRef = useRef();
  const history = useHistory();

  // 权限控制
  const canEditable = permissions[ROLE_MANAGE.EDITABLE];

  const toRoleInfo = ({ id = null } = {}) => {
    const query = id ? { id } : {};
    history.push({
      pathname: '/systemManage/role/roleInfo',
      query,
    });
  };

  // 删除
  const onDeleteRole = async ({ id }) => {
    const res = await deleteRole({ id });
    if (res.code !== 2000) {
      notification.warning({
        message: res.detail,
      });
      return;
    }

    notification.success({
      message: $t('delete.success'),
    });
  };
  const columns = getColumns({
    onDeleteRole,
    toRoleInfo,
    canEditable,
  });

  // 表格属性
  const tableProps = {
    columns,
    rowKey: 'id',
    request: async params => {
      console.log($t('search'), params);
      const { current: page, pageSize: size } = params;
      const res = await getRoleList({ page, size, ...params });
      const { content, totalElements } = res.data;
      return {
        success: true,
        data: content,
        total: totalElements,
      };
    },
    toolBarRender: () => [
      canEditable ? (
        <Button type="primary" onClick={() => toRoleInfo()}>{$t('add.role')}</Button>
      ) : (
        <></>
      ),
    ],
  };
  // 搜索属性
  const searchProps = {
    collapsed: false,
    collapseRender: () => null,
  };

  return (
    <PageHeaderWrapper>
      <ProTable actionRef={actionRef} formRef={formRef} {...tableProps} search={false}></ProTable>
    </PageHeaderWrapper>
  );
};

export default connect(({ menu }) => ({
  permissions: menu.permissions,
}))(Role);
