import {deleteUser, resetUserPassword} from '@apis';
import {LDColumnsType, LDTableButton, modifyDataColumns} from '@components';
import {useTableDeleteEvent, useTableModalEvent} from '@hooks';
import {UserListData} from '@models';
import {useMutation} from '@tanstack/react-query';
import {TABLE_CELL_WIDTH} from '@utils';
import {App} from 'antd';

const tableColumns: LDColumnsType<UserListData>[] = [
  {title: '用户名称', dataIndex: 'userName', width: TABLE_CELL_WIDTH.normal},
  {title: '真实姓名', dataIndex: 'realName', width: TABLE_CELL_WIDTH.normal},
  {title: '角色名称', dataIndex: 'role', width: TABLE_CELL_WIDTH.normal},
  {title: '邮箱', dataIndex: 'email', width: TABLE_CELL_WIDTH.middle},
  {title: '手机号', dataIndex: 'phone', width: TABLE_CELL_WIDTH.normal},
  ...modifyDataColumns,
];

export function useResetPassword() {
  const {message, modal} = App.useApp();

  const {isLoading, mutate} = useMutation({
    mutationFn: resetUserPassword,
    onSuccess({msg}) {
      msg === '200' && message.success('密码重置成功');
    },
  });

  function onClick(name: string, id: string) {
    return function() {
      modal.confirm({
        title: '重置密码',
        content: `你确定要将${name}的密码重置为123456吗？`,
        onOk() {
          mutate(id);
        },
      });
    };
  }

  return [isLoading, onClick] as const;
}

export function useColumns(refetch: () => void) {
  const [deleteId, onDelete] = useTableDeleteEvent(
    deleteUser,
    refetch,
    {label: '用户信息'},
  );
  const [{editId, visible}, {onAdd, onEdit, onClose}] = useTableModalEvent();
  const [isResting, onResetPassword] = useResetPassword();
  const [
    {editId: authId, visible: authVisible},
    {onEdit: onAuthEdit, onClose: onAuthColose},
  ] = useTableModalEvent();

  const columns: LDColumnsType<UserListData>[] = [
    ...tableColumns,
    {
      title: '操作',
      dataIndex: 'id',
      fixed: true,
      width: TABLE_CELL_WIDTH.great,
      render({id, realName}) {
        const loading = String(id) === deleteId;

        return (
          <>
            <LDTableButton
              disabled={loading}
              onClick={onEdit(String(id))}
            >
              修改
            </LDTableButton>
            <LDTableButton
              disabled={loading}
              loading={isResting}
              onClick={onResetPassword(realName, String(id))}
            >
              重置密码
            </LDTableButton>
            <LDTableButton
              disabled={loading}
              onClick={onAuthEdit(String(id))}
            >
              菜单权限
            </LDTableButton>
            <LDTableButton
              loading={loading}
              danger
              onClick={onDelete(String(id), realName)}
            >
              删除
            </LDTableButton>
          </>
        );
      },
    },
  ];

  return [
    {editId, visible, columns, authId, authVisible},
    {onAdd, onClose, onAuthColose},
  ] as const;
}
