// BOM (Bill of Materials) 관리 설정
// 상용 MES 대비 개선사항 Phase 2

/**
 * ═══════════════════════════════════════════════════════════════════
 * BOM (Bill of Materials) 자재명세서 관리
 * ═══════════════════════════════════════════════════════════════════
 *
 * 목적: 제품 생산에 필요한 자재/부품 구성 정보 관리
 *       - 제품별 소요 자재 목록
 *       - 수량 및 단위 정보
 *       - 대체 자재 정보
 *       - 원가 계산 기초 데이터
 *
 * ═══════════════════════════════════════════════════════════════════
 */

// BOM 유형 정의
export const bomTypes = {
  ENGINEERING: {
    code: 'ENGINEERING',
    name: '설계 BOM (E-BOM)',
    description: '설계 도면 기준 BOM',
    usage: '설계/개발 단계',
    color: 'bg-blue-100 text-blue-700',
  },
  MANUFACTURING: {
    code: 'MANUFACTURING',
    name: '제조 BOM (M-BOM)',
    description: '실제 생산 기준 BOM',
    usage: '생산 단계',
    color: 'bg-green-100 text-green-700',
  },
  PLANNING: {
    code: 'PLANNING',
    name: '계획 BOM (P-BOM)',
    description: '생산계획용 BOM',
    usage: 'MRP/계획 단계',
    color: 'bg-purple-100 text-purple-700',
  },
};

// BOM 레벨 정의
export const bomLevels = {
  0: { name: '완제품', description: '최종 출하 제품' },
  1: { name: '주요 반제품', description: '주요 조립품/반제품' },
  2: { name: '중간 반제품', description: '중간 조립품' },
  3: { name: '소조립품', description: '소형 조립품' },
  4: { name: '부품/자재', description: '원자재/구매부품' },
};

// 자재 구분
export const materialCategories = {
  MAKE: {
    code: 'MAKE',
    name: '자가제조',
    description: '내부 생산 품목',
    color: 'bg-blue-100 text-blue-700',
  },
  BUY: {
    code: 'BUY',
    name: '외부구매',
    description: '외부 구매 품목',
    color: 'bg-yellow-100 text-yellow-700',
  },
  PHANTOM: {
    code: 'PHANTOM',
    name: '가상품목',
    description: '중간 조립 단계 (재고 미관리)',
    color: 'bg-gray-100 text-gray-700',
  },
};

// 방화셔터 제품별 BOM 템플릿
export const productBomTemplates = {
  // 스크린 방화셔터 BOM
  'SCREEN_SHUTTER': {
    productCode: 'SCREEN_SHUTTER',
    productName: '스크린 방화셔터',
    bomType: 'MANUFACTURING',
    version: '1.0',
    components: [
      // Level 1: 주요 구성품
      {
        level: 1,
        itemCode: 'SCR-BODY',
        itemName: '본체 조립품',
        category: 'MAKE',
        quantity: 1,
        unit: 'SET',
        processCode: 'ASSEMBLY',
        children: [
          // Level 2: 본체 구성
          { level: 2, itemCode: 'SCR-CASE', itemName: '케이스', category: 'MAKE', quantity: 1, unit: 'EA' },
          { level: 2, itemCode: 'SCR-BRACKET', itemName: '브라켓', category: 'MAKE', quantity: 2, unit: 'EA' },
          { level: 2, itemCode: 'SCR-COVER', itemName: '커버', category: 'MAKE', quantity: 1, unit: 'EA' },
        ],
      },
      {
        level: 1,
        itemCode: 'SCR-SCREEN',
        itemName: '스크린 조립품',
        category: 'MAKE',
        quantity: 1,
        unit: 'SET',
        processCode: 'SCREEN',
        children: [
          { level: 2, itemCode: 'FB-001', itemName: '방화원단', category: 'BUY', quantity: 1, unit: 'M2', spec: '규격별 산출' },
          { level: 2, itemCode: 'SCR-ENDLOCK', itemName: '앤드락', category: 'BUY', quantity: 2, unit: 'EA' },
          { level: 2, itemCode: 'SCR-WEIGHT', itemName: '웨이트바', category: 'MAKE', quantity: 1, unit: 'EA' },
        ],
      },
      {
        level: 1,
        itemCode: 'SCR-DRIVE',
        itemName: '구동장치',
        category: 'BUY',
        quantity: 1,
        unit: 'SET',
        children: [
          { level: 2, itemCode: 'MTR-001', itemName: '전동개폐기', category: 'BUY', quantity: 1, unit: 'EA' },
          { level: 2, itemCode: 'CTL-001', itemName: '연동제어기', category: 'BUY', quantity: 1, unit: 'EA' },
          { level: 2, itemCode: 'SWT-001', itemName: '리미트스위치', category: 'BUY', quantity: 2, unit: 'EA' },
        ],
      },
      // Level 1: 부자재
      {
        level: 1,
        itemCode: 'SCR-FASTENER',
        itemName: '체결부품',
        category: 'PHANTOM',
        quantity: 1,
        unit: 'SET',
        children: [
          { level: 2, itemCode: 'BOLT-M8', itemName: 'M8 볼트', category: 'BUY', quantity: 20, unit: 'EA' },
          { level: 2, itemCode: 'NUT-M8', itemName: 'M8 너트', category: 'BUY', quantity: 20, unit: 'EA' },
          { level: 2, itemCode: 'RIVET-001', itemName: '리벳', category: 'BUY', quantity: 50, unit: 'EA' },
        ],
      },
    ],
  },

  // 슬랫 방화셔터 BOM
  'SLAT_SHUTTER': {
    productCode: 'SLAT_SHUTTER',
    productName: '슬랫 방화셔터',
    bomType: 'MANUFACTURING',
    version: '1.0',
    components: [
      {
        level: 1,
        itemCode: 'SLT-BODY',
        itemName: '본체 조립품',
        category: 'MAKE',
        quantity: 1,
        unit: 'SET',
        processCode: 'ASSEMBLY',
        children: [
          { level: 2, itemCode: 'SLT-CASE', itemName: '케이스', category: 'MAKE', quantity: 1, unit: 'EA' },
          { level: 2, itemCode: 'SLT-GUIDE', itemName: '가이드레일', category: 'MAKE', quantity: 2, unit: 'EA' },
        ],
      },
      {
        level: 1,
        itemCode: 'SLT-CURTAIN',
        itemName: '슬랫 커튼',
        category: 'MAKE',
        quantity: 1,
        unit: 'SET',
        processCode: 'SLAT',
        children: [
          { level: 2, itemCode: 'SLT-001', itemName: '슬랫', category: 'MAKE', quantity: 1, unit: 'SET', spec: '높이별 수량 산출' },
          { level: 2, itemCode: 'SLT-BOTTOM', itemName: '바텀바', category: 'MAKE', quantity: 1, unit: 'EA' },
        ],
      },
      {
        level: 1,
        itemCode: 'SLT-DRIVE',
        itemName: '구동장치',
        category: 'BUY',
        quantity: 1,
        unit: 'SET',
        children: [
          { level: 2, itemCode: 'MTR-002', itemName: '전동개폐기(슬랫용)', category: 'BUY', quantity: 1, unit: 'EA' },
          { level: 2, itemCode: 'CTL-001', itemName: '연동제어기', category: 'BUY', quantity: 1, unit: 'EA' },
        ],
      },
    ],
  },

  // 절곡 제품 BOM
  'FOLD_PRODUCT': {
    productCode: 'FOLD_PRODUCT',
    productName: '절곡 제품',
    bomType: 'MANUFACTURING',
    version: '1.0',
    components: [
      {
        level: 1,
        itemCode: 'FLD-MAIN',
        itemName: '절곡 본체',
        category: 'MAKE',
        quantity: 1,
        unit: 'EA',
        processCode: 'FOLD',
        children: [
          { level: 2, itemCode: 'STEEL-COIL', itemName: '스틸코일', category: 'BUY', quantity: 1, unit: 'KG', spec: '제품별 중량 산출' },
        ],
      },
    ],
  },
};

// BOM 테이블 컬럼 정의
export const bomTableColumns = [
  { key: 'level', label: 'LV', width: '50px', align: 'center' },
  { key: 'itemCode', label: '품목코드', width: '120px' },
  { key: 'itemName', label: '품목명', width: '200px' },
  { key: 'category', label: '구분', width: '80px', align: 'center' },
  { key: 'spec', label: '규격', width: '150px' },
  { key: 'quantity', label: '수량', width: '80px', align: 'right' },
  { key: 'unit', label: '단위', width: '60px', align: 'center' },
  { key: 'processCode', label: '공정', width: '100px' },
  { key: 'leadTime', label: 'L/T(일)', width: '70px', align: 'right' },
  { key: 'unitCost', label: '단가', width: '100px', align: 'right' },
  { key: 'totalCost', label: '합계', width: '100px', align: 'right' },
  { key: 'substitute', label: '대체품', width: '100px' },
  { key: 'note', label: '비고', width: '150px' },
];

/**
 * BOM 전개 (Explosion)
 * @param {object} bom - BOM 데이터
 * @param {number} quantity - 생산 수량
 * @returns {Array} 전개된 자재 소요량 목록
 */
export const explodeBom = (bom, quantity = 1) => {
  const result = [];
  const flattenComponents = (components, parentQty = 1, indent = 0) => {
    components.forEach(comp => {
      const totalQty = comp.quantity * parentQty * quantity;
      result.push({
        ...comp,
        indent,
        requiredQty: totalQty,
        displayLevel: '　'.repeat(indent) + (comp.level || ''),
      });
      if (comp.children && comp.children.length > 0) {
        flattenComponents(comp.children, comp.quantity * parentQty, indent + 1);
      }
    });
  };

  if (bom.components) {
    flattenComponents(bom.components);
  }

  return result;
};

/**
 * 자재 소요량 집계 (Summarized BOM)
 * @param {object} bom - BOM 데이터
 * @param {number} quantity - 생산 수량
 * @returns {Array} 품목별 총 소요량
 */
export const summarizeBom = (bom, quantity = 1) => {
  const summary = {};

  const collectMaterials = (components, parentQty = 1) => {
    components.forEach(comp => {
      // BUY 품목만 집계 (실제 구매 필요 자재)
      if (comp.category === 'BUY') {
        const key = comp.itemCode;
        if (!summary[key]) {
          summary[key] = {
            itemCode: comp.itemCode,
            itemName: comp.itemName,
            unit: comp.unit,
            totalQty: 0,
            locations: [],
          };
        }
        const qty = comp.quantity * parentQty * quantity;
        summary[key].totalQty += qty;
        summary[key].locations.push({
          parentItem: comp.parentItemName || 'Root',
          quantity: qty,
        });
      }
      if (comp.children && comp.children.length > 0) {
        collectMaterials(comp.children, comp.quantity * parentQty);
      }
    });
  };

  if (bom.components) {
    collectMaterials(bom.components);
  }

  return Object.values(summary).sort((a, b) => a.itemCode.localeCompare(b.itemCode));
};

/**
 * BOM 원가 계산
 * @param {object} bom - BOM 데이터
 * @param {object} unitCosts - 품목별 단가 { itemCode: cost }
 * @returns {object} 원가 내역
 */
export const calculateBomCost = (bom, unitCosts = {}) => {
  let materialCost = 0;
  let laborCost = 0;

  const calculateCosts = (components, parentQty = 1) => {
    components.forEach(comp => {
      const qty = comp.quantity * parentQty;
      const unitCost = unitCosts[comp.itemCode] || comp.unitCost || 0;

      if (comp.category === 'BUY') {
        materialCost += qty * unitCost;
      } else if (comp.category === 'MAKE') {
        // 자가제조품은 노무비로 계산 (가공비)
        laborCost += qty * (comp.laborCost || 0);
      }

      if (comp.children && comp.children.length > 0) {
        calculateCosts(comp.children, qty);
      }
    });
  };

  if (bom.components) {
    calculateCosts(bom.components);
  }

  const totalCost = materialCost + laborCost;

  return {
    materialCost,
    laborCost,
    totalCost,
    breakdown: {
      materialRate: totalCost > 0 ? Math.round(materialCost / totalCost * 100) : 0,
      laborRate: totalCost > 0 ? Math.round(laborCost / totalCost * 100) : 0,
    },
  };
};

/**
 * BOM 비교 (버전 비교)
 * @param {object} bomA - 비교 대상 BOM A
 * @param {object} bomB - 비교 대상 BOM B
 * @returns {object} 차이점 목록
 */
export const compareBoms = (bomA, bomB) => {
  const differences = {
    added: [],    // B에만 있는 품목
    removed: [],  // A에만 있는 품목
    changed: [],  // 수량 등 변경된 품목
  };

  const getItemMap = (bom) => {
    const map = {};
    const collect = (components) => {
      components.forEach(comp => {
        map[comp.itemCode] = comp;
        if (comp.children) collect(comp.children);
      });
    };
    if (bom.components) collect(bom.components);
    return map;
  };

  const mapA = getItemMap(bomA);
  const mapB = getItemMap(bomB);

  // B에만 있는 품목 (추가됨)
  Object.keys(mapB).forEach(code => {
    if (!mapA[code]) {
      differences.added.push(mapB[code]);
    }
  });

  // A에만 있는 품목 (삭제됨)
  Object.keys(mapA).forEach(code => {
    if (!mapB[code]) {
      differences.removed.push(mapA[code]);
    }
  });

  // 양쪽에 있지만 다른 품목
  Object.keys(mapA).forEach(code => {
    if (mapB[code]) {
      const a = mapA[code];
      const b = mapB[code];
      if (a.quantity !== b.quantity || a.unit !== b.unit) {
        differences.changed.push({
          itemCode: code,
          itemName: a.itemName,
          before: { quantity: a.quantity, unit: a.unit },
          after: { quantity: b.quantity, unit: b.unit },
        });
      }
    }
  });

  return differences;
};

/**
 * 역전개 (Where-Used)
 * @param {string} itemCode - 조회할 품목코드
 * @param {Array} allBoms - 전체 BOM 목록
 * @returns {Array} 해당 품목이 사용된 상위 품목 목록
 */
export const whereUsed = (itemCode, allBoms) => {
  const usageList = [];

  const searchInComponents = (components, productCode, productName, parentPath = []) => {
    components.forEach(comp => {
      if (comp.itemCode === itemCode) {
        usageList.push({
          productCode,
          productName,
          parentPath: [...parentPath],
          quantity: comp.quantity,
          unit: comp.unit,
        });
      }
      if (comp.children && comp.children.length > 0) {
        searchInComponents(comp.children, productCode, productName, [...parentPath, comp.itemName]);
      }
    });
  };

  allBoms.forEach(bom => {
    if (bom.components) {
      searchInComponents(bom.components, bom.productCode, bom.productName);
    }
  });

  return usageList;
};

export default {
  bomTypes,
  bomLevels,
  materialCategories,
  productBomTemplates,
  bomTableColumns,
  explodeBom,
  summarizeBom,
  calculateBomCost,
  compareBoms,
  whereUsed,
};
