// ============================================================
// MES 완전 통합 시스템
// 채번규칙(문서번호) + 공통코드(품목/LOT) 분리 적용
// 자재관리, 입고LOT, 생산LOT, 문서양식 연동
// ============================================================

import documentTemplateConfig from '../configs/documentTemplateConfig';
import {
  generateItemCode,
  generateLotNo,
  lotProductCodes,
  lotTypeCodes,
  lotSizeCodes,
  lotDateCodeRules,
} from '../configs/codeRuleConfig';

// ============================================================
// 1. 채번관리 - 문서번호 생성 (실제 채번관리 테이블 기반)
// ============================================================

/**
 * 실제 채번관리 설정 (스크린샷 기준)
 * 번호기준 이름 | 적용 대상 | 접두사 | 날짜 형식 | 예시
 */
const NUMBERING_RULES = {
  // 견적번호 기준
  'QT': { prefix: 'KD-PR-', dateFormat: 'YYMMDD', example: 'KD-PR-251209-01' },

  // 발주번호 기준
  'PO': { prefix: 'KD-SO-', dateFormat: 'YYMMDD', example: 'KD-SO-251209-01' },

  // 수주번호 기준 (스크린)
  'SO-SCR': { prefix: 'KD-TS-', dateFormat: 'YYMMDD', example: 'KD-TS-251209-01' },
  'SO': { prefix: 'KD-TS-', dateFormat: 'YYMMDD', example: 'KD-TS-251209-01' },

  // 수주번호 기준 (슬랫)
  'SO-SLT': { prefix: 'KD-SL-', dateFormat: 'YYMMDD', example: 'KD-SL-251209-01' },

  // 수주번호 기준 (절곡)
  'SO-BD': { prefix: 'KD-BD-', dateFormat: 'YYMMDD', example: 'KD-BD-251209-01' },

  // 작업지시번호 기준
  'WO': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },
  'WO-SCR': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },
  'WO-SLT': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },
  'WO-FLD': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },

  // 출하번호 기준
  'SL': { prefix: 'KD-SH-', dateFormat: 'YYMMDD', example: 'KD-SH-251209-01' },
  'SH': { prefix: 'KD-SH-', dateFormat: 'YYMMDD', example: 'KD-SH-251209-01' },

  // 출고번호 기준
  'OUT': { prefix: 'P-', dateFormat: 'YYMMDD', example: '250710-P-03' },

  // 현장코드 기준
  'SITE': { prefix: 'PJ-', dateFormat: 'YYMMDD', example: 'PJ-251217-01' },

  // 검사 LOT 기준 (일반)
  'QC': { prefix: 'KD-QC-', dateFormat: 'YYMMDD', example: 'KD-QC-251209-01' },
  'IQC': { prefix: 'KD-QC-', dateFormat: 'YYMMDD', example: 'KD-QC-251209-01' },

  // 중간검사 LOT 기준
  'PQC': { prefix: 'KD-WE-', dateFormat: 'YYMMDD', example: 'KD-WE-251209-01' },

  // 제품검사 LOT 기준
  'FQC': { prefix: 'KD-SA-', dateFormat: 'YYMMDD', example: 'KD-SA-251209-01' },

  // 생산 LOT 기준
  'PL': { prefix: 'KD-PL-', dateFormat: 'YYMMDD', example: 'KD-PL-251209-01' },

  // 입고검사 LOT 기준 (접두사 없음)
  'IN-LOT': { prefix: '', dateFormat: 'YYMMDD', example: '251209-01' },

  // 완제품/부품 LOT 기준 (수주번호 기반)
  'PROD-LOT': { prefix: 'KD-TS-', dateFormat: 'YYMMDD', example: 'KD-TS-251209-01-01', useOrderRef: true },

  // 작업일지 (작업지시와 동일 패턴)
  'WL-SCR': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },
  'WL-SLT': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },
  'WL-FLD': { prefix: 'KD-WO-', dateFormat: 'YYMMDD', example: 'KD-WO-251209-01' },

  // 재고생산 작업일지 (고유 패턴)
  'WL-STK': { prefix: 'WL-STK-', dateFormat: 'YYMMDD', example: 'WL-STK-251209-01' },
};

// 시퀀스 저장소 (localStorage)
const getSequenceStorage = () => {
  const stored = localStorage.getItem('mes_doc_sequences');
  return stored ? JSON.parse(stored) : {};
};

const setSequenceStorage = (data) => {
  localStorage.setItem('mes_doc_sequences', JSON.stringify(data));
};

// 시퀀스 초기화 (테스트용)
export const resetAllSequences = () => {
  localStorage.removeItem('mes_doc_sequences');
  localStorage.removeItem('mes_lot_sequences');
  console.log('모든 채번 시퀀스가 초기화되었습니다.');
};

/**
 * 문서번호 생성 (실제 채번관리 테이블 적용)
 * @param {string} docType - 문서유형 (QT, SO, WO-SCR, PQC, FQC, SL 등)
 * @param {Date} date - 기준일자
 * @param {object} options - 추가 옵션 (subSeq: 세부순번 등)
 * @returns {string} 생성된 문서번호
 */
export const generateDocNo = (docType, date = new Date(), options = {}) => {
  const rule = NUMBERING_RULES[docType];

  // 날짜 포맷
  const yy = String(date.getFullYear()).slice(-2);
  const mm = String(date.getMonth() + 1).padStart(2, '0');
  const dd = String(date.getDate()).padStart(2, '0');
  const dateKey = `${yy}${mm}${dd}`;

  // 시퀀스 조회 및 증가
  const sequences = getSequenceStorage();
  const seqKey = `${docType}_${dateKey}`;
  const seq = (sequences[seqKey] || 0) + 1;
  sequences[seqKey] = seq;
  setSequenceStorage(sequences);

  const seqStr = String(seq).padStart(2, '0');

  if (!rule) {
    // 규칙 없으면 기본 패턴
    return `${docType}-${dateKey}-${seqStr}`;
  }

  // 채번규칙에 따른 문서번호 생성
  // 예: KD-PR-251217-01
  if (options.subSeq !== undefined) {
    // 세부순번이 있는 경우 (예: 중간검사 KD-WE-251209-01-(3))
    return `${rule.prefix}${dateKey}-${seqStr}-(${options.subSeq})`;
  }

  return `${rule.prefix}${dateKey}-${seqStr}`;
};

/**
 * 채번관리 규칙 조회
 */
export const getNumberingRule = (docType) => {
  return NUMBERING_RULES[docType] || null;
};

/**
 * 모든 채번관리 규칙 조회
 */
export const getAllNumberingRules = () => {
  return { ...NUMBERING_RULES };
};

// ============================================================
// 2. 공통코드 - LOT번호 생성 (codeRuleConfig)
// ============================================================

const getLotSequenceStorage = () => {
  const stored = localStorage.getItem('mes_lot_sequences');
  return stored ? JSON.parse(stored) : {};
};

const setLotSequenceStorage = (data) => {
  localStorage.setItem('mes_lot_sequences', JSON.stringify(data));
};

/**
 * 입고 LOT 번호 생성 (원자재/원단용)
 * 형식: YYMMDD-## (예: 251217-01)
 * @param {string} materialType - 원자재/원단
 * @param {Date} date - 입고일자
 * @returns {string} 입고 LOT 번호
 */
export const generateIncomingLotNo = (materialType, date = new Date()) => {
  const yy = String(date.getFullYear()).slice(-2);
  const mm = String(date.getMonth() + 1).padStart(2, '0');
  const dd = String(date.getDate()).padStart(2, '0');
  const dateKey = `${yy}${mm}${dd}`;

  const sequences = getLotSequenceStorage();
  const seqKey = `LOT-IN_${dateKey}`;
  const seq = (sequences[seqKey] || 0) + 1;
  sequences[seqKey] = seq;
  setLotSequenceStorage(sequences);

  return `${dateKey}-${String(seq).padStart(2, '0')}`;
};

/**
 * 생산 LOT 번호 생성 (절곡품)
 * 형식: {품목코드}{종류코드}{Y}{M}{DD}-{규격} (예: CF4C17-40)
 * @param {string} itemName - 품목명 (케이스, 가이드레일 등)
 * @param {string} typeName - 종류명 (전면부, 본체 등)
 * @param {number} length - 길이 (mm)
 * @param {Date} date - 생산일자
 * @returns {string} 생산 LOT 번호
 */
export const generateProductionLotNo = (itemName, typeName, length, date = new Date()) => {
  const lotRules = documentTemplateConfig?.numberingRules || {};

  // 품목 코드 조회
  const itemCode = lotRules.lotItemCodes?.[itemName]?.code ||
    lotProductCodes[itemName]?.code ||
    itemName.charAt(0).toUpperCase();

  // 종류 코드 조회
  const typeCode = lotRules.lotTypeCodes?.[typeName]?.code ||
    lotTypeCodes[typeName]?.code ||
    typeName.charAt(0).toUpperCase();

  // 날짜 코드 (Y: 연도 끝자리, M: 월코드, DD: 일)
  const y = String(date.getFullYear() % 10);
  const month = date.getMonth() + 1;
  const monthCode = lotRules.monthCodes?.[month] || lotDateCodeRules.monthCodes[month] || month;
  const dd = String(date.getDate()).padStart(2, '0');

  // 규격 코드 (길이 앞 2자리)
  const specCode = lotSizeCodes[String(length)] || String(length).substring(0, 2);

  return `${itemCode}${typeCode}${y}${monthCode}${dd}-${specCode}`;
};

// ============================================================
// 3. 품목코드 생성 (공통코드 규칙)
// ============================================================

/**
 * 품목코드 자동생성 (codeRuleConfig 규칙 적용)
 */
export const generateItemCodeAuto = (itemType, formData) => {
  return generateItemCode(itemType, formData);
};

// ============================================================
// 4. 자재관리 - 입고/출고/재고
// ============================================================

/**
 * 자재 입고 처리
 * @param {object} material - 자재 정보
 * @param {number} qty - 입고 수량
 * @param {string} supplierLotNo - 공급업체 LOT (선택)
 * @returns {object} 입고 데이터
 */
export const createMaterialReceipt = (material, qty, options = {}) => {
  const { supplierLotNo = null, manufacturer = '', multiUnits = [], attachments = [] } = options;
  const today = new Date();
  const incomingLotNo = generateIncomingLotNo(material.itemType, today);

  return {
    id: Date.now(),
    receiptNo: generateDocNo('GR', today), // 입고전표번호
    receiptDate: today.toISOString().split('T')[0],
    materialId: material.id,
    itemCode: material.itemCode,
    itemName: material.itemName,
    spec: material.spec,
    unit: material.unit,
    qty,
    unitPrice: material.standardPrice || 0,
    totalAmount: qty * (material.standardPrice || 0),
    lotNo: incomingLotNo,
    supplierLotNo,
    supplier: material.supplier,
    manufacturer: manufacturer || material.supplier, // 제조사 (기본값은 공급사와 동일)
    multiUnits: multiUnits.length > 0 ? multiUnits : [{ unit: material.unit, qty }], // 복수 단위 관리
    attachments, // 밀시트, 거래명세표 등 첨부파일
    warehouseCode: 'WH-001',
    warehouseName: '원자재창고',
    status: '입고완료',
    createdAt: today.toISOString(),
  };
};

/**
 * 자재 출고 처리 (작업지시 기준)
 * @param {object} workOrder - 작업지시
 * @param {array} materials - 출고할 자재 목록
 * @returns {object} 출고 데이터
 */
export const createMaterialIssue = (workOrder, materials) => {
  const today = new Date();

  return {
    id: Date.now(),
    issueNo: generateDocNo('GI', today), // 출고전표번호
    issueDate: today.toISOString().split('T')[0],
    workOrderId: workOrder.id,
    workOrderNo: workOrder.workOrderNo,
    items: materials.map(m => ({
      materialId: m.id,
      itemCode: m.itemCode,
      itemName: m.itemName,
      spec: m.spec,
      unit: m.unit,
      requestQty: m.requestQty,
      issueQty: m.issueQty || m.requestQty,
      lotNo: m.lotNo,
    })),
    status: '출고완료',
    createdAt: today.toISOString(),
  };
};

// ============================================================
// 5. BOM 자동계산 (견적수식)
// ============================================================

/**
 * 오픈사이즈 → 제작사이즈 변환
 */
export const calculateProductionSize = (W0, H0, productType = '스크린') => {
  if (productType === '철재' || productType === '슬랫') {
    return {
      W1: W0 + 110,
      H1: H0 + 350,
    };
  }
  return {
    W1: W0 + 140,
    H1: H0 + 350,
  };
};

/**
 * 면적 및 중량 계산
 */
export const calculateAreaWeight = (W1, H1, W0, productType = '스크린') => {
  const M = (W1 * H1) / 1000000; // 면적 (㎡)
  let K;

  if (productType === '철재' || productType === '슬랫') {
    K = M * 25;
  } else {
    K = (M * 2) + (W0 * 14.17 / 1000);
  }

  return {
    area: Math.round(M * 100) / 100,
    weight: Math.round(K * 10) / 10,
  };
};

/**
 * 모터용량 조회
 */
const motorCapacityTable = {
  '스크린': [
    { maxWeight: 60, capacity: 150, shaft: '4' },
    { maxWeight: 100, capacity: 200, shaft: '4' },
    { maxWeight: 150, capacity: 300, shaft: '5' },
    { maxWeight: 250, capacity: 400, shaft: '5' },
    { maxWeight: 400, capacity: 500, shaft: '6' },
  ],
  '철재': [
    { maxWeight: 80, capacity: 150, shaft: '4' },
    { maxWeight: 120, capacity: 200, shaft: '4' },
    { maxWeight: 180, capacity: 300, shaft: '5' },
    { maxWeight: 300, capacity: 400, shaft: '5' },
    { maxWeight: 450, capacity: 500, shaft: '6' },
  ],
};

export const lookupMotorCapacity = (weight, productType = '스크린') => {
  const table = motorCapacityTable[productType] || motorCapacityTable['스크린'];
  for (const row of table) {
    if (weight <= row.maxWeight) {
      return { capacity: row.capacity, shaft: row.shaft };
    }
  }
  return { capacity: 500, shaft: '6' };
};

/**
 * 브라켓/앵글 규격 조회
 */
const bracketTable = {
  150: { bracket: '380×180', angle: '40×40×380' },
  200: { bracket: '380×180', angle: '40×40×380' },
  300: { bracket: '380×180', angle: '40×40×380' },
  400: { bracket: '530×320', angle: '50×50×530' },
  500: { bracket: '600×350', angle: '50×50×600' },
};

/**
 * 가이드레일 자재길이 조회
 */
const guideRailLengthTable = [
  { maxG: 2438, length: 2438 },
  { maxG: 3000, length: 3000 },
  { maxG: 3500, length: 3500 },
  { maxG: 4000, length: 4000 },
  { maxG: 4300, length: 4300 },
];

/**
 * 전체 BOM 자동계산
 */
export const calculateFullBOM = (input) => {
  const {
    openWidth: W0 = 3000,
    openHeight: H0 = 3000,
    productType = '스크린',
    installType = '벽면형',
    motorPower = '380',
    wireType = '유선',
    controllerType = '매립',
    qty = 1,
  } = input;

  // 1. 제작사이즈
  const { W1, H1 } = calculateProductionSize(W0, H0, productType);

  // 2. 면적/중량
  const { area: M, weight: K } = calculateAreaWeight(W1, H1, W0, productType);

  // 3. 모터용량
  const { capacity: motorCapacity, shaft: shaftInch } = lookupMotorCapacity(K, productType);

  // 4. 브라켓/앵글
  const bracketSpec = bracketTable[motorCapacity] || bracketTable[300];

  // 5. 가이드레일 길이
  const G = H0 + 250;
  const grSpec = guideRailLengthTable.find(r => G <= r.maxG) || { length: 4300 };

  // 6. BOM 품목 생성
  const bomItems = [
    // 구매부품
    {
      category: '구매부품',
      itemCode: generateItemCodeAuto('부품', { partSubType: '구매 부품', itemName: '전동개폐기', power: `${motorPower}V`, capacity: `${motorCapacity}KG` }),
      itemName: '전동개폐기',
      spec: `${motorPower}V ${motorCapacity}KG`,
      unit: 'EA',
      qty: qty,
      unitPrice: motorCapacity >= 400 ? 450000 : motorCapacity >= 300 ? 350000 : 280000,
      processType: '조립',
    },
    {
      category: '구매부품',
      itemCode: generateItemCodeAuto('부품', { partSubType: '구매 부품', itemName: '연동제어기', spec: `${controllerType}(${wireType})` }),
      itemName: '연동제어기',
      spec: `${controllerType}(${wireType})`,
      unit: 'EA',
      qty: qty,
      unitPrice: wireType === '무선' ? 85000 : 65000,
      processType: '전기',
    },
    {
      category: '구매부품',
      itemCode: `브라켓-${bracketSpec.bracket}`,
      itemName: '브라켓',
      spec: bracketSpec.bracket,
      unit: 'SET',
      qty: qty,
      unitPrice: motorCapacity >= 400 ? 35000 : 25000,
      processType: '조립',
    },
    {
      category: '구매부품',
      itemCode: `감기샤프트-${shaftInch}인치`,
      itemName: '감기샤프트',
      spec: `${shaftInch}인치 L${W1 < 3000 ? 3000 : W1 < 4500 ? 4500 : 6000}`,
      unit: 'EA',
      qty: qty,
      unitPrice: W1 >= 4500 ? 180000 : 120000,
      processType: '조립',
    },
    // 절곡부품
    {
      category: '절곡부품',
      itemCode: generateItemCodeAuto('부품', { partSubType: '절곡 부품', bendingPartItemName: '가이드레일(벽면형)', bendingPartType: '본체', bendingSizeLength: grSpec.length }),
      itemName: '가이드레일(본체)',
      spec: `L${grSpec.length}`,
      unit: 'EA',
      qty: qty * 2,
      unitPrice: 45000,
      processType: '절곡',
      productionLotRequired: true,
    },
    {
      category: '절곡부품',
      itemCode: generateItemCodeAuto('부품', { partSubType: '절곡 부품', bendingPartItemName: '케이스', bendingPartType: '전면부', bendingSizeLength: W1 < 2438 ? 2438 : 4000 }),
      itemName: '케이스판재',
      spec: `L${W1 < 2438 ? 2438 : 4000}`,
      unit: 'EA',
      qty: qty,
      unitPrice: 85000,
      processType: '절곡',
      productionLotRequired: true,
    },
    // 부자재
    {
      category: '부자재',
      itemCode: '연기차단재-W80',
      itemName: '연기차단재',
      spec: `W80 L${grSpec.length}`,
      unit: 'EA',
      qty: productType === '철재' ? qty * 2 : qty * 4,
      unitPrice: 12000,
      processType: '조립',
    },
  ];

  // 스크린 전용 품목
  if (productType === '스크린') {
    bomItems.push({
      category: '원자재',
      itemCode: '스크린원단-0.5T',
      itemName: '스크린 원단',
      spec: `W${W1} H${H1}`,
      unit: 'M',
      qty: Math.ceil((W1 * H1) / 1000000 * 1.1) * qty,
      unitPrice: 15000,
      processType: '스크린',
      incomingLotRequired: true,
    });
  }

  // 금액 계산
  bomItems.forEach(item => {
    item.amount = item.qty * item.unitPrice;
  });

  const totalAmount = bomItems.reduce((sum, item) => sum + item.amount, 0);

  return {
    variables: { W0, H0, W1, H1, M, K, G, motorCapacity, shaftInch, productType, installType },
    items: bomItems,
    summary: {
      totalItemCount: bomItems.length,
      totalAmount,
      vatAmount: Math.round(totalAmount * 0.1),
      grandTotal: Math.round(totalAmount * 1.1),
    },
  };
};

// ============================================================
// 6. 공정관리 - 작업단계/담당자
// ============================================================

export const processWorkflows = {
  '스크린': {
    code: 'SCR',
    name: '스크린',
    docType: 'WO-SCR',
    workLogType: 'WL-SCR',
    steps: [
      { stepNo: 1, stepCode: 'SCR-MAT', stepName: '자재투입', estimatedTime: 10 },
      { stepNo: 2, stepCode: 'SCR-CNT', stepName: '절단매수확인', estimatedTime: 5 },
      { stepNo: 3, stepCode: 'SCR-CUT', stepName: '원단절단', estimatedTime: 30 },
      { stepNo: 4, stepCode: 'SCR-CHK', stepName: '절단Check', estimatedTime: 10, isQC: true },
      { stepNo: 5, stepCode: 'SCR-SEW', stepName: '미싱', estimatedTime: 45 },
      { stepNo: 6, stepCode: 'SCR-END', stepName: '앤드락작업', estimatedTime: 20 },
      { stepNo: 7, stepCode: 'SCR-QC', stepName: '중간검사', estimatedTime: 15, isQC: true },
      { stepNo: 8, stepCode: 'SCR-PACK', stepName: '포장', estimatedTime: 10 },
    ],
    team: '스크린팀',
    workers: ['김스크린', '이스크린', '박스크린'],
  },
  '슬랫': {
    code: 'SLT',
    name: '슬랫',
    docType: 'WO-SLT',
    workLogType: 'WL-SLT',
    steps: [
      { stepNo: 1, stepCode: 'SLT-CUT', stepName: '코일절단', estimatedTime: 25 },
      { stepNo: 2, stepCode: 'SLT-FIN', stepName: '미미작업', estimatedTime: 20 },
      { stepNo: 3, stepCode: 'SLT-QC', stepName: '중간검사', estimatedTime: 10, isQC: true },
      { stepNo: 4, stepCode: 'SLT-PACK', stepName: '포장', estimatedTime: 10 },
    ],
    team: '슬랫팀',
    workers: ['김슬랫', '이슬랫'],
  },
  '절곡': {
    code: 'FLD',
    name: '절곡',
    docType: 'WO-FLD',
    workLogType: 'WL-FLD',
    steps: [
      { stepNo: 1, stepCode: 'FLD-CUT', stepName: '절단', estimatedTime: 30 },
      { stepNo: 2, stepCode: 'FLD-VCT', stepName: 'V컷팅', estimatedTime: 20 },
      { stepNo: 3, stepCode: 'FLD-BND', stepName: '절곡', estimatedTime: 40 },
      { stepNo: 4, stepCode: 'FLD-QC', stepName: '중간검사', estimatedTime: 15, isQC: true },
      { stepNo: 5, stepCode: 'FLD-PACK', stepName: '포장', estimatedTime: 10 },
    ],
    team: '절곡팀',
    workers: ['김절곡', '이절곡', '박절곡'],
  },
  '재고생산': {
    code: 'STK',
    name: '재고생산',
    docType: 'WO-STK',
    workLogType: 'WL-STK',
    steps: [
      { stepNo: 1, stepCode: 'STK-FRM', stepName: '포밍', estimatedTime: 30 },
      { stepNo: 2, stepCode: 'STK-CUT', stepName: '절단', estimatedTime: 20 },
      { stepNo: 3, stepCode: 'STK-QC', stepName: '검사', estimatedTime: 15, isQC: true },
      { stepNo: 4, stepCode: 'STK-STK', stepName: '적재', estimatedTime: 10 },
    ],
    team: '포밍팀',
    workers: ['김생산'],
  },
};

// ============================================================
// 7. 문서양식 연동 - 작업일지/검사성적서
// ============================================================

/**
 * 공정별 작업일지 템플릿 조회
 */
export const getWorkLogTemplate = (processType) => {
  const templates = documentTemplateConfig?.documentTemplates || {};
  const processConfig = processWorkflows[processType];

  if (!processConfig) return null;

  const template = templates[processConfig.workLogType];
  return template || null;
};

/**
 * 작업일지 데이터 생성 (문서양식 연동)
 */
export const createWorkLogData = (workOrder, stepResults) => {
  const processConfig = processWorkflows[workOrder.processType];
  const today = new Date();
  const workLogNo = generateDocNo(processConfig?.workLogType || 'WL', today);

  // 문서양식 템플릿 조회
  const template = getWorkLogTemplate(workOrder.processType);

  return {
    id: Date.now(),
    workLogNo,
    workLogDate: today.toISOString().split('T')[0],
    documentType: processConfig?.workLogType || 'WL',
    templateCode: template?.code || null,

    // 작업지시 연결
    workOrderId: workOrder.id,
    workOrderNo: workOrder.workOrderNo,
    orderId: workOrder.orderId,
    orderNo: workOrder.orderNo,

    // 기본정보
    processType: workOrder.processType,
    productName: workOrder.productName,
    productSpec: workOrder.productSpec,
    lotNo: workOrder.lotNo,

    // 작업정보
    workDate: today.toISOString().split('T')[0],
    team: processConfig?.team || '',
    workers: processConfig?.workers || [],

    // 수량정보
    planQty: workOrder.totalQty,
    actualQty: stepResults?.completedQty || 0,
    defectQty: stepResults?.defectQty || 0,

    // 작업단계별 결과
    stepResults: (processConfig?.steps || []).map(step => {
      const result = stepResults?.steps?.[step.stepCode] || {};
      return {
        stepNo: step.stepNo,
        stepCode: step.stepCode,
        stepName: step.stepName,
        status: result.status || '대기',
        startTime: result.startTime || null,
        endTime: result.endTime || null,
        worker: result.worker || '',
        note: result.note || '',
        isQC: step.isQC || false,
        qcResult: result.qcResult || null,
      };
    }),

    // 특이사항
    remarks: stepResults?.remarks || '',

    // 결재정보
    approval: {
      writer: { name: '', signDate: null },
      reviewer: { name: '', signDate: null },
      approver: { name: '', signDate: null },
    },

    // 메타
    status: '작성중',
    createdAt: today.toISOString(),
    createdBy: '시스템',
  };
};

/**
 * 검사성적서 템플릿 조회
 */
export const getInspectionTemplate = (inspectionType, processType) => {
  const templates = documentTemplateConfig?.documentTemplates || {};

  // 검사유형별 템플릿 매핑
  const templateMap = {
    'IQC': 'IQC', // 수입검사
    'PQC': 'PQC', // 중간검사
    'FQC': 'FQC', // 최종검사
  };

  return templates[templateMap[inspectionType]] || null;
};

/**
 * 검사 데이터 생성 (문서양식 연동)
 */
export const createInspectionData = (workOrder, inspectionType, checkResults) => {
  const today = new Date();
  const inspectionNo = generateDocNo(inspectionType, today);
  const template = getInspectionTemplate(inspectionType, workOrder.processType);

  // 검사항목 기본 세팅
  const defaultCheckItems = getDefaultCheckItems(workOrder.processType, inspectionType);

  return {
    id: Date.now(),
    inspectionNo,
    inspectionDate: today.toISOString().split('T')[0],
    inspectionType,
    templateCode: template?.code || null,

    // 연결정보
    workOrderId: workOrder.id,
    workOrderNo: workOrder.workOrderNo,
    orderId: workOrder.orderId,
    orderNo: workOrder.orderNo,

    // 수입검사 전용 필드 (materialReceipt 연동 시)
    receiptNo: workOrder.receiptNo || null,
    supplier: workOrder.supplier || null,
    manufacturer: workOrder.manufacturer || null,
    incomingLotNo: workOrder.incomingLotNo || null,
    hasMillSheet: workOrder.hasMillSheet || false,

    // 제품정보
    productName: workOrder.productName,
    productSpec: workOrder.productSpec,
    lotNo: workOrder.lotNo,
    productionLotNo: workOrder.productionLotNo || null,

    // 수량
    inspectionQty: workOrder.totalQty,
    passQty: checkResults?.passQty || 0,
    failQty: checkResults?.failQty || 0,
    multiUnits: workOrder.multiUnits || [],

    // 검사결과
    result: checkResults?.result || '미검사',
    inspectorName: checkResults?.inspector || '',

    // 검사항목
    checkItems: defaultCheckItems.map(item => ({
      ...item,
      result: checkResults?.items?.[item.code]?.result || '',
      status: checkResults?.items?.[item.code]?.status || '미검사',
      measuredValue: checkResults?.items?.[item.code]?.measuredValue || '',
    })),

    // 첨부파일 (Mill Sheet 등)
    attachments: workOrder.attachments || [],

    // 비고
    remarks: checkResults?.remarks || '',

    // 결재정보
    approval: {
      inspector: { name: '', signDate: null },
      reviewer: { name: '', signDate: null },
      approver: { name: '', signDate: null },
    },

    // 메타
    status: '검사대기',
    createdAt: today.toISOString(),
    createdBy: '시스템',
  };
};

/**
 * 공정/검사유형별 기본 검사항목
 */
const getDefaultCheckItems = (processType, inspectionType) => {
  const baseItems = [
    { code: 'CHK-001', name: '외관검사', spec: '흠집/변형/이물질 없음', type: '육안검사' },
    { code: 'CHK-002', name: '치수검사', spec: '도면규격 ±3mm', type: '측정검사' },
  ];

  if (processType === '스크린') {
    baseItems.push(
      { code: 'CHK-SCR-001', name: '원단상태', spec: '찢김/얼룩 없음', type: '육안검사' },
      { code: 'CHK-SCR-002', name: '미싱상태', spec: '박음질 견고', type: '육안검사' },
    );
  } else if (processType === '슬랫') {
    baseItems.push(
      { code: 'CHK-SLT-001', name: '슬랫연결', spec: '연결부 이상 없음', type: '육안검사' },
      { code: 'CHK-SLT-002', name: '도장상태', spec: '도장 균일', type: '육안검사' },
    );
  } else if (processType === '절곡') {
    baseItems.push(
      { code: 'CHK-FLD-001', name: '절곡각도', spec: '규격 ±1°', type: '측정검사' },
      { code: 'CHK-FLD-002', name: '용접상태', spec: '용접 견고', type: '육안검사' },
    );
  }

  if (inspectionType === 'FQC') {
    baseItems.push(
      { code: 'CHK-FQC-001', name: '동작검사', spec: '개폐 정상', type: '기능검사' },
      { code: 'CHK-FQC-002', name: '포장상태', spec: '포장 완료', type: '육안검사' },
    );
  }

  return baseItems;
};

// ============================================================
// 8. 전체 프로세스 통합 실행
// ============================================================

/**
 * 완전 통합 프로세스 실행
 * 거래처→현장→품목→단가→견적→수주→생산→검사→입금→출하→최종검사→매출
 */
export const runCompleteProcess = (params) => {
  const {
    customer,
    site,
    openWidth,
    openHeight,
    productType,
    qty,
    testNo,
  } = params;

  const today = new Date();
  const results = {
    testNo,
    success: true,
    errors: [],
    documents: {},
    timeline: [],
  };

  const log = (step, message, data = null) => {
    results.timeline.push({ step, message, timestamp: new Date().toISOString(), data });
    console.log(`[테스트#${testNo}] ${step}: ${message}`);
  };

  try {
    // ═══════════════════════════════════════════════════════════
    // STEP 1: 견적 생성 (채번: QT, BOM 자동계산)
    // ═══════════════════════════════════════════════════════════
    log('견적생성', 'BOM 자동계산 및 견적서 생성');

    const quoteNo = generateDocNo('QT', today);
    const bom = calculateFullBOM({ openWidth, openHeight, productType, qty });

    const quote = {
      id: Date.now(),
      quoteNo,
      quoteDate: today.toISOString().split('T')[0],
      customerId: customer.id,
      customerCode: customer.customerCode,
      customerName: customer.customerName,
      siteId: site.id,
      siteCode: site.siteCode,
      siteName: site.siteName,
      productName: `${productType} 방화셔터`,
      productSpec: `W${openWidth}×H${openHeight}`,
      qty,
      items: bom.items,
      variables: bom.variables,
      supplyAmount: bom.summary.totalAmount,
      vatAmount: bom.summary.vatAmount,
      totalAmount: bom.summary.grandTotal,
      status: '견적완료',
      createdAt: today.toISOString(),
    };

    results.documents.quote = quote;
    log('견적완료', `견적번호: ${quoteNo}, 금액: ${quote.totalAmount.toLocaleString()}원`);

    // ═══════════════════════════════════════════════════════════
    // STEP 2: 수주 전환 (채번: SO)
    // ═══════════════════════════════════════════════════════════
    log('수주전환', '견적→수주 전환');

    const orderNo = generateDocNo('SO', today);
    const dueDate = new Date(today.getTime() + 14 * 24 * 60 * 60 * 1000);

    const order = {
      id: Date.now() + 1,
      orderNo,
      orderDate: today.toISOString().split('T')[0],
      quoteId: quote.id,
      quoteNo: quote.quoteNo,
      customerId: customer.id,
      customerCode: customer.customerCode,
      customerName: customer.customerName,
      siteId: site.id,
      siteCode: site.siteCode,
      siteName: site.siteName,
      productName: quote.productName,
      productSpec: quote.productSpec,
      qty,
      items: quote.items,
      totalAmount: quote.totalAmount,
      dueDate: dueDate.toISOString().split('T')[0],
      status: '수주확정',
      createdAt: today.toISOString(),
    };

    results.documents.order = order;
    log('수주완료', `수주번호: ${orderNo}, 납기: ${order.dueDate}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 3: 자재 입고 (입고LOT 생성)
    // ═══════════════════════════════════════════════════════════
    log('자재입고', '필요 자재 입고 및 입고LOT 생성');

    const materialReceipts = [];
    const requiredMaterials = bom.items.filter(item => item.incomingLotRequired);

    requiredMaterials.forEach(material => {
      const receipt = createMaterialReceipt({
        id: Date.now() + Math.random() * 1000,
        itemCode: material.itemCode,
        itemName: material.itemName,
        itemType: material.category,
        spec: material.spec,
        unit: material.unit,
        standardPrice: material.unitPrice,
        supplier: '포스코',
      }, material.qty, {
        manufacturer: '포스코 생산기술소',
        multiUnits: [
          { unit: 'EA', qty: material.qty },
          { unit: 'KG', qty: material.qty * 57 } // 가상 중량 계산
        ],
        attachments: [
          { name: 'Mill_Sheet_20241028.pdf', type: 'PDF', url: '#' },
          { name: '거래명세표_POSCO.pdf', type: 'PDF', url: '#' }
        ]
      });

      materialReceipts.push(receipt);
    });

    results.documents.materialReceipts = materialReceipts;
    log('입고완료', `${materialReceipts.length}건 입고, LOT: ${materialReceipts.map(r => r.lotNo).join(', ')}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 4: 생산지시 (채번: WO-SCR/WO-SLT/WO-FLD, 생산LOT 생성)
    // ═══════════════════════════════════════════════════════════
    log('생산지시', '공정별 작업지시 생성');

    const workOrders = [];
    const processTypes = productType === '스크린' ? ['스크린', '절곡'] : ['슬랫', '절곡'];

    processTypes.forEach((procType, idx) => {
      const processConfig = processWorkflows[procType];
      const workOrderNo = generateDocNo(processConfig.docType, today);

      // 생산LOT 생성 (절곡품)
      let productionLotNo = null;
      if (procType === '절곡') {
        const grLength = bom.variables.G < 3000 ? 2438 : bom.variables.G < 3500 ? 3000 : 4000;
        productionLotNo = generateProductionLotNo('가이드레일(벽면형)', '본체', grLength, today);
      }

      // 입고LOT 연결 (스크린)
      let incomingLotNo = null;
      if (procType === '스크린' && materialReceipts.length > 0) {
        incomingLotNo = materialReceipts[0].lotNo;
      }

      const wo = {
        id: Date.now() + idx + 100,
        workOrderNo,
        workOrderDate: today.toISOString().split('T')[0],
        processType: procType,
        status: '대기',

        // 연결정보
        orderId: order.id,
        orderNo: order.orderNo,

        // 고객/현장
        customerName: customer.customerName,
        siteName: site.siteName,
        siteCode: site.siteCode,

        // 제품정보
        productName: order.productName,
        productSpec: order.productSpec,

        // LOT 정보
        lotNo: `${order.orderNo}-${String(idx + 1).padStart(2, '0')}`,
        productionLotNo,
        incomingLotNo,

        // 수량
        totalQty: qty,
        completedQty: 0,
        defectQty: 0,

        // 납기
        dueDate: order.dueDate,

        // 공정정보
        steps: processConfig.steps,
        stepStatus: {},
        currentStep: processConfig.steps[0]?.stepName || '',

        // 담당
        team: processConfig.team,
        workers: processConfig.workers,

        // 작업일지 연결
        workLogType: processConfig.workLogType,
        workLogNo: null,

        // 메타
        createdAt: today.toISOString(),
      };

      // 단계별 상태 초기화
      processConfig.steps.forEach(step => {
        wo.stepStatus[step.stepCode] = { status: '대기', startTime: null, endTime: null, worker: '' };
      });

      workOrders.push(wo);
    });

    results.documents.workOrders = workOrders;
    log('생산지시완료', `${workOrders.length}건 작업지시 생성: ${workOrders.map(wo => wo.workOrderNo).join(', ')}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 5: 작업자 진행 (작업일지 생성)
    // ═══════════════════════════════════════════════════════════
    log('작업진행', '작업단계 진행 및 작업일지 생성');

    const workLogs = [];

    workOrders.forEach((wo, idx) => {
      const processConfig = processWorkflows[wo.processType];

      // 모든 단계 완료 처리
      processConfig.steps.forEach((step, stepIdx) => {
        wo.stepStatus[step.stepCode] = {
          status: '완료',
          startTime: new Date(today.getTime() + stepIdx * 60 * 60 * 1000).toISOString(),
          endTime: new Date(today.getTime() + (stepIdx + 1) * 60 * 60 * 1000).toISOString(),
          worker: processConfig.workers[stepIdx % processConfig.workers.length],
        };
      });

      wo.status = '생산완료';
      wo.completedQty = wo.totalQty;
      wo.currentStep = '완료';

      // 작업일지 생성
      const workLog = createWorkLogData(wo, {
        completedQty: wo.totalQty,
        defectQty: 0,
        steps: wo.stepStatus,
        remarks: '',
      });

      workLog.status = '작성완료';
      wo.workLogNo = workLog.workLogNo;
      workLogs.push(workLog);
    });

    results.documents.workLogs = workLogs;
    log('작업완료', `작업일지 ${workLogs.length}건 생성: ${workLogs.map(wl => wl.workLogNo).join(', ')}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 6: 중간검사 (채번: PQC)
    // ═══════════════════════════════════════════════════════════
    log('중간검사', '공정별 중간검사 수행');

    const inspections = [];

    workOrders.forEach(wo => {
      const inspection = createInspectionData(wo, 'PQC', {
        passQty: wo.totalQty,
        failQty: 0,
        result: '합격',
        inspector: '김검사',
        items: {},
      });

      inspection.status = '검사완료';
      inspection.checkItems.forEach(item => {
        item.result = '합격';
        item.status = '검사완료';
      });

      inspections.push(inspection);
    });

    results.documents.pqcInspections = inspections;
    log('중간검사완료', `${inspections.length}건 합격: ${inspections.map(ins => ins.inspectionNo).join(', ')}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 7: 입금확인 (계약금 30%)
    // ═══════════════════════════════════════════════════════════
    log('입금확인', '계약금 입금 처리');

    const depositAmount = Math.floor(order.totalAmount * 0.3);
    const deposit = {
      id: Date.now() + 200,
      depositNo: generateDocNo('DEP', today),
      depositDate: today.toISOString().split('T')[0],
      orderId: order.id,
      orderNo: order.orderNo,
      customerId: customer.id,
      customerName: customer.customerName,
      depositType: '계약금',
      depositAmount,
      bankName: '우리은행',
      accountNo: '1005-XXX-XXXXXX',
      status: '입금완료',
      createdAt: today.toISOString(),
    };

    results.documents.deposit = deposit;
    log('입금완료', `계약금 ${depositAmount.toLocaleString()}원 입금`);

    // ═══════════════════════════════════════════════════════════
    // STEP 8: 출하 처리 (채번: SL)
    // ═══════════════════════════════════════════════════════════
    log('출하처리', '출하지시 및 배송');

    const shipmentNo = generateDocNo('SL', today);
    const shipment = {
      id: Date.now() + 300,
      shipmentNo,
      shipmentDate: today.toISOString().split('T')[0],
      status: '출하완료',

      // 연결정보
      orderId: order.id,
      orderNo: order.orderNo,
      workOrderIds: workOrders.map(wo => wo.id),
      workOrderNos: workOrders.map(wo => wo.workOrderNo),

      // 고객/현장
      customerId: customer.id,
      customerName: customer.customerName,
      siteId: site.id,
      siteName: site.siteName,
      deliveryAddress: site.address,

      // 제품정보
      productName: order.productName,
      productSpec: order.productSpec,
      lotNos: workOrders.map(wo => wo.lotNo),

      // 수량
      shipmentQty: qty,

      // 배송정보
      deliveryType: '직배송',
      vehicleNo: '12가3456',
      driverName: '이배송',
      receiverName: site.siteManager,
      receiverPhone: site.managerPhone,

      createdAt: today.toISOString(),
    };

    results.documents.shipment = shipment;
    log('출하완료', `출하번호: ${shipmentNo}, 배송지: ${site.siteName}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 9: 고객 검사요청
    // ═══════════════════════════════════════════════════════════
    log('검사요청', '고객 검사 요청');

    const inspectionRequest = {
      id: Date.now() + 400,
      requestNo: generateDocNo('FQC-REQ', today),
      requestDate: today.toISOString().split('T')[0],
      shipmentId: shipment.id,
      shipmentNo: shipment.shipmentNo,
      customerId: customer.id,
      customerName: customer.customerName,
      siteName: site.siteName,
      productName: order.productName,
      productSpec: order.productSpec,
      qty,
      requestedDate: new Date(today.getTime() + 3 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      status: '요청완료',
      createdAt: today.toISOString(),
    };

    results.documents.inspectionRequest = inspectionRequest;
    log('검사요청완료', `검사요청번호: ${inspectionRequest.requestNo}`);

    // ═══════════════════════════════════════════════════════════
    // STEP 10: 최종검사 (채번: FQC)
    // ═══════════════════════════════════════════════════════════
    log('최종검사', '최종 품질검사 수행');

    const finalInspection = createInspectionData(workOrders[0], 'FQC', {
      passQty: qty,
      failQty: 0,
      result: '합격',
      inspector: '박품질',
      items: {},
    });

    finalInspection.status = '검사완료';
    finalInspection.checkItems.forEach(item => {
      item.result = '합격';
      item.status = '검사완료';
    });

    results.documents.finalInspection = finalInspection;
    log('최종검사완료', `검사번호: ${finalInspection.inspectionNo}, 결과: 합격`);

    // ═══════════════════════════════════════════════════════════
    // STEP 11: 매출 확정
    // ═══════════════════════════════════════════════════════════
    log('매출확정', '매출 확정 및 잔금 청구');

    const salesNo = generateDocNo('INV', today);
    const sales = {
      id: Date.now() + 500,
      salesNo,
      salesDate: today.toISOString().split('T')[0],

      // 연결정보
      orderId: order.id,
      orderNo: order.orderNo,
      shipmentId: shipment.id,
      shipmentNo: shipment.shipmentNo,
      inspectionId: finalInspection.id,
      inspectionNo: finalInspection.inspectionNo,

      // 고객정보
      customerId: customer.id,
      customerName: customer.customerName,
      siteName: site.siteName,

      // 금액정보
      supplyAmount: Math.floor(order.totalAmount / 1.1),
      vatAmount: Math.floor(order.totalAmount - order.totalAmount / 1.1),
      totalAmount: order.totalAmount,
      depositAmount: deposit.depositAmount,
      remainingAmount: order.totalAmount - deposit.depositAmount,

      // 상태
      status: '청구완료',
      invoiceDate: today.toISOString().split('T')[0],
      createdAt: today.toISOString(),
    };

    results.documents.sales = sales;
    log('매출확정완료', `매출번호: ${salesNo}, 잔금: ${sales.remainingAmount.toLocaleString()}원`);

    // ═══════════════════════════════════════════════════════════
    // 결과 요약
    // ═══════════════════════════════════════════════════════════
    results.summary = {
      quoteNo: quote.quoteNo,
      orderNo: order.orderNo,
      workOrderCount: workOrders.length,
      workOrderNos: workOrders.map(wo => wo.workOrderNo),
      workLogNos: workLogs.map(wl => wl.workLogNo),
      productionLotNos: workOrders.filter(wo => wo.productionLotNo).map(wo => wo.productionLotNo),
      incomingLotNos: materialReceipts.map(r => r.lotNo),
      inspectionNos: [...inspections.map(i => i.inspectionNo), finalInspection.inspectionNo],
      shipmentNo: shipment.shipmentNo,
      salesNo: sales.salesNo,
      totalAmount: order.totalAmount,
      depositAmount: deposit.depositAmount,
      remainingAmount: sales.remainingAmount,
    };

    log('테스트완료', '전체 프로세스 성공!');

  } catch (error) {
    results.success = false;
    results.errors.push({ error: error.message, stack: error.stack });
    console.error(`[테스트#${testNo}] 오류:`, error);
  }

  return results;
};

// ============================================================
// 9. 마스터 데이터 (10개씩)
// ============================================================

export const masterData = {
  // 거래처 10개
  customers: [
    { id: 1, customerCode: 'C-001', customerName: '삼성물산(주)', businessNo: '124-81-00998', ceoName: '오세철', contactName: '김철수', contactPhone: '02-2145-5114', email: 'sales@samsung.co.kr', address: '서울시 강남구 삼성동 159', paymentTerms: '월말마감 익월15일', creditLimit: 500000000, status: '활성' },
    { id: 2, customerCode: 'C-002', customerName: '현대건설(주)', businessNo: '101-81-03810', ceoName: '윤영준', contactName: '박영희', contactPhone: '02-746-1114', email: 'const@hdec.co.kr', address: '서울시 종로구 율곡로 75', paymentTerms: '월말마감 익월말', creditLimit: 800000000, status: '활성' },
    { id: 3, customerCode: 'C-003', customerName: 'GS건설(주)', businessNo: '104-81-17992', ceoName: '허윤홍', contactName: '이정민', contactPhone: '02-728-1114', email: 'biz@gsconst.co.kr', address: '서울시 강남구 논현로 508', paymentTerms: '월말마감 익월15일', creditLimit: 600000000, status: '활성' },
    { id: 4, customerCode: 'C-004', customerName: '대우건설(주)', businessNo: '117-81-16765', ceoName: '백정완', contactName: '최민수', contactPhone: '02-2288-3500', email: 'sales@dwconst.co.kr', address: '서울시 중구 을지로 170', paymentTerms: '월말마감 익월말', creditLimit: 400000000, status: '활성' },
    { id: 5, customerCode: 'C-005', customerName: '롯데건설(주)', businessNo: '110-81-07367', ceoName: '하석주', contactName: '정수진', contactPhone: '02-2118-2114', email: 'contact@lotteconst.co.kr', address: '서울시 송파구 올림픽로 300', paymentTerms: '월말마감 익월20일', creditLimit: 550000000, status: '활성' },
    { id: 6, customerCode: 'C-006', customerName: '포스코건설(주)', businessNo: '201-81-32456', ceoName: '한성희', contactName: '강동원', contactPhone: '02-3457-1000', email: 'order@poscoenc.com', address: '인천시 연수구 컨벤시아대로 165', paymentTerms: '월말마감 익월15일', creditLimit: 700000000, status: '활성' },
    { id: 7, customerCode: 'C-007', customerName: '호반건설(주)', businessNo: '134-81-09876', ceoName: '김상열', contactName: '이미영', contactPhone: '062-600-7777', email: 'sales@hoban.co.kr', address: '광주시 서구 상무중앙로 110', paymentTerms: '월말마감 익월말', creditLimit: 450000000, status: '활성' },
    { id: 8, customerCode: 'C-008', customerName: '한화건설(주)', businessNo: '108-81-33333', ceoName: '최광호', contactName: '박준혁', contactPhone: '02-729-1114', email: 'const@hanwha.com', address: '서울시 중구 청계천로 86', paymentTerms: '월말마감 익월15일', creditLimit: 480000000, status: '활성' },
    { id: 9, customerCode: 'C-009', customerName: '태영건설(주)', businessNo: '125-81-22222', ceoName: '윤세영', contactName: '김하늘', contactPhone: '02-2630-3114', email: 'taeyoung@tyenc.co.kr', address: '서울시 영등포구 여의대로 108', paymentTerms: '월말마감 익월말', creditLimit: 380000000, status: '활성' },
    { id: 10, customerCode: 'C-010', customerName: '두산건설(주)', businessNo: '142-81-11111', ceoName: '김정환', contactName: '오지현', contactPhone: '02-3398-3398', email: 'doosan@doosanenc.com', address: '서울시 중구 을지로6가 18-12', paymentTerms: '월말마감 익월20일', creditLimit: 420000000, status: '활성' },
  ],

  // 현장 10개
  sites: [
    { id: 1, siteCode: 'S-001', siteName: '래미안 강남 포레스트', customerId: 1, customerName: '삼성물산(주)', address: '서울시 강남구 개포동 12-1', siteManager: '김현장', managerPhone: '010-1234-5678', totalUnits: 850, status: '진행중' },
    { id: 2, siteCode: 'S-002', siteName: '힐스테이트 판교 센트럴', customerId: 2, customerName: '현대건설(주)', address: '경기도 성남시 분당구 판교동 789', siteManager: '박건축', managerPhone: '010-2345-6789', totalUnits: 1200, status: '진행중' },
    { id: 3, siteCode: 'S-003', siteName: '자이 위례 에듀파크', customerId: 3, customerName: 'GS건설(주)', address: '경기도 성남시 수정구 위례동 456', siteManager: '이시공', managerPhone: '010-3456-7890', totalUnits: 680, status: '진행중' },
    { id: 4, siteCode: 'S-004', siteName: '푸르지오 송도 마리나시티', customerId: 4, customerName: '대우건설(주)', address: '인천시 연수구 송도동 123', siteManager: '최대리', managerPhone: '010-4567-8901', totalUnits: 1500, status: '진행중' },
    { id: 5, siteCode: 'S-005', siteName: '롯데캐슬 동탄 파크타운', customerId: 5, customerName: '롯데건설(주)', address: '경기도 화성시 동탄면 789-12', siteManager: '정과장', managerPhone: '010-5678-9012', totalUnits: 2200, status: '진행중' },
    { id: 6, siteCode: 'S-006', siteName: '더샵 청라 레이크파크', customerId: 6, customerName: '포스코건설(주)', address: '인천시 서구 청라동 456', siteManager: '강팀장', managerPhone: '010-6789-0123', totalUnits: 1100, status: '진행중' },
    { id: 7, siteCode: 'S-007', siteName: '호반써밋 광교중앙역', customerId: 7, customerName: '호반건설(주)', address: '경기도 수원시 영통구 이의동 123', siteManager: '이매니저', managerPhone: '010-7890-1234', totalUnits: 900, status: '진행중' },
    { id: 8, siteCode: 'S-008', siteName: '포레나 수지 힐스테이트', customerId: 8, customerName: '한화건설(주)', address: '경기도 용인시 수지구 풍덕천동 789', siteManager: '박차장', managerPhone: '010-8901-2345', totalUnits: 750, status: '진행중' },
    { id: 9, siteCode: 'S-009', siteName: '데시앙 동탄 2차', customerId: 9, customerName: '태영건설(주)', address: '경기도 화성시 동탄2동 456', siteManager: '김부장', managerPhone: '010-9012-3456', totalUnits: 620, status: '진행중' },
    { id: 10, siteCode: 'S-010', siteName: '위브 청라 시티뷰', customerId: 10, customerName: '두산건설(주)', address: '인천시 서구 청라동 789', siteManager: '오실장', managerPhone: '010-0123-4567', totalUnits: 550, status: '진행중' },
  ],

  // 제품 10개
  products: [
    { id: 1, itemCode: '방화셔터 W3000×H3000', itemName: '방화셔터 W3000×H3000', itemType: '제품', productType: '스크린', spec: 'W3000×H3000', unit: 'SET', standardPrice: 2850000 },
    { id: 2, itemCode: '방화셔터 W3500×H4000', itemName: '방화셔터 W3500×H4000', itemType: '제품', productType: '스크린', spec: 'W3500×H4000', unit: 'SET', standardPrice: 3650000 },
    { id: 3, itemCode: '방화셔터(철재) W2500×H3000', itemName: '방화셔터(철재) W2500×H3000', itemType: '제품', productType: '철재', spec: 'W2500×H3000', unit: 'SET', standardPrice: 3200000 },
    { id: 4, itemCode: '방화셔터 W4000×H4500', itemName: '방화셔터 W4000×H4500', itemType: '제품', productType: '스크린', spec: 'W4000×H4500', unit: 'SET', standardPrice: 4250000 },
    { id: 5, itemCode: '방화셔터(철재) W3000×H3500', itemName: '방화셔터(철재) W3000×H3500', itemType: '제품', productType: '철재', spec: 'W3000×H3500', unit: 'SET', standardPrice: 3850000 },
    { id: 6, itemCode: '방화셔터 W2500×H2800', itemName: '방화셔터 W2500×H2800', itemType: '제품', productType: '스크린', spec: 'W2500×H2800', unit: 'SET', standardPrice: 2450000 },
    { id: 7, itemCode: '방화셔터 W5000×H5000', itemName: '방화셔터 W5000×H5000', itemType: '제품', productType: '스크린', spec: 'W5000×H5000', unit: 'SET', standardPrice: 5200000 },
    { id: 8, itemCode: '방화셔터(철재) W4000×H4000', itemName: '방화셔터(철재) W4000×H4000', itemType: '제품', productType: '철재', spec: 'W4000×H4000', unit: 'SET', standardPrice: 4650000 },
    { id: 9, itemCode: '방화셔터 W3200×H3600', itemName: '방화셔터 W3200×H3600', itemType: '제품', productType: '스크린', spec: 'W3200×H3600', unit: 'SET', standardPrice: 3150000 },
    { id: 10, itemCode: '방화셔터(철재) W3500×H3800', itemName: '방화셔터(철재) W3500×H3800', itemType: '제품', productType: '철재', spec: 'W3500×H3800', unit: 'SET', standardPrice: 4050000 },
  ],

  // 원자재 10개
  rawMaterials: [
    { id: 101, itemCode: '철판-EGI-1.2T', itemName: '아연도금강판', itemType: '원자재', spec: 'EGI 1.2T 4×8', unit: 'EA', standardPrice: 85000, supplier: '포스코', safetyStock: 50 },
    { id: 102, itemCode: '철판-EGI-1.6T', itemName: '아연도금강판', itemType: '원자재', spec: 'EGI 1.6T 4×8', unit: 'EA', standardPrice: 115000, supplier: '포스코', safetyStock: 30 },
    { id: 103, itemCode: '스크린원단-0.5T', itemName: '스크린 원단', itemType: '원자재', spec: '0.5T W1200', unit: 'M', standardPrice: 15000, supplier: '대한섬유', safetyStock: 500 },
    { id: 104, itemCode: '슬랫코일-50mm', itemName: '슬랫 코일', itemType: '원자재', spec: '50mm 백색', unit: 'KG', standardPrice: 4500, supplier: '한국알루미늄', safetyStock: 1000 },
    { id: 105, itemCode: '철판-SUS-1.0T', itemName: '스테인리스판', itemType: '원자재', spec: 'SUS304 1.0T', unit: 'EA', standardPrice: 180000, supplier: '포스코', safetyStock: 20 },
    { id: 106, itemCode: '철판-EGI-2.0T', itemName: '아연도금강판', itemType: '원자재', spec: 'EGI 2.0T 4×8', unit: 'EA', standardPrice: 145000, supplier: '포스코', safetyStock: 25 },
    { id: 107, itemCode: '스크린원단-0.3T', itemName: '스크린 원단(얇은형)', itemType: '원자재', spec: '0.3T W1200', unit: 'M', standardPrice: 12000, supplier: '대한섬유', safetyStock: 300 },
    { id: 108, itemCode: '슬랫코일-75mm', itemName: '슬랫 코일(대형)', itemType: '원자재', spec: '75mm 백색', unit: 'KG', standardPrice: 5500, supplier: '한국알루미늄', safetyStock: 800 },
    { id: 109, itemCode: '철판-SUS-1.5T', itemName: '스테인리스판(두꺼운)', itemType: '원자재', spec: 'SUS304 1.5T', unit: 'EA', standardPrice: 250000, supplier: '포스코', safetyStock: 15 },
    { id: 110, itemCode: '각파이프-50×50', itemName: '각파이프', itemType: '원자재', spec: '50×50 t2.0', unit: 'EA', standardPrice: 35000, supplier: '한국철강', safetyStock: 100 },
  ],

  // 부품 10개
  parts: [
    { id: 201, itemCode: '전동개폐기-380V300KG', itemName: '전동개폐기', itemType: '부품', subType: '구매 부품', spec: '380V 300KG', unit: 'EA', standardPrice: 350000, supplier: '동양전기' },
    { id: 202, itemCode: '전동개폐기-380V500KG', itemName: '전동개폐기', itemType: '부품', subType: '구매 부품', spec: '380V 500KG', unit: 'EA', standardPrice: 480000, supplier: '동양전기' },
    { id: 203, itemCode: '연동제어기-매립(유선)', itemName: '연동제어기', itemType: '부품', subType: '구매 부품', spec: '매립(유선)', unit: 'EA', standardPrice: 65000, supplier: '세진전자' },
    { id: 204, itemCode: '브라켓-380×180', itemName: '브라켓', itemType: '부품', subType: '구매 부품', spec: '380×180', unit: 'SET', standardPrice: 25000, supplier: '한국철강' },
    { id: 205, itemCode: '감기샤프트-5인치-L4500', itemName: '감기샤프트', itemType: '부품', subType: '구매 부품', spec: '5인치 L4500', unit: 'EA', standardPrice: 120000, supplier: '대한샤프트' },
    { id: 206, itemCode: 'RM24', itemName: '가이드레일(벽면형)-본체', itemType: '부품', subType: '절곡 부품', spec: 'L2438', unit: 'EA', standardPrice: 45000, processType: '절곡' },
    { id: 207, itemCode: 'RM30', itemName: '가이드레일(벽면형)-본체', itemType: '부품', subType: '절곡 부품', spec: 'L3000', unit: 'EA', standardPrice: 52000, processType: '절곡' },
    { id: 208, itemCode: 'CF24', itemName: '케이스-전면부', itemType: '부품', subType: '절곡 부품', spec: 'L2438', unit: 'EA', standardPrice: 85000, processType: '절곡' },
    { id: 209, itemCode: '개폐기조립체-300KG', itemName: '개폐기조립체', itemType: '부품', subType: '조립 부품', spec: '300KG형', unit: 'SET', standardPrice: 450000, processType: '조립' },
    { id: 210, itemCode: '제어반조립체-매립형', itemName: '제어반조립체', itemType: '부품', subType: '조립 부품', spec: '매립형', unit: 'SET', standardPrice: 120000, processType: '조립' },
  ],

  // 소모품 10개
  consumables: [
    { id: 301, itemCode: '용접봉-3.2MM', itemName: '용접봉', itemType: '소모품', spec: '3.2mm 일반용', unit: 'KG', standardPrice: 8500, supplier: '한국용접' },
    { id: 302, itemCode: '실리콘-백색', itemName: '실리콘', itemType: '소모품', spec: '백색 280ml', unit: 'EA', standardPrice: 3500, supplier: '한국실리콘' },
    { id: 303, itemCode: '도장-회색', itemName: '스프레이 도장', itemType: '소모품', spec: '회색 400ml', unit: 'EA', standardPrice: 6500, supplier: '한국도료' },
    { id: 304, itemCode: '장갑-면장갑', itemName: '면장갑', itemType: '소모품', spec: '표준형', unit: '켤레', standardPrice: 800, supplier: '안전용품' },
    { id: 305, itemCode: '테이프-포장용', itemName: '포장테이프', itemType: '소모품', spec: '48mm×50M', unit: 'EA', standardPrice: 2500, supplier: '한국포장' },
    { id: 306, itemCode: '연마지-80번', itemName: '연마지', itemType: '소모품', spec: '80번', unit: '장', standardPrice: 500, supplier: '한국연마' },
    { id: 307, itemCode: '절삭유-범용', itemName: '절삭유', itemType: '소모품', spec: '20L', unit: '캔', standardPrice: 45000, supplier: '한국오일' },
    { id: 308, itemCode: '마스킹테이프', itemName: '마스킹테이프', itemType: '소모품', spec: '24mm×18M', unit: 'EA', standardPrice: 1800, supplier: '한국포장' },
    { id: 309, itemCode: '안전화-표준', itemName: '안전화', itemType: '소모품', spec: '표준형', unit: '켤레', standardPrice: 35000, supplier: '안전용품' },
    { id: 310, itemCode: '보안경-투명', itemName: '보안경', itemType: '소모품', spec: '투명', unit: 'EA', standardPrice: 8000, supplier: '안전용품' },
  ],
};

/**
 * 10건 전체 통합 테스트 실행
 */
export const runAllTests = () => {
  console.log('═══════════════════════════════════════════════════════════════');
  console.log('  MES 완전 통합 테스트 시작 (10건)');
  console.log('  채번규칙 + 공통코드 + LOT관리 + 문서양식 연동 검증');
  console.log('═══════════════════════════════════════════════════════════════');

  // 시퀀스 초기화
  resetAllSequences();

  const testCases = [
    { openWidth: 3000, openHeight: 3000, productType: '스크린', qty: 2 },
    { openWidth: 3500, openHeight: 4000, productType: '스크린', qty: 3 },
    { openWidth: 2500, openHeight: 3000, productType: '철재', qty: 1 },
    { openWidth: 4000, openHeight: 4500, productType: '스크린', qty: 4 },
    { openWidth: 3000, openHeight: 3500, productType: '철재', qty: 2 },
    { openWidth: 2500, openHeight: 2800, productType: '스크린', qty: 5 },
    { openWidth: 5000, openHeight: 5000, productType: '스크린', qty: 1 },
    { openWidth: 4000, openHeight: 4000, productType: '철재', qty: 3 },
    { openWidth: 3200, openHeight: 3600, productType: '스크린', qty: 2 },
    { openWidth: 3500, openHeight: 3800, productType: '철재', qty: 2 },
  ];

  const results = [];

  testCases.forEach((testCase, index) => {
    const customer = masterData.customers[index];
    const site = masterData.sites[index];

    console.log(`\n─── 테스트 #${index + 1} 시작: ${customer.customerName} - ${site.siteName} ───`);

    const result = runCompleteProcess({
      customer,
      site,
      ...testCase,
      testNo: index + 1,
    });

    results.push(result);
  });

  // 결과 요약
  const summary = {
    totalTests: results.length,
    successCount: results.filter(r => r.success).length,
    failCount: results.filter(r => !r.success).length,
    results: results.map(r => ({
      testNo: r.testNo,
      success: r.success,
      summary: r.summary,
      errors: r.errors,
    })),
  };

  console.log('\n═══════════════════════════════════════════════════════════════');
  console.log('  통합 테스트 결과 요약');
  console.log('═══════════════════════════════════════════════════════════════');
  console.log(`  총 테스트: ${summary.totalTests}건`);
  console.log(`  성공: ${summary.successCount}건`);
  console.log(`  실패: ${summary.failCount}건`);

  return { results, summary };
};

export default {
  // 채번관리 (문서번호)
  generateDocNo,
  resetAllSequences,

  // 공통코드 (LOT번호)
  generateIncomingLotNo,
  generateProductionLotNo,
  generateItemCodeAuto,

  // 자재관리
  createMaterialReceipt,
  createMaterialIssue,

  // BOM 계산
  calculateProductionSize,
  calculateAreaWeight,
  lookupMotorCapacity,
  calculateFullBOM,

  // 공정관리
  processWorkflows,

  // 문서양식
  getWorkLogTemplate,
  createWorkLogData,
  getInspectionTemplate,
  createInspectionData,

  // 통합 프로세스
  runCompleteProcess,
  runAllTests,

  // 마스터 데이터
  masterData,
};
