import { PlusOutlined } from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Button, Modal, Space, Switch, Tag } from 'antd';
import React, { useRef } from 'react';
import Truly from '../../components/Truly';
import { OPTIONS } from '../../constants';
import { RoleController } from '../../services';
import { isFalse, isTrue } from '../../utils/auth';
import EditForm from './EditForm';

const User: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const onDelete = (record: RoleController.RoleFields) => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认删除角色名称为"${record.roleName}"的数据项？`,
      maskClosable: true,
      onOk: async () => {
        await RoleController.delApi(record.roleId);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const columns: ProColumns<RoleController.RoleFields>[] = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      width: 240,
      ellipsis: true,
    },
    {
      title: '角色类别',
      dataIndex: 'roleType',
      valueType: 'select',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
      fieldProps: {
        options: OPTIONS.OPTIONS_ROLE,
      },
    },
    {
      title: '权限字符',
      dataIndex: 'roleKey',
      width: 240,
      ellipsis: true,
    },
    {
      title: '显示顺序',
      dataIndex: 'roleSort',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_AVAILABLE,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
      render: (_, record) => {
        if (isTrue('administration:role:status:change')) {
          return (
            <Switch
              size="small"
              checked={Boolean(2 - Number(record.status))}
              onChange={async () => {
                const { roleId, status: preStatus } = record;
                const status = preStatus === '1' ? '2' : '1';
                await RoleController.changeStatusApi({ roleId, status });
                actionRef.current?.reload();
              }}
            />
          );
        } else if (record.status === '1') {
          return <Tag color="blue">启用</Tag>;
        }
        return <Tag color="red">停用</Tag>;
      },
    },
    {
      title: '创建时间',
      key: 'showTime',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'params[beginTime]': value[0],
            'params[endTime]': value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      hideInTable: isFalse(
        'administration:role:edit',
        'administration:role:delete',
      ),
      fixed: 'right',
      render: (_, record) => (
        <Truly truly={true}>
          <Space>
            <Truly truly={isTrue('administration:role:edit')}>
              <EditForm
                type="update"
                title="编辑角色"
                value={record}
                trigger={<a>编辑</a>}
                onSubmit={() => {
                  actionRef.current?.reload();
                }}
              ></EditForm>
            </Truly>
            <Truly truly={isTrue('administration:role:delete')}>
              <a onClick={() => onDelete(record)} style={{ color: '#FF4D4F' }}>
                删除
              </a>
            </Truly>
          </Space>
        </Truly>
      ),
    },
  ];

  return (
    <ProTable<RoleController.RoleFields>
      rowKey={'roleId'}
      actionRef={actionRef}
      search={{ span: 6 }}
      toolBarRender={() => [
        <Truly key="add" truly={isTrue('administration:role:add')}>
          <EditForm
            type="add"
            title="新增角色"
            trigger={
              <Button type="primary" icon={<PlusOutlined />}>
                新增
              </Button>
            }
            onSubmit={() => {
              actionRef.current?.reload();
            }}
          ></EditForm>
        </Truly>,
      ]}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        hideOnSinglePage: true,
      }}
      scroll={{ x: 0 }}
      request={async (params) => {
        const { current: pageNum, ...rest } = params;
        const { total = 0, data = [] } = await RoleController.getListApi({
          ...rest,
          pageNum,
        });
        return {
          data,
          total,
        };
      }}
    />
  );
};

export default User;
