-- =====================================================
-- MDM 主数据迁移 - 第二阶段：物料数据迁移
-- 执行顺序：先执行第一阶段 SQL
-- 适用场景：新项目初始化，无历史业务数据
-- =====================================================

-- =====================================================
-- 01. 迁移 MES 物料数据
-- =====================================================

-- MES 物料类型为 itemType=1（物料）
INSERT INTO mdm_item (id, code, name, bar_code, specification, category_id, unit_measure_id, brand_id,
    item_type, status, purchase_price, sales_price, cost_price, min_price, safety_stock, min_stock, max_stock,
    min_order_qty, lead_time, is_batch_managed, is_serial_managed, barcode_rule_id, expiry_day, high_value,
    weight, remark, creator, create_time, updater, update_time, deleted)
SELECT
    m.id AS id,
    m.code,
    m.name,
    NULL AS bar_code,  -- MES 物料没有条码字段
    m.specification,
    -- MES 分类ID偏移了10000
    m.item_type_id + 10000 AS category_id,
    -- MES 单位ID偏移了1000
    m.unit_measure_id + 1000 AS unit_measure_id,
    NULL AS brand_id,
    1 AS item_type,  -- 物料类型
    m.status,
    NULL AS purchase_price,
    NULL AS sales_price,
    NULL AS cost_price,
    NULL AS min_price,
    NULL AS safety_stock,
    m.min_stock,
    m.max_stock,
    NULL AS min_order_qty,
    NULL AS lead_time,
    COALESCE(m.batch_flag, FALSE) AS is_batch_managed,
    FALSE AS is_serial_managed,
    NULL AS barcode_rule_id,
    NULL AS expiry_day,
    COALESCE(m.high_value, FALSE) AS high_value,
    NULL AS weight,
    m.remark,
    '1' AS creator,
    m.create_time,
    '1' AS updater,
    m.update_time,
    0 AS deleted
FROM mes_md_item m
WHERE m.deleted = 0
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    code = VALUES(code);

-- =====================================================
-- 02. 迁移 ERP 产品数据
-- =====================================================

-- ERP 产品类型为 itemType=2（产品）
INSERT INTO mdm_item (id, code, name, bar_code, specification, category_id, unit_measure_id, brand_id,
    item_type, status, purchase_price, sales_price, cost_price, min_price, safety_stock, min_stock, max_stock,
    min_order_qty, lead_time, is_batch_managed, is_serial_managed, barcode_rule_id, expiry_day, high_value,
    weight, remark, creator, create_time, updater, update_time, deleted)
SELECT
    p.id AS id,
    p.bar_code AS code,  -- ERP 使用条码作为编码
    p.name,
    p.bar_code,
    p.standard AS specification,
    -- ERP 分类ID无偏移
    p.category_id,
    -- ERP 单位ID偏移了100
    p.unit_id + 100 AS unit_measure_id,
    NULL AS brand_id,
    2 AS item_type,  -- 产品类型
    p.status,
    p.purchase_price,
    p.sale_price AS sales_price,
    NULL AS cost_price,
    p.min_price,
    NULL AS safety_stock,
    NULL AS min_stock,
    NULL AS max_stock,
    NULL AS min_order_qty,
    NULL AS lead_time,
    FALSE AS is_batch_managed,
    FALSE AS is_serial_managed,
    NULL AS barcode_rule_id,
    p.expiry_day,
    FALSE AS high_value,
    p.weight,
    p.remark,
    '1' AS creator,
    p.create_time,
    '1' AS updater,
    p.update_time,
    0 AS deleted
FROM erp_product p
WHERE p.deleted = 0
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    bar_code = VALUES(bar_code);

-- =====================================================
-- 03. 迁移 WMS 商品数据
-- =====================================================

-- WMS 商品类型为 itemType=1（物料）
-- 注意：WMS 商品的 unit 字段是字符串，需要匹配 MDM 单位名称，找不到则使用默认单位（id=1）
INSERT INTO mdm_item (id, code, name, bar_code, specification, category_id, unit_measure_id, brand_id,
    item_type, status, purchase_price, sales_price, cost_price, min_price, safety_stock, min_stock, max_stock,
    min_order_qty, lead_time, is_batch_managed, is_serial_managed, barcode_rule_id, expiry_day, high_value,
    weight, remark, creator, create_time, updater, update_time, deleted)
SELECT
    w.id + 30000 AS id,  -- WMS 商品ID偏移30000避免冲突
    w.code,
    w.name,
    NULL AS bar_code,
    NULL AS specification,
    -- WMS 分类ID偏移了20000
    w.category_id + 20000 AS category_id,
    -- WMS 商品单位为字符串，需匹配MDM单位名称，找不到则使用默认单位
    COALESCE(
        (SELECT id FROM mdm_unit_measure WHERE name = w.unit AND deleted = 0 LIMIT 1),
        1  -- 默认单位ID
    ) AS unit_measure_id,
    -- WMS 品牌ID无偏移
    w.brand_id,
    1 AS item_type,  -- 默认物料类型
    0 AS status,  -- 默认启用
    NULL AS purchase_price,
    NULL AS sales_price,
    NULL AS cost_price,
    NULL AS min_price,
    NULL AS safety_stock,
    NULL AS min_stock,
    NULL AS max_stock,
    NULL AS min_order_qty,
    NULL AS lead_time,
    FALSE AS is_batch_managed,
    FALSE AS is_serial_managed,
    NULL AS barcode_rule_id,
    NULL AS expiry_day,
    FALSE AS high_value,
    NULL AS weight,
    w.remark,
    '1' AS creator,
    w.create_time,
    '1' AS updater,
    w.update_time,
    0 AS deleted
FROM wms_item w
WHERE w.deleted = 0
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    code = VALUES(code);

-- =====================================================
-- 04. 迁移 WMS SKU 数据并创建 MDM SKU
-- =====================================================

-- 迁移 WMS SKU 到 MDM SKU
INSERT INTO mdm_item_sku (id, item_id, code, name, bar_code, length, width, height,
    gross_weight, net_weight, cost_price, sale_price, status, remark,
    creator, create_time, updater, update_time, deleted)
SELECT
    s.id + 40000 AS id,  -- SKU ID偏移40000避免冲突
    -- WMS 商品ID偏移了30000
    s.item_id + 30000 AS item_id,
    s.code,
    s.name,
    s.bar_code,
    s.length,
    s.width,
    s.height,
    s.gross_weight,
    s.net_weight,
    s.cost_price,
    s.selling_price AS sale_price,
    0 AS status,
    NULL AS remark,
    '1' AS creator,
    s.create_time,
    '1' AS updater,
    s.update_time,
    0 AS deleted
FROM wms_item_sku s
WHERE s.deleted = 0
ON DUPLICATE KEY UPDATE
    name = VALUES(name),
    code = VALUES(code);

-- =====================================================
-- 05. 为 MES/ERP 物料创建默认 SKU
-- =====================================================

-- 为 MES 物料创建默认 SKU（如果不存在）
INSERT INTO mdm_item_sku (item_id, code, name, bar_code, length, width, height,
    gross_weight, net_weight, cost_price, sale_price, status, remark,
    creator, create_time, updater, update_time, deleted)
SELECT
    m.id AS item_id,
    CONCAT(m.code, '-DEFAULT') AS code,
    CONCAT(m.name, '-默认SKU') AS name,
    NULL AS bar_code,
    NULL AS length,
    NULL AS width,
    NULL AS height,
    NULL AS gross_weight,
    NULL AS net_weight,
    NULL AS cost_price,
    NULL AS sale_price,
    0 AS status,
    '系统自动创建' AS remark,
    '1' AS creator,
    NOW() AS create_time,
    '1' AS updater,
    NOW() AS update_time,
    0 AS deleted
FROM mdm_item m
WHERE m.item_type = 1  -- MES 物料
  AND m.deleted = 0
  AND m.id < 30000  -- 排除 WMS 商品（已有 SKU）
  AND NOT EXISTS (
      SELECT 1 FROM mdm_item_sku s WHERE s.item_id = m.id AND s.deleted = 0
  );

-- 为 ERP 产品创建默认 SKU（如果不存在）
INSERT INTO mdm_item_sku (item_id, code, name, bar_code, length, width, height,
    gross_weight, net_weight, cost_price, sale_price, status, remark,
    creator, create_time, updater, update_time, deleted)
SELECT
    p.id AS item_id,
    CONCAT(p.bar_code, '-DEFAULT') AS code,
    CONCAT(p.name, '-默认SKU') AS name,
    p.bar_code,
    NULL AS length,
    NULL AS width,
    NULL AS height,
    NULL AS gross_weight,
    NULL AS net_weight,
    NULL AS cost_price,
    NULL AS sale_price,
    0 AS status,
    '系统自动创建' AS remark,
    '1' AS creator,
    NOW() AS create_time,
    '1' AS updater,
    NOW() AS update_time,
    0 AS deleted
FROM mdm_item p
WHERE p.item_type = 2  -- ERP 产品
  AND p.deleted = 0
  AND NOT EXISTS (
      SELECT 1 FROM mdm_item_sku s WHERE s.item_id = p.id AND s.deleted = 0
  );

-- =====================================================
-- 06. 数据验证
-- =====================================================

-- 验证物料数据迁移
SELECT 'MES物料迁移' AS source,
       (SELECT COUNT(*) FROM mes_md_item WHERE deleted = 0) AS original_count,
       (SELECT COUNT(*) FROM mdm_item WHERE item_type = 1 AND id < 30000 AND deleted = 0) AS migrated_count;

SELECT 'ERP产品迁移' AS source,
       (SELECT COUNT(*) FROM erp_product WHERE deleted = 0) AS original_count,
       (SELECT COUNT(*) FROM mdm_item WHERE item_type = 2 AND deleted = 0) AS migrated_count;

SELECT 'WMS商品迁移' AS source,
       (SELECT COUNT(*) FROM wms_item WHERE deleted = 0) AS original_count,
       (SELECT COUNT(*) FROM mdm_item WHERE id >= 30000 AND deleted = 0) AS migrated_count;

-- 验证 SKU 数据
SELECT 'SKU总数' AS metric, COUNT(*) AS count FROM mdm_item_sku WHERE deleted = 0;
SELECT '有SKU的物料数' AS metric, COUNT(DISTINCT item_id) AS count FROM mdm_item_sku WHERE deleted = 0;

-- =====================================================
-- 07. 检查使用默认单位的 WMS 商品
-- =====================================================

-- 查看 WMS 商品中单位无法匹配的情况
SELECT w.id, w.code, w.name, w.unit
FROM wms_item w
WHERE w.deleted = 0
  AND NOT EXISTS (
      SELECT 1 FROM mdm_unit_measure u WHERE u.name = w.unit AND u.deleted = 0
  )
LIMIT 20;