-- AIDOP-S7-L1-001-DIMENSION-UI-DASHBOARD-CLOSEOUT-1：S7_L1_001 维度配置生产固化（幂等）。
-- 动态绑定当前生效 SUMMARY 配置（不写死 SummaryConfigId/dev Id）；已存在当前生效维度配置则整体跳过（杜绝双 Current）。
-- 若正式 SUMMARY 版本与预期不一致，不强行插入错误绑定：无当前维度配置才插，插入即绑定彼时真实 SUMMARY 版本。
-- 表列 PascalCase（EnableUnderLine=false）；SQL 来自已通过试点验证的订单维度实现，未改业务公式。
-- 幂等：NOT EXISTS(任一 IsCurrent=1 的 S7_L1_001 维度配置) 才插；重复执行影响行 0。

INSERT INTO ado_smart_ops_kpi_dimension_config
  (`TenantId`,`MetricCode`,`ModuleCode`,`SummaryConfigId`,`SummaryConfigVersion`,`DimensionConfigVersion`,
   `DataSourceCode`,`SqlScript`,`AggregationType`,`SupportedDimensionsJson`,`TimeoutSeconds`,
   `PublishStatus`,`IsCurrent`,`BusinessSqlSource`,`ChangeRemark`,`Remark`,`CreatedBy`,`CreatedAt`)
SELECT s.`TenantId`, 'S7_L1_001', 'S7', s.`Id`, s.`VersionNo`, 1,
   'MDP_LOCAL',
   'SELECT biz_date AS value_date, ''ORDER'' AS dimension_type, order_no AS dimension_code, order_no AS dimension_name, cycle_days AS metric_value, cycle_days AS sum_value, 1 AS sample_count, order_no AS source_key
FROM dwd_t8_order_shipment_cycle
WHERE tenant_id = @tenant_id AND factory_id = @factory_id AND biz_date = @biz_date AND source_ztid = @ztid
  AND cycle_days IS NOT NULL',
   'AVERAGE_OF_SUMS', '["value_date","order_no"]', 60,
   'PUBLISHED', 1,
   'SUMMARY S7_L1_001 同源 dwd_t8_order_shipment_cycle 订单级 cycle_days',
   '生产固化：订单发货周期订单维度，AVERAGE_OF_SUMS 与汇总 AVG(cycle_days) 1:1', 'S7_L1_001 维度配置生产初始化', 'system', NOW()
FROM ado_smart_ops_kpi_calc_config s
WHERE s.`MetricCode` = 'S7_L1_001' AND s.`IsCurrent` = 1 AND s.`PublishStatus` = 'PUBLISHED'
  AND NOT EXISTS (
    SELECT 1 FROM ado_smart_ops_kpi_dimension_config d
    WHERE d.`MetricCode` = 'S7_L1_001' AND d.`TenantId` = s.`TenantId` AND d.`IsCurrent` = 1
  )
LIMIT 1;
