DECLARE $param_dict AS Dict<String, String>;

$base_dir = IF(
  $param_dict["branch"] = "prod",
  "//home/vipplanners/sow",
  "//home/vipplanners/sow_dev" || '/' || $param_dict["branch"]
);

-- input
$result_full = $base_dir || '/' || 'meat/latest';
$fraud = "//home/vipplanners/dict/sow/fraud";

-- output
$result_v1 = $base_dir || '/' || "short_result/latest";
$result_v2 = $base_dir || '/' || "short_result/latest_v2";
$result_has_tier = $base_dir || '/' || "short_result/latest_v2_not_empty_tier";
$result_has_no_tier = $base_dir || '/' || "short_result/latest_v2_empty_tier";

PRAGMA AnsiInForEmptyOrNullableItemsCollections;
PRAGMA yson.AutoConvert; 
PRAGMA SimpleColumns;
use hahn;

$get_names = (
select
    spark_id,shortened_name
from
    (
    select
        spark_id,
        ListHead(String::SplitToList(NormName, ",")) as shortened_name
    from
        (
        select
            spark_id,
            some(NormName) as NormName
        from
            `//home/comdep-analytics/zedlaa/spark/raw/firms_all_2`
        with InferSchema
        group by
            cast(SparkID as Int64) as spark_id
        )
    )
where
    nvl(shortened_name,"") != ""
)
;


insert into $result_v1 WITH TRUNCATE 
select
    a.spark_id as spark_id,
    nvl(b.shortened_name,a.name) as name,
    is_firm,
    head_spark_id,
    head_name,
    -- зануляем отрицательные значения в актах:
    if(nvl(acts,0) < 0, 0, nvl(acts,0)) as acts,
    if(nvl(mediabanners_acts,0) < 0, 0, nvl(mediabanners_acts,0)) as mediabanners_acts,
    if(nvl(orderstat,0) < 0, 0, nvl(orderstat,0)) as orderstat,
    
    nvl(inn,"") as inn, 
    nvl(ogrn,"") as ogrn, 
    nvl(legal_city,"") as legal_city,

    revenue,
    commercial_expenses,
    client_id,
    client_type,
    curr_client_tier,
    curr_counterparty_name,
    main_okved,
    company_size,
    cluster,
    McKinsey_industry,
    Yandex_industry,
    
    -- корректируем значения wallet_size_by_revenue. Если "кошелёк" меньше, чем клиент тратит у нас, доводим размер кошелька хотя бы до уровня откруток в Яндексе
    if(
        wallet_size_by_revenue is null, null, 
        if(
            nvl(wallet_size_by_revenue,0) < nvl(sparkid_acts_total,0),
            nvl(sparkid_acts_total,0),
            wallet_size_by_revenue
        )
    ) as wallet_size_by_revenue,
    
    --- делаем то же самое с показателем SOW: если цифра меньше 0 (пришло из актов) = 0; если > 100%, ставим 100%
    if(
        sow_by_revenue is null, null,
        if(
            nvl(sow_by_revenue,0)<0, 0,
            if(nvl(sow_by_revenue,0)>1,1,
            sow_by_revenue
            )
        )
    ) as sow_by_revenue,
        
    if(
        sow_by_commercial_expenses is null, null,
        if(
            nvl(sow_by_commercial_expenses,0)<0, 0,
            if(nvl(sow_by_commercial_expenses,0)>1,1,
            sow_by_commercial_expenses
            )
        )
    ) as sow_by_commercial_expenses
        
from
    $result_full as a
left join
    $get_names as b on a.spark_id = b.spark_id
left only join
    $fraud as c on a.spark_id = c.spark_id
;

COMMIT;

-- После этого - записываем значения для саджеста в полях фильтрации:
/*
insert into `home/vipplanners/sow/short_result/dashboard_name` with truncate
Select name
from `home/vipplanners/sow/short_result/latest`
group by name
;
insert into `home/vipplanners/sow/short_result/dashboard_client_id` with truncate
Select client_id
from `home/vipplanners/sow/short_result/latest`
group by client_id
;
insert into `home/vipplanners/sow/short_result/dashboard_cluster` with truncate
Select cluster
from `home/vipplanners/sow/short_result/latest`
group by cluster
;
insert into `home/vipplanners/sow/short_result/latest_wo_t3t4` with truncate
Select *
from `home/vipplanners/sow/short_result/latest`
where NVL(curr_client_tier, 'EMPTY') not in ('t3 Center', 't3 Regions', 't4', 'EMPTY')
;
insert into `home/vipplanners/sow/short_result/latest_not_empty` with truncate
Select *
from `home/vipplanners/sow/short_result/latest`
where NVL(curr_client_tier, 'EMPTY') not in ('EMPTY')
;
insert into `home/vipplanners/sow/short_result/dashboard_curr_client_tier` with truncate
Select curr_client_tier
from `home/vipplanners/sow/short_result/latest`
group by curr_client_tier
;
*/


insert into $result_v2 WITH TRUNCATE 
select
    a.spark_id as spark_id,
    nvl(b.shortened_name,a.name) as client_name,
    is_firm,
    head_spark_id,
    head_name,
    nvl(inn,"") as inn, 
    nvl(ogrn,"") as ogrn, 
    nvl(legal_city,"") as legal_city,
    -- зануляем отрицательные значения в актах:
    if(nvl(acts,0) < 0, 0, nvl(acts,0)) as acts,
    if(nvl(mediabanners_acts,0) < 0, 0, nvl(mediabanners_acts,0)) as mediabanners_acts,
    if(nvl(orderstat,0) < 0, 0, nvl(orderstat,0)) as orderstat,
    
    revenue,
    commercial_expenses,
    client_id as client_id,
    client_type,
    NVL(curr_client_tier,'Нет тира') as curr_client_tier,
    curr_counterparty_name,
    main_okved,
    company_size,
    NVL(cluster,'Нет кластера') as client_cluster,
    McKinsey_industry,
    Yandex_industry,
    
    -- корректируем значения wallet_size_by_revenue. Если "кошелёк" меньше, чем клиент тратит у нас, доводим размер кошелька хотя бы до уровня откруток в Яндексе
    if(
        wallet_size_by_revenue is null, null, 
        if(
            nvl(wallet_size_by_revenue,0) < nvl(sparkid_acts_total,0),
            nvl(sparkid_acts_total,0),
            wallet_size_by_revenue
        )
    ) as wallet_size_by_revenue,
    
    --- делаем то же самое с показателем SOW: если цифра меньше 0 (пришло из актов) = 0; если > 100%, ставим 100%
    if(
        sow_by_revenue is null, null,
        if(
            nvl(sow_by_revenue,0)<0, 0,
            if(nvl(sow_by_revenue,0)>1,1,
            sow_by_revenue
            )
        )
    ) as sow_by_revenue,
        
    if(
        sow_by_commercial_expenses is null, null,
        if(
            nvl(sow_by_commercial_expenses,0)<0, 0,
            if(nvl(sow_by_commercial_expenses,0)>1,1,
            sow_by_commercial_expenses
            )
        )
    ) as sow_by_commercial_expenses
        
from
    $result_full as a
left join
    $get_names as b on a.spark_id = b.spark_id
left only join
    $fraud as c on a.spark_id = c.spark_id
;    


COMMIT;

insert into $result_has_tier WITH TRUNCATE 
select * from $result_v2
where curr_client_tier <> 'Нет тира'
;

insert into $result_has_no_tier WITH TRUNCATE 
select * from $result_v2
where curr_client_tier == 'Нет тира'
;

