import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { Equipment, EquipmentParam } from './model';
/**
 * 分页查询设备
 */
export async function pageEquipment(params: EquipmentParam) {
  const res = await request.get<ApiResult<PageResult<Equipment>>>(
    '/apps/equipment/page',
    {
      params
    }
  );
  if (res.data.code === 0) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 查询设备列表
 */
export async function listEquipment(params?: EquipmentParam) {
  const res = await request.get<ApiResult<Equipment[]>>('/apps/equipment', {
    params
  });
  if (res.data.code === 0 && res.data.data) {
    return res.data.data;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 添加设备
 */
export async function addEquipment(data: Equipment) {
  const merchantCode = localStorage.getItem('merchantCode');
  console.log(merchantCode);
  if (merchantCode !== null && merchantCode != '') {
    console.log(merchantCode);
    data.merchantCode = String(merchantCode);
  }
  const res = await request.post<ApiResult<unknown>>('/apps/equipment', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 修改设备
 */
export async function updateEquipment(data: Equipment) {
  const res = await request.put<ApiResult<unknown>>('/apps/equipment', data);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 绑定设备
 */
export async function bindEquipment(data: Equipment) {
  const res = await request.put<ApiResult<unknown>>(
    '/apps/equipment/bind',
    data
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 删除设备
 */
export async function removeEquipment(id?: number) {
  const res = await request.delete<ApiResult<unknown>>('/apps/equipment/' + id);
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 批量删除设备
 */
export async function removeBatchEquipment(data: (number | undefined)[]) {
  const res = await request.delete<ApiResult<unknown>>(
    '/apps/equipment/batch',
    {
      data
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}

/**
 * 检查IP是否存在
 */
export async function checkExistence(
  field: string,
  value: string,
  id?: number
) {
  const res = await request.get<ApiResult<unknown>>(
    '/apps/equipment/existence',
    {
      params: { field, value, id }
    }
  );
  if (res.data.code === 0) {
    return res.data.message;
  }
  return Promise.reject(new Error(res.data.message));
}
