<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.nantian.cloud.jljc.mapper.DischargeEnergyStockMonthMapper">

    <sql id="tableName">
        t_discharge_energy_stock_month
    </sql>
    <sql id="baseColumn">
        id,item_name,item_location,enterprise_name,enterprise_code,production_value,energy_consumption,energy_consumption_unit,energy_standard,remark,userid,update_time,del_flag,dept_id,state
    </sql>
    <sql id="baseColumn1">
        item_name,item_location,
        enterprise_name,enterprise_code,energy_consumption,energy_consumption_unit,energy_standard,remark,userid,del_flag,dept_id,state,
        year,quarter,replacement,item_description,item_invest,energy_design_dl,energy_design_dj,
        energy_coal,energy_current,revenue,production_new,start_time,production_time,enterprise_state,energy_raw,energy_raw_value,electricity_price
    </sql>

    <sql id="baseColumn2">
        item_type,item_id,product_name,product_num,energy_office,energy_number,
        energy_time,production_value,capacity_design,product_output1,product_output2,product_output3,product_output4,
        product_output5,userid,update_time,del_flag,dept_id
    </sql>

    <insert id="addStock" parameterType="com.nantian.cloud.jljc.entity.DischargeEnergyStockMonth" useGeneratedKeys="true" keyProperty="id">
        insert into t_discharge_energy_stock_month(<include refid="baseColumn1"/>)
        values(#{query.industryTypeName},#{query.industryTypeCode},#{query.industrySubclassName},#{query.industrySubclassCode},#{query.itemName},#{query.itemLocation},
        #{query.enterpriseName},#{query.enterpriseCode},#{query.energyConsumption},#{query.energyConsumptionUnit},#{query.energyStandard},#{query.userid},#{query.delFlag},#{query.deptId},#{query.state},
        #{query.year},#{query.quarter},#{query.replacement},#{query.item_description},#{query.item_invest},#{query.energy_design_dl},#{query.energy_design_dj},
        #{query.energy_coal},#{query.energy_current},#{query.revenue},#{query.production_new},#{query.start_time},#{query.production_time},
        #{query.enterprise_state},#{query.energy_raw},#{query.energy_raw_value},#{query.electricity_price})
    </insert>
    <insert id="addProduction" parameterType="com.nantian.cloud.jljc.entity.DischargeEnergyProductMonth" useGeneratedKeys="true" keyProperty="id">
        insert into t_discharge_energy_product_month(<include refid="baseColumn2"/>)
        values(#{query.itemType},#{query.itemId},#{query.productName},#{query.productNum},#{query.energyOffice},
        #{query.energyNumber},#{query.energyTime},#{query.productionValue},#{query.capacityDesign},
        #{query.productOutput1},#{query.productOutput2},#{query.productOutput3},#{query.productOutput4},
        #{query.productOutput5},#{query.userid},#{query.updateTime},#{query.remark},
        #{query.delFlag},#{query.deptId})
    </insert>

    <select id="getPageData" resultType="com.nantian.cloud.jljc.entity.DischargeEnergyStockMonth">
        select *
        from t_discharge_energy_stock_month
        <trim prefix="where" prefixOverrides="and">
<!--            <if test="query.industryTypeCode != null">-->
<!--                and industry_type_code = #{query.industryTypeCode}-->
<!--            </if>-->
<!--            <if test="query.industrySubclassCode != null">-->
<!--                and industry_subclass_code = #{query.industrySubclassCode}-->
<!--            </if>-->
            <if test="query.itemName != null">
                and item_name = #{query.itemName}
            </if>
            <if test="query.delFlag != null">
                and del_flag = #{query.delFlag}
            </if>
            <if test="query.itemLocation != null">
                and item_location = #{query.itemLocation}
            </if>
            <if test="query.enterpriseName != null">
                and enterprise_name = #{query.enterpriseName}
            </if>
            <if test="query.enterpriseCode != null">
                and enterprise_code = #{query.enterpriseCode}
            </if>
            <if test="query.year != null">
                and year = #{query.year}
            </if>
            <if test="query.quarter != null">
                and quarter = #{query.quarter}
            </if>
            <if test="query.id != null">
                and id = #{query.id}
            </if>
            <if test="query.state != null">
                and state = #{query.state}
            </if>
        </trim>
    </select>
    <select id="getStockProductIndex" resultType="com.nantian.cloud.jljc.entity.DischargeEnergyStockMonth">
        SELECT t.id, item_location old_item_location, enterprise_name, enterprise_code, t.dept_id, item_type, item_name, production_total,
        year, quarter, item_invest, enterprise_state, start_time, production_time, energy_office, energy_number, energy_time,
        energy_consumption_last_dl, energy_consumption_last_dj, energy_consumption_last_two_dl, energy_consumption_last_two_dj, energy_coal,
        energy_raw, energy_raw_value, energy_design_dl, energy_design_dj, energy_new_plan_dl, energy_new_plan_dj, energy_saving_effect, energy_electricity,
        adminis_flag, auditor_flag, update_user, audit_user, cause, report_user, report_status, organization_code, ministry_state, ecology_state,
        energy_office_and_number, actual_quantity, reduced_scalar, increment, energy_consumption_dl, energy_consumption_dj, completed_investment,
        limit_standard, energy_efficiency_level, document_number, previous_situation, capacity_replacement, project_located, energy_this_month,electricity_price,
        energy_january_to_this_month, electric_this_month, electric_january_to_this_month, energy_output_value, energy_added_value,
        case when t.item_location not like '%53%' then t.item_location when d1.version like '1' then d1.meaning2 when t.item_location like '%00%' then concat(d1.meaning2,right(d1.meaning,1)) else (
            select concat(d2.meaning2,right(d2.meaning,1),d1.meaning) from dict_region d2 where d2.id = concat(left(right(t.item_location,6),4),'00') and d2.del_flag = '1'
        ) end item_location
        from t_discharge_energy_stock_month t
        left join dict_region d1 on d1.id = right(t.item_location,6) and d1.del_flag = '1'
        <trim prefix="where" prefixOverrides="and">
            and t.del_flag = '1'
<!--            <if test="query.industryTypeCode != null">-->
<!--                and industry_type_code like concat('%',#{query.industryTypeCode},'%')-->
<!--            </if>-->
<!--            <if test="query.industrySubclassCode != null">-->
<!--                and industry_subclass_code like concat('%',#{query.industrySubclassCode},'%')-->
<!--            </if>-->
            <if test="query.itemName != null">
                and item_name like concat('%',#{query.itemName},'%')
            </if>
            <if test="query.enterpriseName != null">
                and enterprise_name like concat('%',#{query.enterpriseName},'%')
            </if>
            <if test="query.enterpriseCode != null">
                and enterprise_code like concat('%',#{query.enterpriseCode},'%')
            </if>
            <if test="query.year != null">
                and year = #{query.year}
            </if>
            <if test="query.quarter != null">
                and quarter = #{query.quarter}
            </if>
            <if test="query.itemType != null">
                and item_type = #{query.itemType}
            </if>
            <if test="query.reportStatus != null">
                and report_status like concat('%', #{query.reportStatus}, '%')
            </if>
        </trim>
        ORDER BY id DESC

    </select>
    <select id="getTotal" resultType="com.nantian.cloud.jljc.vo.dischargeEnergy.DischargeEnergyTotalVo">
        select (select meaning2 from dict_region where id like concat(#{deptId},'00%')) regionName, count(id) num, concat(round(sum(energy_consumption),4),'') energyConsumption, concat(round(sum(item_invest),4),'') itemInvest,
        concat(round(sum(energy_design_dl),4),'') energyDesignDl, concat(round(sum(energy_design_dj),4),'') energyDesignDj, concat(round(sum(energy_coal),4),'') energyCoal, concat(round(sum(energy_current),4),'') energyCurrent,
        concat(round(sum(revenue),4),'') revenue, concat(round(sum(production_new),4),'') productionNew, concat(round(sum(energy_consumption_last_dl),4),'') energyConsumptionLastDl, concat(round(sum(energy_consumption_last_dj),4),'') energyConsumptionLastDj,
        concat(round(sum(energy_consumption_last_two_dl),4),'') energyConsumptionLastTwoDl, concat(round(sum(energy_consumption_last_two_dj),4),'') energyConsumptionLastTwoDj, concat(round(sum(energy_new_plan_dl),4),'') energyNewPlanDl,
        concat(round(sum(energy_new_plan_dj),4),'') energyNewPlanDj, concat(round(sum(energy_saving_effect),4),'') energySavingEffect, concat(round(sum(energy_electricity),4),'') energyElectricity,
        concat(round(sum(energy_consumption_dl),4),'') energyConsumptionDl, concat(round(sum(energy_consumption_dj),4),'') energyConsumptionDj,
        sum(case when JSON_EXTRACT(report_status,"$.city") = "1" then 1 else 0 end) provNum, sum(case when JSON_EXTRACT(report_status,"$.country") = "1" then 1 else 0 end) cityNum
        from t_discharge_energy_stock_month where year = #{query.year} and quarter = #{query.quarter} and item_type = #{query.itemType} and dept_id like concat(#{deptId},'%') and del_flag = '1'
    </select>
    <select id="getTotalProv" resultType="com.nantian.cloud.jljc.vo.dischargeEnergy.DischargeEnergyTotalVo">
        select d.meaning2 regionName, count(z.id) num, concat(round(sum(energy_consumption),4),'') energyConsumption, concat(round(sum(item_invest),4),'') itemInvest,
        concat(round(sum(energy_design_dl),4),'') energyDesignDl, concat(round(sum(energy_design_dj),4),'') energyDesignDj, concat(round(sum(energy_coal),4),'') energyCoal, concat(round(sum(energy_current),4),'') energyCurrent,
        concat(round(sum(revenue),4),'') revenue, concat(round(sum(production_new),4),'') productionNew, concat(round(sum(energy_consumption_last_dl),4),'') energyConsumptionLastDl, concat(round(sum(energy_consumption_last_dj),4),'') energyConsumptionLastDj,
        concat(round(sum(energy_consumption_last_two_dl),4),'') energyConsumptionLastTwoDl, concat(round(sum(energy_consumption_last_two_dj),4),'') energyConsumptionLastTwoDj, concat(round(sum(energy_new_plan_dl),4),'') energyNewPlanDl,
        concat(round(sum(energy_new_plan_dj),4),'') energyNewPlanDj, concat(round(sum(energy_saving_effect),4),'') energySavingEffect, concat(round(sum(energy_electricity),4),'') energyElectricity,
        concat(round(sum(energy_consumption_dl),4),'') energyConsumptionDl, concat(round(sum(energy_consumption_dj),4),'') energyConsumptionDj,
        sum(case when JSON_EXTRACT(z.report_status,"$.city") = "1" then 1 else 0 end) provNum, sum(case when JSON_EXTRACT(z.report_status,"$.country") = "1" then 1 else 0 end) cityNum
        from dict_region d
        left join t_discharge_energy_stock_month z on d.id = concat(left(z.dept_id,4),'00') and year = #{query.year} and quarter = #{query.quarter} and item_type = #{query.itemType} and z.del_flag = '1'
        where d.pid = '530000' group by d.id order by d.id
    </select>

    <select id="getChanges" resultType="map">
        select t1.item_name as itemName, t1.year as year, t1.quarter as quarter
        from t_discharge_energy_stock_month t1 left join t_discharge_energy_stock_month t2 on t1.item_name = t2.item_name
        where (t1.year = t2.year and t1.quarter - 1 = t2.quarter and t1.item_type != t2.item_type)
            or (t1.`quarter` = 1 and t2.`quarter` = 12 and t1.year - 1 = t2.year and t1.item_type != t2.item_type)
            and t1.del_flag = '1'
        <if test="query.itemName != null">
            and t1.item_name like concat('%',#{query.itemName},'%')
        </if>
        <if test="query.itemLocation != null">
            and t1.item_location like concat('%',#{query.itemLocation},'%')
        </if>
        <if test="query.enterpriseName != null">
            and t1.enterprise_name like concat('%',#{query.enterpriseName},'%')
        </if>
        <if test="query.enterpriseCode != null">
            and t1.enterprise_code like concat('%',#{query.enterpriseCode},'%')
        </if>
        <if test="query.year != null">
            and t1.year = #{query.year}
        </if>
        <if test="query.quarter != null">
            and t1.quarter = #{query.quarter}
        </if>
        <if test="query.itemType != null">
            and t1.item_type = #{query.itemType}
        </if>
        <if test="query.reportStatus != null">
            and t1.report_status like concat('%', #{query.reportStatus}, '%')
        </if>
    </select>
    <!--
    拟建项目转在建项目：根据项目名称
    在建项目转存量项目：根据企业编码与产品名称
    <select id="getItemChange" resultType="com.nantian.cloud.jljc.entity.DischargeEnergyStockMonth">
        select distinct t1.id, t1.item_name, t1.year, t1.quarter, t1.enterprise_code
        from t_discharge_energy_stock_month t1
        left join t_discharge_energy_stock_month t2 on t2.del_flag = "1"
        <choose>
            <when test="query.itemType == '1'.toString()">
                and t1.enterprise_code = t2.enterprise_code
            </when>
            <when test="query.itemType == '2'.toString()">
                and t1.item_name = t2.item_name
            </when>
        </choose>
        left join t_discharge_energy_product_month t3 on t3.del_flag = "1" and t1.id = t3.item_id
        left join t_discharge_energy_product_month t4 on t4.del_flag = "1" and t1.id = t3.item_id
        where t1.id = #{query.id}
        <if test="query.itemType == '1'.toString()">
            and t3.product_name = t4.product_name
        </if>
        <choose>
            <when test="query.quarter == '1'.toString()">
                and t1.year - 1 = t2.year and t1.`quarter` = 1 and t2.`quarter` = 12 and t1.item_type != t2.item_type
            </when>
            <otherwise>
                and t1.year = t2.year and t1.quarter - 1 = t2.quarter and t1.item_type != t2.item_type
            </otherwise>
        </choose>
    </select>-->
    <select id="getItemChange" resultType="com.nantian.cloud.jljc.entity.DischargeEnergyStockMonth">
        select distinct t1.id, t1.item_name, t1.year, t1.quarter, t1.enterprise_code
        from t_discharge_energy_stock_month t1
        left join t_discharge_energy_stock_month t2 on t2.del_flag = "1" and t1.item_name = t2.item_name
        where t1.id = #{query.id}
        <choose>
            <when test="query.quarter == '1'.toString()">
                and t1.year - 1 = t2.year and t1.`quarter` = 1 and t2.`quarter` = 12 and t1.item_type != t2.item_type
            </when>
            <otherwise>
                and t1.year = t2.year and t1.quarter - 1 = t2.quarter and t1.item_type != t2.item_type
            </otherwise>
        </choose>
    </select>

    <sql id="base_summary_table1">
        select t1.id '地区编码', t1.meaning2 '地区名称',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.energy_consumption_last_two_dl else null end)/10000,4),'') '存量企业-2020年综合能源消费量当量值（万吨标准煤）',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.energy_consumption_last_dl else null end)/10000,4),'') '存量企业-2021年综合能源消费量当量值（万吨标准煤）',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.energy_consumption_dl else null end)/10000,4),'')  '存量企业-2022年综合能源消费量当量值（万吨标准煤）',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.electric_january_to_this_month else null end)/10000,4),'')  '存量企业-2023年1-X月综合能源消费量当量值（万吨标准煤）',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.electric_january_to_this_month else null end),4),'')  '存量企业-2023年1-X月用电量（万千瓦时）',
        IFNULL(round(sum(case when t2.item_type = '1' then 1 else null end),0),'') '存量项目',
        IFNULL(round(sum(case when t2.item_type = '2' then 1 else null end),0),'') '在建项目',
        IFNULL(round(sum(case when t2.item_type = '3' then 1 else null end),0),'') '拟建项目'
        from (
            select id, meaning, meaning2 from dict_region where pid = '530000'
        ) t1 left join (
            select id, item_name, item_location, item_type, dept_id, production_total, energy_consumption_last_dl, energy_consumption_last_two_dl, energy_consumption_dl, energy_january_to_this_month, electric_january_to_this_month,
            case when item_location like '53%' then right(item_location,6) else dept_id end region_code
            from t_discharge_energy_stock_month
            where del_flag = '1' and year = #{year} and quarter = #{quarter}
        ) t2 on left(t1.id,4) = left(t2.region_code,4)
    </sql>
    <select id="getSummaryTable1" resultType="java.util.Map">
        <include refid="base_summary_table1"></include>
        group by t1.id order by t1.id asc;
    </select>
    <select id="getSummaryTableSum" resultType="java.util.Map">
        <include refid="base_summary_table1"></include>
    </select>

    <sql id="base_summary_table_data">
        select t1.id '地区编码', t1.meaning2 '地区名称',
        IFNULL(round(sum(case when t2.item_type = '1' then 1 else null end),0),'') '存量项目数量',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.energy_january_to_this_month else null end)/10000,4),'') '能耗（万吨标准煤）-存量-当量值',
        IFNULL(round(sum(case when t2.item_type = '1' then t2.electric_january_to_this_month else null end),4),'') '用电量（万千瓦时）-存量',
        IFNULL(round(sum(case when t2.item_type = '2' then 1 else null end),0),'') '在建项目数量',
        IFNULL(round(sum(case when t2.item_type = '2' then t2.energy_january_to_this_month else null end)/10000,4),'') '能耗（万吨标准煤）-在建-当量值',
        IFNULL(round(sum(case when t2.item_type = '3' then 1 else null end),0),'') '拟建项目数量',
        IFNULL(round(sum(case when t2.item_type = '3' then t2.energy_january_to_this_month else null end)/10000,4),'') '能耗（万吨标准煤）-拟建-当量值'
        from (
            select id, meaning, meaning2 from dict_region where pid = '530000'
        ) t1 left join (
            select distinct m1.id, m1.item_name, m1.item_location, m1.item_type, m1.dept_id, m1.energy_january_to_this_month, m1.electric_january_to_this_month,
            case when m1.item_location like '53%' then right(m1.item_location,6) else m1.dept_id end region_code
            from t_discharge_energy_stock_month m1
            left join t_discharge_energy_product_month m2 on m2.del_flag = '1' and m1.id = m2.item_id
            where m1.del_flag = '1' and m1.year = #{year} and m1.quarter = #{quarter} and left(m2.industry_type_code,2) =  #{s}
        ) t2 on left(t1.id,4) = left(t2.region_code,4)
    </sql>
    <select id="getSummaryTableData" resultType="java.util.Map">
        <include refid="base_summary_table_data"></include>
        group by t1.id order by t1.id asc;
    </select>
    <select id="getSummaryTableDataSum" resultType="java.util.Map">
        <include refid="base_summary_table_data"></include>
    </select>

    <select id="getSummaryTableData2" resultType="java.util.Map">
        select t1.code '行业编码', t1.name '行业名称', IFNULL(round(sum(t2.num),0),'') '数量',
        IFNULL(round(sum(t2.production_total)/10000,4),'') '生产总值（亿元）',
        IFNULL(round((sum(t2.production_total)-sum(t3.production_total))*100/sum(t3.production_total),2),'') '同比增速%',
        IFNULL(round(sum(t2.electric_january_to_this_month),4),'') '用电量（万千瓦时）',
        IFNULL(round((sum(t2.electric_january_to_this_month)-sum(t3.electric_january_to_this_month))*100/sum(t3.electric_january_to_this_month),2),'') '用电量同比增速%',
        IFNULL(round(sum(t2.electric_january_to_this_month)/10000,4),'') '1-x月能源消费总量（万吨标准煤，当量值）',
        IFNULL(round(sum(t4.electric_january_to_this_month)/10000,4),'') '1月能源消费总量（万吨标准煤，当量值）',
        IFNULL(round((sum(t2.electric_january_to_this_month)-sum(t4.electric_january_to_this_month))*100/sum(t4.electric_january_to_this_month),2),'') '能耗累计增速%',
        IFNULL(round(sum(t2.electricity_price),2),'') '度电增加值（元）',
        IFNULL(round(sum(t2.electricity_price)/sum(t2.electric_january_to_this_month),2),'') '度电产值（元/千瓦时）'
        from(
            select '25' code, '石油、煤炭及其他燃料加工业' name union
            select '26' code, '化学原料和化学制品制造业' name union
            select '30' code, '非金属矿物制品业' name union
            select '31' code, '黑色金属冶炼和压延加工业' name union
            select '32' code, '有色金属冶炼和压延加工业' name union
            select '44' code, '电力、热力生产及供应业' name
        )t1 left join (
            select left(m2.industry_type_code,2) industry_type_code, count(distinct m1.id) num, GROUP_CONCAT(distinct m1.id) id, sum(m1.production_total) production_total,
            sum(m1.energy_january_to_this_month) energy_january_to_this_month, sum(m1.electric_january_to_this_month) electric_january_to_this_month, sum(m1.electricity_price) electricity_price
            from t_discharge_energy_stock_month m1
            left join t_discharge_energy_product_month m2 on m2.del_flag = '1' and m1.id = m2.item_id and m2.industry_type_code is not null
            where m1.del_flag = '1' and m1.item_type = '1' and m1.year = #{year} and m1.quarter = #{quarter}
            group by left(m2.industry_type_code,2)
        ) t2 on t1.code = t2.industry_type_code
        left join (
            select left(m2.industry_type_code,2) industry_type_code, count(distinct m1.id) num, GROUP_CONCAT(distinct m1.id) id, sum(m1.production_total) production_total,
            sum(m1.energy_january_to_this_month) energy_january_to_this_month, sum(m1.electric_january_to_this_month) electric_january_to_this_month, sum(m1.electricity_price) electricity_price
            from t_discharge_energy_stock_month m1
            left join t_discharge_energy_product_month m2 on m2.del_flag = '1' and m1.id = m2.item_id and m2.industry_type_code is not null
            where m1.del_flag = '1' and m1.item_type = '1' and m1.year = ${year}-1 and m1.quarter = #{quarter}
            group by left(m2.industry_type_code,2)
        ) t3 on t1.code = t3.industry_type_code
        left join (
            select left(m2.industry_type_code,2) industry_type_code, count(distinct m1.id) num, GROUP_CONCAT(distinct m1.id) id, sum(m1.production_total) production_total,
            sum(m1.energy_january_to_this_month) energy_january_to_this_month, sum(m1.electric_january_to_this_month) electric_january_to_this_month, sum(m1.electricity_price) electricity_price
            from t_discharge_energy_stock_month m1
            left join t_discharge_energy_product_month m2 on m2.del_flag = '1' and m1.id = m2.item_id and m2.industry_type_code is not null
            where m1.del_flag = '1' and m1.item_type = '1' and m1.year = #{year} and m1.quarter = 1
            group by left(m2.industry_type_code,2)
        ) t4 on t1.code = t4.industry_type_code
        group by t1.code order by t1.code asc;

    </select>
</mapper>
