import { request } from 'umi';
import type { RoleListParams, TagListItem, TagListParamsV2 } from './data';
import service from '@/services/http/service';

export async function queryRole(params: RoleListParams) {
  if (params.status != null) {
    params.status = Number(params.status)
  }
  return request('/api/sys/role/list', {
    method: 'POST',
    data: {
      ...params,
    },
  });
}

//查询用户的关糸
export async function queryAllTags(params: TagListParamsV2) {
  let result = await service.post('/api/v1/tag/list', {
    "page_no": params.current,
    "page_size": params.pageSize
  });

  return Promise.resolve({
    data: result.data.list,
    success: true,
  })
}

export async function queryMenuByRoleId(params: { id?: number }) {
  return request('/api/sys/role/queryMenuByRoleId', {
    method: 'POST',
    data: {
      ...params,
    },
  });
}

export async function updateRoleMenu(params: { roleId: number, menuIds: number[] }) {
  return request('/api/sys/role/updateRoleMenu', {
    method: 'POST',
    data: {
      ...params,
    },
  });
}

export async function removeRoleOne(params: { id: number }) {
  return request('/api/sys/role/delete', {
    method: 'POST',
    data: {
      ...params,
    },
  });
}

export async function removeTag(params: { ids: number[] }) {
  let result = await service.post('/api/v1/tag/delete', {
    "ids": params.ids,
  });

  return Promise.resolve({
    data: result.data,
    success: true,
  })
}

function addHashIfNeeded(str: string): string {
  if (str.charAt(0) !== '#') {
    return '#' + str;
  }
  return str;
}

export async function addTag(params: TagListItem) {
  let result = await service.post('/api/v1/tag/add', {
    "name": addHashIfNeeded(params.name),
    "name_cn": addHashIfNeeded(params.name_cn),
    // "remark": params.remark,
  });

  return Promise.resolve({
    data: result.data.roles,
    success: true,
  })
}

export async function updateTag(params: TagListItem) {

  let result = await service.post('/api/v1/tag/edit', {
    "id": params.id,
    "name": addHashIfNeeded(params.name),
    "name_cn": addHashIfNeeded(params.name_cn),
  });

  return Promise.resolve({
    data: result.data,
    success: true,
  })

}
