import { getMachinery, type Machinery } from "../../../api/equipment";
import { getBarcodePage } from "../../../api/wls";

const MACHINERY_BIZ_TYPE = 400;

function scanCode() {
  return new Promise<string | null>((resolve, reject) => {
    uni.scanCode({
      onlyFromCamera: true,
      scanType: ["qrCode", "barCode"],
      success: result => resolve(String(result.result || "").trim()),
      fail: error => {
        const message = String((error as { errMsg?: string })?.errMsg || "");
        if (/cancel/i.test(message)) resolve(null);
        else reject(new Error("扫码失败，请检查相机权限后重试"));
      },
    });
  });
}

function matchKnownMachinery(content: string, machineries: Machinery[]) {
  const exact = machineries.find(item => item.code && item.code === content);
  if (exact) return exact;
  const matches = machineries
    .filter(item => item.code && content.includes(item.code))
    .sort((a, b) => (b.code?.length || 0) - (a.code?.length || 0));
  return matches[0];
}

export async function scanMachinery(accessToken: string, machineries: Machinery[]) {
  const content = await scanCode();
  if (!content) return null;

  try {
    const page = await getBarcodePage(accessToken, {
      pageNo: 1,
      pageSize: 20,
      bizType: MACHINERY_BIZ_TYPE,
      content,
    });
    const barcode = page.list.find(item => item.content === content && item.bizType === MACHINERY_BIZ_TYPE);
    if (barcode?.bizId) return await getMachinery(accessToken, barcode.bizId);
  } catch {
    // Some equipment roles can use records without barcode-list permission.
  }

  const matched = matchKnownMachinery(content, machineries);
  if (matched?.id) return await getMachinery(accessToken, matched.id);
  throw new Error("未识别到设备，请确认扫描的是设备台账中的二维码");
}
