import {
  usercontrollerAdduser,
  usercontrollerListusers,
  usercontrollerToggleactive,
  usercontrollerUpdateuser,
} from '@/servers/api/user';
import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  DrawerForm,
  PageContainer,
  ProColumns,
  ProForm,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { App, Button, Tag } from 'antd';
import { useRef } from 'react';

const ListPage: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const { message } = App.useApp();
  const columns: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'username',
    },

    {
      title: '超管',
      dataIndex: 'isSuper',
      valueType: 'select',
      valueEnum: {
        true: { text: '是' },
        false: { text: '否' },
      },
    },
    {
      title: '激活',
      dataIndex: 'isActive',
      valueEnum: {
        true: {
          text: '是',
        },
        false: {
          text: '否',
        },
      },
      render: (_, record: any) => (
        <Tag color={record?.isActive ? 'green' : 'red'}>
          {record?.isActive ? '启用中' : '已禁用'}
        </Tag>
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => (
        <>
          <EditForm record={record} tableRef={actionRef} />
          <Button
            danger={record.isActive}
            type="link"
            onClick={async () => {
              // 软删除为禁用(isActive=false),再次点击可启用
              const next = !record.isActive;
              const { success, message: errMsg } =
                await usercontrollerToggleactive({
                  userId: record.id,
                  isActive: next,
                });
              if (!success) return message.error(errMsg);
              actionRef.current?.reload();
            }}
          >
            {record.isActive ? '禁用' : '启用'}
          </Button>
        </>
      ),
    },
  ];
  return (
    <PageContainer ghost>
      <ProTable
        headerTitle="查询表格"
        actionRef={actionRef}
        rowKey="id"
        request={async (params) => {
          const {
            current = 1,
            pageSize = 10,
            username,
            isActive,
            isSuper,
            remark,
          } = params as any;
          console.log(`params`, params);
          const qp: any = { current, pageSize };
          if (username) qp.username = username;
          if (typeof isActive !== 'undefined' && isActive !== '')
            qp.isActive = String(isActive);
          if (typeof isSuper !== 'undefined' && isSuper !== '')
            qp.isSuper = String(isSuper);
          if (remark) qp.remark = remark;
          const { data, success } = await usercontrollerListusers({
            params: qp,
          });
          return {
            total: data?.total || 0,
            data: data?.items || [],
            success,
          };
        }}
        columns={columns}
        toolBarRender={() => [<CreateForm tableRef={actionRef} />]}
      />
    </PageContainer>
  );
};

const CreateForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
}> = ({ tableRef }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm
      title="新建"
      trigger={
        <Button type="primary">
          <PlusOutlined />
          新建
        </Button>
      }
      autoFocusFirstInput
      drawerProps={{
        destroyOnHidden: true,
      }}
      onFinish={async (values) => {
        try {
          const { success, message: errMsg } = await usercontrollerAdduser(
            values,
          );
          if (!success) {
            throw new Error(errMsg);
          }
          tableRef.current?.reload();
          message.success('提交成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="username"
          label="用户名"
          width="lg"
          placeholder="请输入用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        />
        <ProFormText
          name="password"
          label="密码"
          width="lg"
          placeholder="请输入密码"
          rules={[{ required: true, message: '请输入密码' }]}
        />
        <ProFormSwitch name="isSuper" label="超管" />
        <ProFormSwitch name="isAdmin" label="管理员" />
        <ProFormTextArea
          name="remark"
          label="备注"
          placeholder="请输入备注"
          fieldProps={{ autoSize: { minRows: 2, maxRows: 4 } }}
        />
      </ProForm.Group>
    </DrawerForm>
  );
};

const EditForm: React.FC<{
  tableRef: React.MutableRefObject<ActionType | undefined>;
  record: any;
}> = ({ tableRef, record }) => {
  const { message } = App.useApp();
  return (
    <DrawerForm
      title="编辑"
      trigger={<Button type="link">编辑</Button>}
      initialValues={{
        username: record.username,
        isSuper: record.isSuper,
        isAdmin: record.isAdmin,
        remark: record.remark,
      }}
      onFinish={async (values: any) => {
        try {
          // 更新用户,密码可选填
          const { success, message: err } = await usercontrollerUpdateuser(
            { id: record.id },
            values,
          );
          if (!success) throw new Error(err);
          tableRef.current?.reload();
          message.success('更新成功');
          return true;
        } catch (error: any) {
          message.error(error.message);
          return false;
        }
      }}
    >
      <ProForm.Group>
        <ProFormText
          name="username"
          label="用户名"
          width="lg"
          placeholder="请输入用户名"
          rules={[{ required: true, message: '请输入用户名' }]}
        />
        <ProFormText
          name="password"
          label="密码(不填不改)"
          width="lg"
          placeholder="如需修改请输入新密码"
        />
        <ProFormSwitch name="isSuper" label="超管" />
        <ProFormSwitch name="isAdmin" label="管理员" />
        <ProFormTextArea
          name="remark"
          label="备注"
          placeholder="请输入备注"
          fieldProps={{ autoSize: { minRows: 2, maxRows: 4 } }}
        />
      </ProForm.Group>
    </DrawerForm>
  );
};

export default ListPage;
