import {
  AccountParams,
  OrganizationListItem,
  MenuParams,
  RoleParams,
  RolePageParams,
  MenuListGetResultModel,
  OrganizationListGetResultModel,
  AccountListGetResultModel,
  RolePageListGetResultModel,
  RoleListGetResultModel,
  RoleReqDTO,
  AccountListItem,
  AccountListModel,
  RoleOrOrganizationParam,
  ChangeAccountParams,
  RoleListItem,
} from './model/systemModel';
import { USER_INFO_KEY } from '/@/enums/cacheEnum';
import { session } from '/@/utils/Memory';
import { getAuthCache } from '/@/utils/auth';
import { defHttp } from '/@/utils/http/axios';

enum Api {
  // AccountList = '/user/page',
  AccountList = '/user-center/user/getUserArr',//获取用户列表
  IsAccountExist = '/user/account_exist/',
  IsPhoneExist = '/user/get_user/',
  DeptList = '/dept/all',
  setRoleStatus = '/role/update_status/',
  MenuList = '/system/getMenuList',
  RolePageList = '/role',
  TenantRolePageList = '/role/tenant',
  SaveOrUpdateRoleInfoWithMenu = '/user-center/role/editGroup',
  DeleteRole = '/user-center/role/delteGroup',
  GetAllRoleList = '/role/find/list',
  // BaseUserUrl = '/user',
  BaseUserUrl = '/user-center/user/EditUser',
  BaseOrganization = '/organization',
  SelectGroupList = "/user-center/role/selectGroupList",
  DeleteUser = '/user-center/user/DeleteUser',
  GetUserInfoByLoginCode = '/user-center/user/getUserInfoByLoginCode'
}

export const getAccountInfo = (userId: string) =>
  defHttp.get<AccountListModel>({ url: Api.BaseUserUrl + '/' + userId });

export const getAccountList = (params: AccountParams) => {
  var data = {
    keyStr: params.keyStr,
    page: params.page,
    rows: params.pageSize,
  }
  return new Promise<void>((resolve, reject) => {
    defHttp.post<AccountListGetResultModel>({ url: Api.AccountList, data }).then((res) => {
      res.datas.records.map(i => i.id = i.EMPLOYEE_ID);
      resolve({
        total: res.datas.total,
        items: res.datas.records,
      })
    })
  })
}

export const getUserInfoByLoginCode = (keyWord) => {
  var params = {
    keyWord: keyWord,
    depId: null
  }
  const formData = new FormData();
  Object.keys(params).forEach((key) => formData.append(key, params[key]))
  return new Promise<void>((resolve, reject) => {
    defHttp.post<RolePageListGetResultModel>({
      url: Api.GetUserInfoByLoginCode, params: formData
    }).then(r => {
      if (r.resp_code == 0 && r.datas.length) {
        resolve(r.datas[0])
      } else {
        resolve(false)
      }
    })
  })
}


export const alterUnlock = (userId: string) =>
  defHttp.post<AccountListGetResultModel>({ url: `/user/` + userId + `/unlock` });
/**
 * 获取组织列表
 * @param params 请求参数
 */
export const getOrganizationList = (params?: OrganizationListItem) =>
  defHttp.get<OrganizationListGetResultModel>({
    url: Api.BaseOrganization + '/me/list',
    params,
  });

/**
 * 更新或者保存组织
 * @param params
 * @param isUpdate
 */
export const saveOrUpdateOrganization = (params?: OrganizationListItem, isUpdate?: boolean) => {
  if (isUpdate) {
    return defHttp.put<OrganizationListGetResultModel>({ url: Api.BaseOrganization, params });
  } else {
    return defHttp.post<OrganizationListGetResultModel>({ url: Api.BaseOrganization, params });
  }
};

/**
 * 删除组织
 * @param ids 删除的ID
 */
export const delOrganization = (ids: string[]) =>
  defHttp.delete({
    url: Api.BaseOrganization,
    data: {
      ids,
    },
  });

export const getMenuList = (params?: MenuParams) =>
  defHttp.get<MenuListGetResultModel>({ url: Api.MenuList, params });

export const getRoleListByPage = (params?: RolePageParams) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.SelectGroupList }).then((res) => {
      console.log(res.datas)
      resolve(res.datas)
    })
  })
}

export const getTenantRoleRoleListByPage = (params?: RolePageParams) =>
  defHttp.get<RolePageListGetResultModel>({ url: Api.TenantRolePageList, params });

export const getTenantRoleListByPage = (params?: RolePageParams) =>
  defHttp.get<RolePageListGetResultModel>({ url: Api.RolePageList, params });

export const getAllRoleList = async (params?: RoleParams) => {
  // return defHttp.post<RoleListGetResultModel>({ url: Api.GetAllRoleList, params });
};

// 过滤角色列表----根据登录的账号所属的角色-过滤掉其他平台类型的角色
export const filterRoleList = async () => {
  const res = await defHttp.post<RoleListGetResultModel>({ url: Api.GetAllRoleList });
  const userInfo: any = getAuthCache(USER_INFO_KEY);
  const role = userInfo.roles[0];
  const options = res.filter((item) => {
    if (role === 'SYS_ADMIN' || role === 'PLATFORM_ADMIN') {
      return item.roleType === 'PLATFORM_ADMIN';
    } else {
      return item.roleType === 'CUSTOMER_USER';
    }
  });
  return Promise.resolve<RoleListItem[]>(options);
};


export const setRoleStatus = (id: number, status: number) => {
  return defHttp.put({ url: Api.setRoleStatus + id + '/' + status });
};
export const saveOrUpdateRoleInfoWithMenu = (params) => {
  params.parentGid = session.getItem("adminRole")?.groupid || 'CEEFEC51A38740DBA3657F91C230784B';
  const formData = new FormData();
  Object.keys(params).forEach((key) => formData.append(key, params[key]));
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.SaveOrUpdateRoleInfoWithMenu, params: formData }).then((res) => {
      resolve(res.datas)
    })
  })
};

export const isAccountExist = (account: string) => {
  return defHttp.get({ url: Api.IsAccountExist + account }, { errorMessageMode: 'none' });
};

export const IsPhoneExist = (phoneNumber: string) => {
  return defHttp.get({
    url: Api.IsPhoneExist + phoneNumber,
  });
};

export const delRole = (id) => {
  const formData = new FormData();
  formData.append("groupid", id)
  return defHttp.post({ url: Api.DeleteRole, params: formData });
};

/**
 * 更新或添加用户信息
 * @param params
 * @param isUpdate
 * @constructor
 */
export const SaveOrUpdateUserInfo = (params) => {
  const formData = new FormData();
  Object.keys(params).forEach((key) => formData.append(key, params[key]))
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.BaseUserUrl, params: formData }).then((res) => resolve(res))
  })
}
/**
 * 删除User
 * @param ids 删除id数组
 */
export const deleteUser = (id) => {
  const formData = new FormData();
  formData.append("userid", id)
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.DeleteUser, params: formData }).then((res) => resolve(res.datas))
  })
}

/**
 * 查询当前用户的关系
 * @param params
 */

export const findCurrentUserRelation = (params: RoleOrOrganizationParam) =>
  defHttp.post<Array<string>>({
    url: Api.BaseUserUrl + '/relation',
    params: params,
  });

/**
 * 修改密码
 * @param params
 */
export const resetPassword = (params: ChangeAccountParams) =>
  defHttp.post({
    url: Api.BaseUserUrl + '/reset',
    params: params,
  });
