import {
  DoubleRightOutlined,
  PlusOutlined,
  UnlockOutlined,
} from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { useRequest } from 'ahooks';
import {
  Button,
  Dropdown,
  MenuProps,
  Modal,
  Space,
  Switch,
  Tag,
  message,
} from 'antd';
import React, { useRef, useState } from 'react';
import Truly from '../../components/Truly';
import { OPTIONS } from '../../constants';
import { CommonController, UserController } from '../../services';
import { isFalse, isSomeTrue, isTrue } from '../../utils/auth';
import EditForm from './EditForm';
import PasswordForm from './Password';
import RoleForm from './RoleForm';

const User: React.FC<unknown> = () => {
  const { data: docList } = useRequest(CommonController.getDocSelectApi);
  const { data: roleList } = useRequest(CommonController.getRoleSelectApi);
  const [selectRows, setSelectRows] = useState<UserController.UserFields[]>([]);
  const actionRef = useRef<ActionType>();

  const onDelete = (record: UserController.UserFields) => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认删除用户名称为"${record.userName}"的数据项？`,
      maskClosable: true,
      onOk: async () => {
        await UserController.delApi(record.userId);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onBatchLock = () => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认执行批量解锁操作？`,
      maskClosable: true,
      onOk: async () => {
        const userIds = selectRows.map((item) => item.userId);
        await UserController.unlockApi(userIds);
        actionRef.current?.reload();
        message.success('操作成功！');
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onLock = (record: UserController.UserFields) => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认解锁用户名为"${record.userName}"操作？`,
      maskClosable: true,
      onOk: async () => {
        await UserController.unlockApi([record.userId]);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const getItems = (record: UserController.UserFields) => {
    const items: MenuProps['items'] = [];
    if (isTrue('administration:user:password:reset')) {
      items.push({
        key: 'resetPassword',
        label: (
          <PasswordForm
            title="重置密码"
            value={record}
            trigger={
              <Button type="link" style={{ padding: 4 }}>
                重置密码
              </Button>
            }
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></PasswordForm>
        ),
      });
    }
    if (isTrue('administration:user:role:bind')) {
      items.push({
        key: 'role',
        label: (
          <RoleForm
            title="分配角色"
            value={record}
            roleList={roleList || []}
            trigger={
              <Button type="link" style={{ padding: 4 }}>
                分配角色
              </Button>
            }
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></RoleForm>
        ),
      });
    }
    if (isTrue('administration:user:lock') && record.lock === '2') {
      items.push({
        key: 'lock',
        label: (
          <Button
            type="link"
            style={{ padding: 4 }}
            onClick={() => onLock(record)}
          >
            解锁
          </Button>
        ),
      });
    }
    return items;
  };

  const columns: ProColumns<UserController.UserFields>[] = [
    {
      title: '名称',
      dataIndex: 'userName',
      width: 240,
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '用户类别',
      dataIndex: 'userType',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_USER,
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      width: 240,
      ellipsis: true,
      hideInSearch: true,
    },
    {
      title: '手机号',
      width: 240,
      ellipsis: true,
      dataIndex: 'phonenumber',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_AVAILABLE,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      ellipsis: true,
      hideInSearch: true,
      render: (_, record) => {
        if (isTrue('administration:user:status:change')) {
          return (
            <Switch
              size="small"
              checked={Boolean(2 - Number(record.status))}
              onChange={async () => {
                const { userId, status: preStatus } = record;
                const status = preStatus === '1' ? '2' : '1';
                await UserController.changeStatusApi({ userId, status });
                actionRef.current?.reload();
              }}
            />
          );
        } else if (record.status === '1') {
          return <Tag color="blue">启用</Tag>;
        }
        return <Tag color="red">停用</Tag>;
      },
    },
    {
      title: '是否锁定',
      dataIndex: 'lock',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
      render: (text, record) => {
        if (record.lock === '2') {
          return <Tag color="red">是</Tag>;
        }
        return <Tag color="blue">否</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: 160,
      hideInTable: isFalse(
        'administration:user:edit',
        'administration:user:password:reset',
        'administration:user:role:bind',
        'administration:user:delete',
      ),
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Truly truly={isTrue('administration:user:edit')}>
            <EditForm
              key="update"
              type="update"
              title="编辑用户"
              value={record}
              docList={docList || []}
              roleList={roleList || []}
              trigger={<a>编辑</a>}
              onOk={() => {
                actionRef.current?.reload();
              }}
            ></EditForm>
          </Truly>
          <Truly truly={isTrue('administration:user:delete')}>
            <a onClick={() => onDelete(record)} style={{ color: '#FF4D4F' }}>
              删除
            </a>
          </Truly>
          <Truly
            truly={isSomeTrue(
              'administration:user:password:reset',
              'administration:user:role:bind',
              'administration:user:lock',
            )}
          >
            <Dropdown menu={{ items: getItems(record) }}>
              <a>
                更多 <DoubleRightOutlined />
              </a>
            </Dropdown>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<UserController.UserFields>
      rowKey={'userId'}
      actionRef={actionRef}
      search={{ span: 6 }}
      rowSelection={{
        fixed: true,
        onChange: (keys, rows) => setSelectRows(rows),
      }}
      tableAlertRender={false}
      toolBarRender={() => [
        <Truly key="add" truly={isTrue('administration:user:add')}>
          <EditForm
            type="add"
            title="新增用户"
            docList={docList || []}
            roleList={roleList || []}
            trigger={
              <Button type="primary" icon={<PlusOutlined />}>
                新增
              </Button>
            }
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></EditForm>
        </Truly>,
        <Truly key="lock" truly={isTrue('administration:user:lock')}>
          <Button
            type="primary"
            icon={<UnlockOutlined />}
            disabled={!selectRows.some((item) => item.lock === '2')}
            onClick={onBatchLock}
          >
            解锁
          </Button>
        </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 UserController.getListApi({
          ...rest,
          pageNum,
        });
        actionRef.current?.clearSelected?.();
        return {
          data,
          total,
        };
      }}
    />
  );
};

export default User;
