-- Step 2: 填充 dim_material 从配送流水+盘点数据合并去重
-- 配送流水有1835种物料，盘点数据有6133种物料，合并去重

WITH merged AS (
  -- 配送流水中的物料
  SELECT item_code AS material_code, item_name AS material_name, specification, 
         major_category, minor_category, finance_category, unit AS base_unit,
         NULL::text AS supplier_code,
         row_number() OVER (PARTITION BY item_code ORDER BY 
           (minor_category IS NOT NULL AND minor_category != '')::int DESC,
           (finance_category IS NOT NULL AND finance_category != '')::int DESC,
           (specification IS NOT NULL AND specification != '')::int DESC
         ) AS rn
  FROM distribution_detail_records 
  WHERE item_code IS NOT NULL AND item_code != ''
  
  UNION ALL
  
  -- 盘点倒挤数据中的物料
  SELECT item_code AS material_code, item_name AS material_name, specification,
         major_category, minor_category, finance_category, unit AS base_unit,
         NULL::text AS supplier_code,
         row_number() OVER (PARTITION BY item_code ORDER BY 
           (minor_category IS NOT NULL AND minor_category != '')::int DESC,
           (finance_category IS NOT NULL AND finance_category != '')::int DESC,
           (specification IS NOT NULL AND specification != '')::int DESC
         ) AS rn
  FROM inventory_cost_records 
  WHERE item_code IS NOT NULL AND item_code != ''
),
best AS (
  SELECT DISTINCT ON (material_code) material_code, material_name, specification,
         major_category, minor_category, finance_category, base_unit, supplier_code
  FROM merged
  ORDER BY material_code, 
    (minor_category IS NOT NULL AND minor_category != '') DESC,
    (finance_category IS NOT NULL AND finance_category != '') DESC,
    (specification IS NOT NULL AND specification != '') DESC,
    (major_category IS NOT NULL AND major_category != '') DESC
)
INSERT INTO analytics.dim_material (material_code, material_name, specification, major_category, minor_category, finance_category, base_unit, supplier_code, status, created_at, updated_at)
SELECT material_code, material_name, specification, major_category, minor_category, finance_category, base_unit, supplier_code, '启用', now(), now()
FROM best
ON CONFLICT (material_code) DO UPDATE SET
  material_name = EXCLUDED.material_name,
  specification = COALESCE(NULLIF(EXCLUDED.specification, ''), dim_material.specification),
  major_category = COALESCE(NULLIF(EXCLUDED.major_category, ''), dim_material.major_category),
  minor_category = COALESCE(NULLIF(EXCLUDED.minor_category, ''), dim_material.minor_category),
  finance_category = COALESCE(NULLIF(EXCLUDED.finance_category, ''), dim_material.finance_category),
  base_unit = COALESCE(NULLIF(EXCLUDED.base_unit, ''), dim_material.base_unit),
  updated_at = now();
