-- Databricks notebook source
-- CREATE OR REPLACE TABLE DM.DM_TD_EXT_COUNTY_ORG (
--   REGION_CODE STRING,
--   REGION_NAME_EN STRING,
--   RSM_NAME STRING,
--   RC_CODE STRING,
--   RC_NAME_EN STRING,
--   RC_NAME STRING,
--   REGIONCENTER STRING,
--   AUDIT_COD STRING,
--   MARKET STRING,
--   BU_CATEGORY STRING,
--   BU_NAME_EN STRING,
--   SUB_BU_NAME STRING,
--   SUB_BU_CODE_AUTH STRING,
--   BU_CODE_AUTH STRING,
--   DATA_SOURCE STRING,
--   REGION_RATIO FLOAT,
--   TEAM STRING,
--   MR_TRTY_CODE STRING,
--   NSD_KCODE STRING,
--   NSD_NAME STRING,
--   RSD_KCODE STRING,
--   RSD_NAME STRING,
--   RSM_KCODE STRING,
--   DSM_KCODE STRING,
--   DSM_NAME STRING,
--   MR_KCODE STRING,
--   MR_NAME STRING)
-- USING delta
-- LOCATION 'abfss://master@retaildlstoragetest.dfs.core.chinacloudapi.cn/DM/dm_td_ext_county_org';

-- COMMAND ----------

-- MAGIC %run ../../../Common/config

-- COMMAND ----------

-- MAGIC %python
-- MAGIC spark.read.table(f'`{CDW_CATALOG}`.`dwd`.`dim_product_wide`').createOrReplaceTempView('cdw_dwd_dim_product_wide')

-- COMMAND ----------

-- 20260130 由于DM.dm_td_org数据需要转换，新增这个CELL。
create or replace temporary view dm_td_org_temp
as 
SELECT org_key,mr_trty_tag,district_code,rsm_name,rc_name,p2.region_name,p2.rsd_kcode,p2.rsd_name
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bu_code = 'PC12' then 'PC09' else p2.bu_code end bu_code
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bu_report = 'EC' THEN 'Retail' ELSE p2.bu_report end bu_report
  ,CASE WHEN p2.yyyymm >= '202601' and p2.sub_bu_code = 'NA27' then 'NA06' else p2.sub_bu_code end sub_bu_code
  ,CASE WHEN p2.yyyymm >= '202601' and p2.sub_bu_name = 'EC' then 'Retail' else p2.sub_bu_name end sub_bu_name
  ,CASE WHEN p2.yyyymm >= '202601' and p2.sub_bu_name_en = 'EC' then 'Retail' else p2.sub_bu_name_en end sub_bu_name_en
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bu_name = 'EC' then 'Retail' else p2.bu_name end bu_name
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bu_name_en = 'EC' then 'Retail' else p2.bu_name_en end bu_name_en
  ,CASE WHEN p2.yyyymm >= '202601' and p2.nsd_kcode = 'ND_EC0001_V' then 'KSGX559' else p2.nsd_kcode end nsd_kcode
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bu_name = 'EC'and p2.nsd_name = 'Vacant' then '李白杨' else p2.nsd_name end nsd_name
  ,CASE WHEN p2.yyyymm >= '202601' and p2.nsd_trty_code = 'ND_EC0001' then 'ND_RT0001' else p2.nsd_trty_code end nsd_trty_code
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bsd_kcode = 'VP_EC0001_V' then 'VP_RT0001_V' else p2.bsd_kcode end bsd_kcode
  ,CASE WHEN p2.yyyymm >= '202601' and p2.bsd_trty_code = 'VP_EC0001' then 'VP_RT0001' else p2.bsd_trty_code end bsd_trty_code
  ,mr_kcode,dsm_trty_code,rsm_trty_code,dsm_kcode,rsd_trty_code
  ,district_name,dsm_name,mr_name,yyyymm,mr_trty_code,REGION_CODE,rc_code,bu_category,rsm_kcode
FROM DM.dm_td_org P2

-- COMMAND ----------

-- 
insert overwrite DM.DM_TD_EXT_COUNTY_ORG
(REGION_CODE,region_name_en,rc_code,rc_name_en,RegionCenter,AUDIT_COD,MARKET,bu_category,bu_name_en,sub_bu_name,sub_bu_code_auth,bu_code_auth,DATA_SOURCE,REGION_RATIO,RSM_Name,RC_Name,
TEAM,
MR_TRTY_CODE,
NSD_KCODE,
NSD_NAME,
RSD_KCODE,
RSD_NAME,
RSM_KCODE,
DSM_KCODE,
DSM_NAME,
MR_KCODE,
MR_NAME
)
WITH 
-- ① 市场与子BU映射
market_ta AS (
  select distinct MARKET,bu as subbu from dwd.dwd_gnd_tblmarket_bymonth
  -- WHERE UPPER(TA) <> 'ALL'
),

-- ② 产品包与市场映射
pack_2_market AS (
  SELECT DISTINCT
    a.PACK_CODE,
    a.market,
    b.subbu
  FROM
    dm.dm_td_ext_COUNTY_market_pack_mapping a
  LEFT JOIN market_ta b ON a.MARKET = b.market
),
-- FAMILY与market映射
family_2_markt as (select distinct
  t3.prd_family_cd,
  -- t4.ims_pack_cod,
  t5.market
from
  cdw_dwd_dim_product_wide t3
    inner JOIN dwd.dwd_td_imscode_azcode t4
      ON t3.prd_brand_cd = t4.brandcode
    inner join pack_2_market t5
      on t4.ims_pack_cod = t5.pack_code
where
  t3.prd_family_cd is not null
  and t4.ims_pack_cod is not null
),

-- ③ 外部地理信息
external_geo AS (
    SELECT DISTINCT
        province_c,
        audit_cod,
        REGION_CENTER
    FROM dm.dm_td_external_geo_temp
    WHERE DATA_SOURCE = 'IQVIA-COUNTY(Quarterly)'
),

-- ④ 当前考核月份
YM_CVH AS (
    SELECT key_value
    FROM dm.dm_td_date_config
    WHERE key_code = 'pfmc_cvh'
),

-- ⑤ 组织架构（取当前考核月份快照）
td_org AS (
    SELECT DISTINCT
        REGION_CODE,
        region_name,
        rc_code,
        rc_name,
        bu_category,
        bu_name_en,
        sub_bu_name,
        sub_bu_code,
        bu_code,
        RSM_Name,
        rsd_name,
        mr_trty_code,
        rsm_trty_code
    FROM dm_td_org_temp       t1
    INNER JOIN YM_CVH         t2 ON t1.yyyymm = t2.key_value
),

-- ⑥ 辖区-指征明细（仅保留 OBU/RIN，排除双考）
territory AS (
    SELECT DISTINCT
        trty_code,
        inst_code,
        family_code,
        bu
    FROM dm.dm_td_sd_territory_indication  t1
    INNER JOIN YM_CVH                       t2 ON t1.yyyymm = t2.key_value
    WHERE t1.bu IN ('BBU_County')   -- 20260320 chenwu DTP数据源只保留 OBU 和 RIN
      AND t1.key_hp <> 3            -- 20250904 chenwu 排除双考影响
),

-- ⑦ 辖区-省份-市场关联
province_market AS (
    SELECT
        t1.trty_code,
        t2.province_name,
        t3.market        
    FROM territory                      t1
    LEFT JOIN dwd.dwd_td_institution    t2 ON t1.inst_code   = t2.inst_code
    INNER JOIN family_2_markt            t3 ON t1.family_code = t3.prd_family_cd
)
,part1(
-- ════════════════════════════════════════════
-- 主查询 Part 1：正常地理覆盖行
-- ════════════════════════════════════════════
SELECT DISTINCT
    t1.REGION_CODE,
    t1.region_name,
    t1.rc_code,
    t1.rc_name AS rc_name_en,
    t3.REGION_CENTER                            AS RegionCenter,
    t3.AUDIT_COD,
    t2.MARKET,
    t1.bu_category,
    t1.bu_name_en,
    t1.sub_bu_name,
    t1.sub_bu_code                              AS sub_bu_code_auth,
    CONCAT(t1.bu_code, 'IQVIA-COUNTY(Quarterly)')        AS bu_code_auth,
    'IQVIA-COUNTY(Quarterly)'                            AS DATA_SOURCE,
    1                                           AS REGION_RATIO,
    t1.RSM_Name,
    t1.rsd_name,
    ''                                          AS TEAM,
    ''                                          AS MR_TRTY_CODE,
    ''                                          AS NSD_KCODE,
    ''                                          AS NSD_NAME,
    ''                                          AS RSD_KCODE,
    ''                                          AS RC_Name,
    ''                                          AS RSM_KCODE,
    ''                                          AS DSM_KCODE,
    ''                                          AS DSM_NAME,
    ''                                          AS MR_KCODE,
    ''                                          AS MR_NAME
FROM td_org           t1
INNER JOIN province_market t2 ON t1.mr_trty_code   = t2.trty_code
INNER JOIN external_geo    t3 ON t2.province_name  = t3.province_c
WHERE t2.market    IS NOT NULL
  AND t3.audit_cod IS NOT NULL
)

,all_combinations AS (
  SELECT 
    /*+ BROADCAST(geo) */
    p.market,
    P.subbu,
    geo.audit_cod
  FROM (SELECT DISTINCT market,subbu FROM pack_2_market) p
  CROSS JOIN external_geo geo
  GROUP BY     
    p.market,
    P.subbu,
    geo.audit_cod
)


SELECT * FROM part1

UNION ALL

-- ════════════════════════════════════════════
-- 主查询 Part 2：ROC 虚拟兜底行
-- ════════════════════════════════════════════
SELECT DISTINCT
    'ROC'                                                               AS REGION_CODE,
    'ROC'                                                               AS region_name,
    'ROC'                                                               AS rc_code,
    'ROC'                                                               AS rc_name_en,
    'Other Low Tiers'                                                   AS RegionCenter,
    ac.audit_cod                                                        AS AUDIT_COD,
    ac.market,
    'All Channel'                                                       AS bu_category,
    NVL(subbu,'ROC')           AS bu_name_en,
    NVL(subbu,'ROC')           AS sub_bu_name,
    NVL(subbu,'ROC')           AS sub_bu_code_auth,
    'IQVIA-COUNTY(Quarterly)'                                           AS bu_code_auth,
    'IQVIA-COUNTY(Quarterly)'                                           AS DATA_SOURCE,
    1                                                                   AS REGION_RATIO,
    'Vacant'                                                            AS RSM_Name,
    'Vacant'                                                            AS RC_Name,
    ''                                                                  AS TEAM,
    ''                                                                  AS MR_TRTY_CODE,
    ''                                                                  AS NSD_KCODE,
    ''                                                                  AS NSD_NAME,
    ''                                                                  AS RSD_KCODE,
    ''                                                                  AS RSD_NAME,
    ''                                                                  AS RSM_KCODE,
    ''                                                                  AS DSM_KCODE,
    ''                                                                  AS DSM_NAME,
    ''                                                                  AS MR_KCODE,
    ''                                                                  AS MR_NAME
FROM all_combinations ac
LEFT ANTI JOIN part1 p
           ON ac.market    = p.market
          AND ac.audit_cod = p.audit_cod
