import { create } from 'zustand';
import { query } from '@/modules';
import { toast } from 'react-toastify';
import { Result } from '@kevisual/query/query';
type AdminStore = {
  /**
   * 创建新用户
   * @returns
   */
  createNewUser: (data: any) => Promise<void>;
  /**
   * 删除用户
   * @param id
   */
  deleteUser: (id: string) => Promise<void>;
  /**
   * 更新用户
   * @param id
   * @param data
   */
  updateUser: (id: string, data: any) => Promise<void>;

  /**
   * 重置密码
   * @param id
   */
  resetPassword: (id: string, password?: string) => Promise<void>;

  /**
   * 修改用户名
   * @param id
   * @param name
   */
  changeName: (id: string, name: string) => Promise<Result<any>>;

  /**
   * 检查用户是否存在
   * @param name
   * @returns
   */
  checkUserExist: (name: string) => Promise<boolean | null>;
};

export const useAdminStore = create<AdminStore>((set) => ({
  createNewUser: async (data: any) => {
    const res = await query.post({
      path: 'user',
      key: 'createNewUser',
      data,
    });
    if (res.code === 200) {
      toast.success('创建用户成功');
    } else {
      toast.error(res.message || '创建用户失败');
    }
  },
  deleteUser: async (id: string) => {
    const res = await query.post({
      path: 'user',
      key: 'deleteUser',
      data: {
        id,
      },
    });
    if (res.code === 200) {
      toast.success('删除用户成功');
    } else {
      toast.error(res.message || '删除用户失败');
    }
  },
  updateUser: async (id: string, data: any) => {
    console.log('updateUser', id, data);
  },
  resetPassword: async (id: string, password?: string) => {
    const res = await query.post({
      path: 'user',
      key: 'resetPassword',
      data: {
        id,
        password,
      },
    });
    if (res.code === 200) {
      if (res.data.password) {
        toast.success('new password is ' + res.data.password);
      } else {
        toast.success('重置密码成功');
      }
    } else {
      toast.error(res.message || '重置密码失败');
    }
  },
  changeName: async (id: string, name: string) => {
    const res = await query.post({
      path: 'user',
      key: 'changeName',
      data: {
        id,
        newName: name,
      },
    });
    if (res.code === 200) {
      toast.success('修改用户名成功');
    } else {
      toast.error(res.message || '修改用户名失败');
    }
    return res;
  },
  checkUserExist: async (name: string) => {
    const res = await query.post({
      path: 'user',
      key: 'checkUserExist',
      data: {
        username: name,
      },
    });
    if (res.code === 200) {
      const user = res.data || {};
      return !!user.id;
    } else {
      toast.error(res.message || '检查用户是否存在,请求失败');
    }
    return null;
  },
}));
