-- 【dic_erp片区】
with one_to_many_organ AS(
    SELECT
        a.username AS username -- 用户名
         ,SUBSTRING_INDEX(SUBSTRING_INDEX(a.mang_organ, ',',b.help_topic_id + 1),',',-1)   AS mang_organ -- 管理片区
    FROM ods_one_to_many_perm a
             JOIN mysql.help_topic b
                  on b.help_topic_id < (LENGTH(a.mang_organ) - length(replace(a.mang_organ,',','')) + 1)
    WHERE a.username  = '${fine_username}'
)
SELECT DISTINCT
    organ_code AS 片区id,
    organ_name AS 片区名称
FROM dw.dws_engine_meter_dosage_m
where 1=1
-- ${if(GETUSERDEPARTMENTS(2)="领悦集团总部","","and organ_name = '"+GETUSERDEPARTMENTS(2)+"'")}

  AND CASE WHEN (SELECT mang_organ FROM ods_one_to_many_perm WHERE username  = '${fine_username}') IS NOT NULL
               THEN organ_name IN (SELECT mang_organ FROM one_to_many_organ WHERE username  = '${fine_username}')
           ELSE ${if(GETUSERDEPARTMENTS(2)!="领悦集团总部","organ_name = '"+GETUSERDEPARTMENTS(2)+"'","1=1")} END

-- 【单位面积能耗_环比】
    with one_to_many AS(
SELECT
a.username AS username -- 用户名
,SUBSTRING_INDEX(SUBSTRING_INDEX(a.mang_project, ',',b.help_topic_id + 1),',',-1) AS mang_project -- 管理项目名
FROM ods_one_to_many_perm a
JOIN mysql.help_topic b
on b.help_topic_id < (LENGTH(a.mang_project) - length(replace(a.mang_project,',','')) + 1)
WHERE a.username  = '${fine_username}'
)
select
    A.organ_code      AS organ_code
     , A.organ_name      AS organ_name
     , A.comm_id         AS comm_id
     , A.comm_name       AS comm_name
     , A.MeterType       AS MeterType
     , A.list_ym         AS list_ym
     , A.Dosage          AS Dosage
     , A.Amount          AS Amount
     , B.StateNameNew AS StateNameNew
     ,CASE WHEN StateNameNew = '写字楼' AND MeterType = '水表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS XZL_SHUI
     ,CASE WHEN StateNameNew = '写字楼' AND MeterType = '电表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS XZL_DIAN
     ,CASE WHEN  StateNameNew = '商住' AND MeterType = '水表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS SZ_SHUI
     ,CASE WHEN  StateNameNew = '商住' AND MeterType = '电表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS SZ_DIAN
     ,IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) AS DOSAGE_PER_SQUARE_METER
from
    (
        SELECT
            organ_code
             , organ_name
             , comm_id
             , comm_name
             , MeterType
             , list_ym
             , Dosage
             , Amount
        FROM dws_engine_meter_dosage_m
        WHERE 1=1
          AND MeterType IN ('水表','电表')
          AND list_ym < date_format(CURRENT_DATE(),'%Y%m')
            ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
    AND LEFT (list_ym,4) = ${left(p_ym,4)}
      -- ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
          AND CASE WHEN (SELECT mang_project FROM ods_one_to_many_perm WHERE username  = '${fine_username}' AND mang_organ IS NULL) IS NOT NULL
            THEN comm_name IN (SELECT mang_project FROM one_to_many WHERE username  = '${fine_username}')
            ELSE ${if(left(fine_role,2)=="项目","comm_name = '"+GETUSERDEPARTMENTS(3)+"'","1=1")} END


    )A
        LEFT JOIN
    (
        select
            CommId  -- 项目id
             ,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                   ELSE '商住'
            END AS StateNameNew
             ,SUM(FloorArea + UndergroundArea) as totalarea
             ,SUM(ContractArea) AS  ContractArea-- 合同面积（建筑面积）
        from dim_project_base_info_d
        GROUP BY
            CommId,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                        ELSE '商住'
            END
    )B
    ON A.comm_id = B.CommId
ORDER BY A.list_ym,A.MeterType

-- 【单位面积能耗_同比】

    with one_to_many AS(
SELECT
a.username AS username -- 用户名
,SUBSTRING_INDEX(SUBSTRING_INDEX(a.mang_project, ',',b.help_topic_id + 1),',',-1) AS mang_project -- 管理项目名
FROM ods_one_to_many_perm a
JOIN mysql.help_topic b
on b.help_topic_id < (LENGTH(a.mang_project) - length(replace(a.mang_project,',','')) + 1)
WHERE a.username  = '${fine_username}'
)
select
    A.organ_code      AS organ_code
     , A.organ_name      AS organ_name
     , A.comm_id         AS comm_id
     , A.comm_name       AS comm_name
     , A.MeterType       AS MeterType
     , A.list_ym         AS list_ym
     , A.Dosage          AS Dosage
     , A.Amount          AS Amount
     , B.StateNameNew AS StateNameNew
     ,CASE WHEN StateNameNew = '写字楼' AND MeterType = '水表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS XZL_SHUI
     ,CASE WHEN StateNameNew = '写字楼' AND MeterType = '电表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS XZL_DIAN
     ,CASE WHEN  StateNameNew = '商住' AND MeterType = '水表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS SZ_SHUI
     ,CASE WHEN  StateNameNew = '商住' AND MeterType = '电表' THEN IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea)) ELSE 0 END AS SZ_DIAN
     ,IF(B.ContractArea = 0,0,(A.Dosage / B.totalarea))AS DOSAGE_PER_SQUARE_METER
from
    (
        SELECT
            organ_code
             , organ_name
             , comm_id
             , comm_name
             , MeterType
             , list_ym
             , Dosage
             , Amount
        FROM dws_engine_meter_dosage_m
        WHERE 1=1
          AND list_ym <> DATE_FORMAT(CURDATE(), '%Y%m')
          AND list_ym >= '${FORMAT(MONTHDELTA(CONCATENATE(p_ym,"-01"),-60),"yyyyMM")}'
            ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
            ${IF(LEN(p_ym)>0," AND right(list_ym,2) ='" +right(p_ym,2) + "'","")}
          --  ${if(left(fine_role,2)=="项目","and comm_name = '"+GETUSERDEPARTMENTS(3)+"'","")}
          AND CASE WHEN (SELECT mang_project FROM ods_one_to_many_perm WHERE username  = '${fine_username}' AND mang_organ IS NULL) IS NOT NULL
                       THEN comm_name IN (SELECT mang_project FROM one_to_many WHERE username  = '${fine_username}')
                   ELSE ${if(left(fine_role,2)=="项目","comm_name = '"+GETUSERDEPARTMENTS(3)+"'","1=1")} END

          and MeterType in ('水表','电表')

    )A
        LEFT JOIN
    (
        select
            CommId  -- 项目id
             ,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                   ELSE '商住'
            END AS StateNameNew
             ,SUM(FloorArea + UndergroundArea) as totalarea
             ,SUM(ContractArea) AS  ContractArea-- 合同面积（建筑面积）
        from dim_project_base_info_d
        GROUP BY
            CommId,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                        ELSE '商住'
            END
    )B
    ON A.comm_id = B.CommId
order by A.list_ym,A.MeterType asc


-- 【明细】

    with one_to_many AS(
SELECT
a.username AS username -- 用户名
,SUBSTRING_INDEX(SUBSTRING_INDEX(a.mang_project, ',',b.help_topic_id + 1),',',-1) AS mang_project -- 管理项目名
FROM ods_one_to_many_perm a
JOIN mysql.help_topic b
on b.help_topic_id < (LENGTH(a.mang_project) - length(replace(a.mang_project,',','')) + 1)
WHERE a.username  = '${fine_username}'
)
select

    ${if(len(p_area) == 0,"A.organ_name","A.comm_name")} as p_area  -- 片区/项目
     , A.MeterType       AS MeterType
     , SUM(A.Dosage)          AS Dosage -- 能耗
     , sum(A.Amount)          AS Amount -- 金额
 --    , B.StateNameNew AS StateNameNew -- 业态
     ,IF(sum(B.ContractArea) = 0,0,(sum(A.Dosage) / sum(B.totalarea)))AS DOSAGE_PER_SQUARE_METER -- 单位面积能耗
from
    (
        SELECT
            organ_code
             , organ_name
             , comm_id
             , comm_name
             , MeterType
             , list_ym
             , Dosage
             , Amount
        FROM dws_engine_meter_dosage_m
        WHERE 1=1
          and MeterType in ('水表','电表')
          and list_ym = ${replace(p_ym,'-','')}
        ${IF(LEN(p_area)>0," AND organ_code IN ('"+JOINARRAY(p_area,"','")+"')", "")}
        ${IF(LEN(P_MeterType)>0," AND MeterType IN ('"+JOINARRAY(P_MeterType,"','")+"')", "")}
    )A
    LEFT JOIN
    (
        select
            CommId  -- 项目id
             ,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                   ELSE '商住'
            END AS StateNameNew
             ,SUM(FloorArea + UndergroundArea) as totalarea
             ,SUM(ContractArea) AS  ContractArea-- 合同面积（建筑面积）
        from dim_project_base_info_d
        GROUP BY
            CommId,CASE WHEN StateNameNew = '写字楼' THEN StateNameNew
                        ELSE '商住'
            END
    )B
    ON A.comm_id = B.CommId
GROUP BY
${if(len(p_area) == 0,"A.organ_name","A.comm_name")}
, A.MeterType