import qs from 'query-string';
import request from '../utils/request';
import { RoleFields } from './RoleController';
import { Result, ResultList, _Pager_Params, _TimeRange_Params } from './types';

export type UserFields = {
  userId: string;
  deptId: string;
  userName: string;
  nickName: string;
  email: string;
  phonenumber: string;
  sex: string;
  status: string;
  createTime: string;
  remark: string;
  password: string;
  appId: string;
  appName: string;
  medicalWorkersId: string;
  medicalWorkersName: string;
  lock: string; // 1 未锁定 2 锁定
  userType: string; // 1 内部 2 外部
  roles?: RoleFields[];
};

// 用户列表
interface GetList_Params extends _Pager_Params, _TimeRange_Params {
  userName: string;
  phonenumber: string;
  status: string;
}
type UserListResult = ResultList<UserFields[]>;
export async function getListApi(params: Partial<GetList_Params>) {
  return request<Partial<UserListResult>>({
    url: '/user/list?' + qs.stringify(params),
    method: 'get',
  });
}
// 用户详情
interface DetailsResult extends Result<UserFields> {
  roleIds: RoleFields['roleId'][];
  roles: RoleFields[];
  posts: any[];
  postIds: string[];
}
export async function getDetailsApi(userId?: UserFields['userId']) {
  return request<Partial<DetailsResult>>({
    url: `/user/${userId || ''}`,
    method: 'get',
  });
}
// 新增
type _Add_Params = Partial<Omit<UserFields, 'userId'>> & {
  roleIds: UserFields['userId'][];
};
export async function addApi(data: _Add_Params) {
  return request({
    url: '/user',
    method: 'post',
    data,
  });
}
// 编辑
type _Update_params = Partial<UserFields> & {
  roleIds: UserFields['userId'][];
};
export async function updateApi(data: _Update_params) {
  return request({
    url: '/user/edit',
    method: 'post',
    data,
  });
}
// 删除用户
export async function delApi(userId: UserFields['userId']) {
  return request({
    url: '/user/delete/' + userId,
    method: 'get',
  });
}
// 重置密码
interface _ResetPassword_Params {
  userId: UserFields['userId'];
  password: string;
}
export async function resetPasswordApi(data: _ResetPassword_Params) {
  return request({
    url: '/user/resetPwd',
    method: 'post',
    data,
  });
}

// 分配角色
interface _AuthRole_Params {
  userId: UserFields['userId'];
  roleIds: string;
}
export async function authRoleApi(params: _AuthRole_Params) {
  return request({
    url: '/user/authRole',
    method: 'get',
    params,
  });
}
// 切换状态
interface _ChangeStatus_Params {
  userId: UserFields['userId'];
  status: string;
}
export async function changeStatusApi(data: _ChangeStatus_Params) {
  return request({
    url: '/user/changeStatus',
    method: 'post',
    data,
  });
}

// 解锁
export async function unlockApi(userIds: UserFields['userId'][]) {
  const userIdsString = userIds.join(',');
  return request({
    url: `/user/unlock/${userIdsString}`,
    method: 'get',
  });
}
