/**
 * 탑씰 회사 실제 데이터 화면 검증
 * - 회사 선택 → 탑씰
 * - 구매관리 > 발주관리
 * - 수주관리
 * - 테이블 가로 스크롤, 페이지네이션 확인
 */

import { chromium } from "playwright";
import * as path from "path";
import * as fs from "fs";

const BASE_URL = "http://localhost:9771";
const SCREENSHOT_DIR = path.join(__dirname, "../verification-screenshots");

async function main() {
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
  const page = await context.newPage();

  const results: Record<string, any> = {};

  try {
    // Step 1: 접속
    console.log("Step 1: 접속...");
    await page.goto(BASE_URL, { waitUntil: "load", timeout: 30000 });
    await page.waitForTimeout(2000);

    const url = page.url();
    if (url.includes("/login")) {
      console.log("로그인 필요...");
      await page.fill("#userId", "wace");
      await page.fill("#password", "qlalfqjsgh11");
      await page.locator('button[type="submit"]').first().click();
      await page.waitForURL((u) => !u.includes("/login"), { timeout: 15000 }).catch(() => {});
      await page.waitForTimeout(3000);
    }

    await page.getByText("현재 관리 회사").waitFor({ timeout: 8000 }).catch(() => {});

    // Step 2: 회사 선택 → 탑씰
    console.log("Step 2: 회사 선택 → 탑씰...");
    const companyBtn = page.getByText("회사 선택").first();
    if ((await companyBtn.count()) > 0) {
      await companyBtn.click();
      await page.waitForTimeout(1500);
      const tapseal = page.getByText("탑씰", { exact: true }).first();
      if ((await tapseal.count()) > 0) {
        await tapseal.click();
        await page.waitForTimeout(2500);
        console.log("탑씰 선택됨");
      }
    }

    // Step 3: 구매관리 > 발주관리
    console.log("Step 3: 구매관리 > 발주관리 클릭...");
    const purchaseMgmt = page.getByText("구매관리").first();
    if ((await purchaseMgmt.count()) > 0) {
      await purchaseMgmt.click();
      await page.waitForTimeout(800);
      const orderMgmt = page.getByText("발주관리").first();
      if ((await orderMgmt.count()) > 0) {
        await orderMgmt.click();
        await page.waitForTimeout(4000);
      }
    }
    await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 10000 }).catch(() => {});
    await page.waitForTimeout(2000);

    // Step 4: 발주관리 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-10.png"), fullPage: true });
    console.log("verify-10.png 저장 (발주관리)");

    // Step 5: 발주관리 - 테이블/스크롤/페이지네이션 확인
    const orderDims = await page.evaluate(() => {
      const table = document.querySelector("table");
      const tableContainer = table?.closest("[style*='overflow'], [class*='overflow']");
      const pagination = document.body.innerText.includes("표시") || document.body.innerText.includes("1/");
      return {
        tableScrollWidth: table ? (table as HTMLElement).scrollWidth : 0,
        tableClientWidth: table ? (table as HTMLElement).clientWidth : 0,
        containerClientWidth: tableContainer ? (tableContainer as HTMLElement).clientWidth : 0,
        hasPagination: pagination,
        dataRows: table ? table.querySelectorAll("tbody tr").length : 0,
      };
    });
    results.orderMgmt = orderDims;
    console.log("발주관리 - 테이블:", orderDims.tableScrollWidth, "x", orderDims.tableClientWidth, "데이터행:", orderDims.dataRows, "페이지네이션:", orderDims.hasPagination);

    // Step 6: 테이블 가로 스크롤 시도
    const scrollResult = await page.evaluate(() => {
      const table = document.querySelector("table");
      const scrollable = table?.closest("[style*='overflow'], [class*='overflow']") as HTMLElement;
      if (scrollable && scrollable.scrollWidth > scrollable.clientWidth) {
        scrollable.scrollLeft = 200;
        return { scrolled: true, scrollLeft: scrollable.scrollLeft };
      }
      return { scrolled: false };
    });
    results.orderScroll = scrollResult;
    await page.waitForTimeout(500);

    // Step 7: 수주관리 메뉴 클릭
    console.log("Step 7: 수주관리 클릭...");
    const salesMgmt = page.getByText("영업관리").first();
    if ((await salesMgmt.count()) > 0) {
      await salesMgmt.click();
      await page.waitForTimeout(600);
    }
    const orderScreen = page.getByText("수주관리").first();
    if ((await orderScreen.count()) > 0) {
      await orderScreen.click();
      await page.waitForTimeout(4000);
    }
    await page.getByText("로딩중", { exact: false }).waitFor({ state: "hidden", timeout: 10000 }).catch(() => {});
    await page.waitForTimeout(2000);

    // Step 8: 수주관리 스크린샷
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-11.png"), fullPage: true });
    console.log("verify-11.png 저장 (수주관리)");

    // Step 9: 수주관리 - 테이블/페이지네이션 확인
    const salesDims = await page.evaluate(() => {
      const table = document.querySelector("table");
      const pagination = document.body.innerText.includes("표시") || document.body.innerText.includes("1/");
      return {
        tableScrollWidth: table ? (table as HTMLElement).scrollWidth : 0,
        tableClientWidth: table ? (table as HTMLElement).clientWidth : 0,
        hasPagination: pagination,
        dataRows: table ? table.querySelectorAll("tbody tr").length : 0,
      };
    });
    results.salesOrderMgmt = salesDims;
    console.log("수주관리 - 테이블:", salesDims.tableScrollWidth, "x", salesDims.tableClientWidth, "데이터행:", salesDims.dataRows, "페이지네이션:", salesDims.hasPagination);

    // 이전 문제 해결 여부
    const orderTableFits = orderDims.tableScrollWidth <= (orderDims.containerClientWidth || orderDims.tableClientWidth + 100);
    const salesTableFits = salesDims.tableScrollWidth <= salesDims.tableClientWidth + 100;
    results.issuesResolved = {
      orderTableOverflow: orderTableFits,
      orderPaginationVisible: orderDims.hasPagination,
      salesTableOverflow: salesTableFits,
      salesPaginationVisible: salesDims.hasPagination,
    };

    console.log("\n=== 이전 문제 해결 여부 ===");
    console.log("발주관리 - 테이블 넘침 해결:", orderTableFits);
    console.log("발주관리 - 페이지네이션 보임:", orderDims.hasPagination);
    console.log("수주관리 - 테이블 넘침 해결:", salesTableFits);
    console.log("수주관리 - 페이지네이션 보임:", salesDims.hasPagination);

    fs.writeFileSync(
      path.join(SCREENSHOT_DIR, "verify-tapseal-result.json"),
      JSON.stringify(results, null, 2)
    );
  } catch (error: any) {
    console.error("오류:", error.message);
    await page.screenshot({ path: path.join(SCREENSHOT_DIR, "verify-99-error.png"), fullPage: true }).catch(() => {});
  } finally {
    await browser.close();
  }
}

main();
