<?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.openhis.web.inventorymanage.mapper.ProductDetailsMapper">

    <select id="selectProductDetailsPage"
            resultType="com.openhis.web.inventorymanage.dto.ProductDetailsPageDto">
        WITH latest_records AS (
            SELECT
                item_table,
                item_id,
                location_id,
                lot_number,
                trace_no,
                MAX(create_time) AS latest_time
            FROM
                adm_trace_no_manage
            WHERE delete_flag = '0'
            GROUP BY
                item_table,
                item_id,
                location_id,
                lot_number,
                trace_no
        )
        SELECT T6.id,                    --库存项目管理ID（停供用）
               T6.bus_no,                --药品编码
               T6.medicine_name,         --药品名称
               T6.py_str,                --药品拼音
               T6.total_volume,          --规格
               T6.chrgitm_lv,            --医保等级
               T6.manufacturer_text,     --厂家
               T6.lot_number,            --批次号
               T6.category_code,         --药品类型
               T6.item_type,             --药品类型区分
               T6.part_percent,          --拆零比
               T6.unit_code,             --采购单位
               T6.quantity,              --库存（小单位）
               T6.min_unit_code,         --库存单位
               T6.price,                 --采购单价
               T6.production_date,       --生产日期
               T6.expiration_date,       --失效日期
               T6.remaining_days,        --剩余天数
               T6.trace_no,              --追溯码
               T6.status_enum,           --药品状态（药品停用）
               T6.location_id,
               T6.location_name,         --仓库
               T6.location_store_id,
               T6.location_store_name,   --货位
               T6.form_enum,             --仓库类型
               T6.supplier_id,           --供应商
               T6.supply_name,           --供应商名称
               T6.inventory_status_enum, --停供状态
               T6.dose_form_code,        --剂型
               T6.approval_number,       --批准文号/国药准字
               T6.retail_price,          --零售价
               T6.tenant_id,
               T6.in_count,
               T6.out_count,
               T6.item_table,
               T6.item_id
        FROM (
                 SELECT T1.id,                    --库存项目管理ID（停供用）
                        T2.bus_no,                --药品编码
                        T2."name" AS medicine_name, --药品名称
                        T2.py_str,                --药品拼音
                        T3.total_volume,          --规格
                        T2.chrgitm_lv,            --医保等级
                        T2.manufacturer_text,     --厂家
                        T1.lot_number,            --批次号
                        T2.category_code,         --药品类型
                        '0' AS item_type,         --药品类型区分
                        T2.part_percent,          --拆零比
                        T2.unit_code,             --采购单位
                        T1.quantity,              --库存（小单位）
                        T2.min_unit_code,         --库存单位
                        T1.price,                 --采购单价
                        T1.production_date,       --生产日期
                        T1.expiration_date,       --失效日期
                        (T1.expiration_date::date - CURRENT_DATE) AS remaining_days, --剩余天数
                        T1.trace_no,              --追溯码
                        T3.status_enum,           --药品状态（药品停用）
                        T1.location_id,
                        T5."name" AS location_name, --仓库
                        T1.location_store_id,
                        T4."name" AS location_store_name, --货位
                        T5.form_enum,             --仓库类型
                        T1.supplier_id,           --供应商
                        T8.name AS supply_name,   --供应商名称
                        T1.inventory_status_enum, --停供状态
                        T3.dose_form_code,        --剂型
                        T2.approval_number,       --批准文号/国药准字
                        T10.amount AS retail_price, --零售价
                        T1.tenant_id,             --修复：添加逗号
                        COALESCE(in_counts.in_count, 0) AS in_count,
                        COALESCE(out_counts.out_count, 0) AS out_count,
                        T1.item_table,
                        T1.item_id
                 FROM wor_inventory_item T1
                          INNER JOIN med_medication_definition T2
                                     ON T1.item_id = T2.id
                                         AND T2.delete_flag = '0'
                          LEFT JOIN med_medication T3
                                    ON T2.id = T3.medication_def_id
                                        AND T3.delete_flag = '0'
                          LEFT JOIN adm_location T4
                                    ON T1.location_store_id = T4.id
                                        AND T4.delete_flag = '0'
                          LEFT JOIN adm_location T5
                                    ON T1.location_id = T5.id
                                        AND T5.delete_flag = '0'
                          LEFT JOIN adm_supplier T8
                                    ON T1.supplier_id = T8.id
                                        AND T8.delete_flag = '0'
                          LEFT JOIN adm_charge_item_definition T9
                                    ON T9.instance_table = 'med_medication_definition'
                                        AND T9.instance_id = T2.id
                                        AND T9.delete_flag = '0'
                          LEFT JOIN LATERAL (
                     SELECT amount
                     FROM adm_charge_item_def_detail
                     WHERE definition_id = T9.id
                       AND condition_value = T1.lot_number
                       AND condition_code = '1'--1:批号进价
                       AND delete_flag = '0'
                     ORDER BY create_time DESC
                         LIMIT 1
             ) T10 ON TRUE
    LEFT JOIN (
        SELECT ls.item_table,
               ls.item_id,
               ls.location_id,
               ls.lot_number,
               SUM(CASE WHEN T10.status_enum = '1' THEN 1 ELSE 0 END) AS in_count
        FROM latest_records ls
        LEFT JOIN adm_trace_no_manage T10
            ON T10.item_table = ls.item_table
            AND T10.item_id = ls.item_id
            AND T10.location_id = ls.location_id
            AND T10.lot_number = ls.lot_number
            AND T10.trace_no = ls.trace_no
            AND T10.create_time = ls.latest_time
        GROUP BY ls.item_table, ls.item_id, ls.location_id, ls.lot_number
    ) in_counts
        ON T1.item_table = in_counts.item_table
            AND T1.item_id = in_counts.item_id
            AND T1.location_id = in_counts.location_id
            AND T1.lot_number = in_counts.lot_number
            LEFT JOIN (
            SELECT ls.item_table,
            ls.item_id,
            ls.location_id,
            ls.lot_number,
            SUM(CASE WHEN T10.status_enum = '2' THEN 1 ELSE 0 END) AS out_count
            FROM latest_records ls
            LEFT JOIN adm_trace_no_manage T10
            ON T10.item_table = ls.item_table
            AND T10.item_id = ls.item_id
            AND T10.location_id = ls.location_id
            AND T10.lot_number = ls.lot_number
            AND T10.trace_no = ls.trace_no
            AND T10.create_time = ls.latest_time
            GROUP BY ls.item_table, ls.item_id, ls.location_id, ls.lot_number
            ) out_counts
            ON T1.item_table = out_counts.item_table
            AND T1.item_id = out_counts.item_id
            AND T1.location_id = out_counts.location_id
            AND T1.lot_number = out_counts.lot_number
        WHERE T1.delete_flag = '0'
            ) AS T6
            ${ew.customSqlSegment}

        UNION ALL

        SELECT T7.id,                    --库存项目管理ID（停供用）
               T7.bus_no,                --药品编码
               T7.medicine_name,         --药品名称
               T7.py_str,                --药品拼音
               T7.total_volume,          --规格
               T7.chrgitm_lv,            --医保等级
               T7.manufacturer_text,     --厂家
               T7.lot_number,            --批次号
               T7.category_code,         --药品类型
               T7.item_type,             --药品类型区分
               T7.part_percent,          --拆零比
               T7.unit_code,             --采购单位
               T7.quantity,              --库存（小单位）
               T7.min_unit_code,         --库存单位
               T7.price,                 --采购单价
               T7.production_date,       --生产日期
               T7.expiration_date,       --失效日期
               T7.remaining_days,        --剩余天数
               T7.trace_no,              --追溯码
               T7.status_enum,           --药品状态（药品停用）
               T7.location_id,
               T7.location_name,         --仓库
               T7.location_store_id,
               T7.location_store_name,   --货位
               T7.form_enum,             --仓库类型
               T7.supplier_id,           --供应商
               T7.supply_name,           --供应商名称
               T7.inventory_status_enum, --停供状态
               T7.dose_form_code,        --剂型
               T7.approval_number,       --批准文号/国药准字
               T7.retail_price,          --零售价
               T7.tenant_id,
               T7.in_count,
               T7.out_count,
               T7.item_table,
               T7.item_id
        FROM (
                 SELECT T1.id,                    --库存项目管理ID（停供用）
                        T2.bus_no,                --药品编码
                        T2."name" AS medicine_name, --药品名称
                        T2.py_str,                --药品拼音
                        T2.size AS total_volume,  --规格
                        T2.chrgitm_lv,            --医保等级
                        T2.manufacturer_text,     --厂家
                        T1.lot_number,            --批次号
                        T2.category_code,         --药品类型
                        '9' AS item_type,         --药品类型区分
                        T2.part_percent,          --拆零比
                        T2.unit_code,             --采购单位
                        T1.quantity,              --库存（小单位）
                        T2.min_unit_code,         --库存单位
                        T1.price,                 --采购单价
                        T1.production_date,       --生产日期
                        T1.expiration_date,       --失效日期
                        (T1.expiration_date::date - CURRENT_DATE) AS remaining_days, --剩余天数
                        T1.trace_no,              --追溯码
                        T2.status_enum,           --药品状态（药品停用）
                        T1.location_id,
                        T5."name" AS location_name, --仓库
                        T1.location_store_id,
                        T4."name" AS location_store_name, --货位
                        T5.form_enum,             --仓库类型
                        T1.supplier_id,           --供应商
                        T8.name AS supply_name,   --供应商名称
                        T1.inventory_status_enum, --停供状态
                        '0' AS dose_form_code,    --剂型
                        T2.approval_number,       --批准文号/国药准字
                        T10.amount AS retail_price, --零售价
                        T1.tenant_id,             --修复：添加逗号
                        COALESCE(in_counts.in_count, 0) AS in_count,
                        COALESCE(out_counts.out_count, 0) AS out_count,
                        T1.item_table,
                        T1.item_id
                 FROM wor_inventory_item T1
                          INNER JOIN adm_device_definition T2
                                     ON T1.item_id = T2.id
                                         AND T2.delete_flag = '0'
                          LEFT JOIN adm_location T4
                                    ON T1.location_store_id = T4.id
                                        AND T4.delete_flag = '0'
                          LEFT JOIN adm_location T5
                                    ON T1.location_id = T5.id
                                        AND T5.delete_flag = '0'
                          LEFT JOIN adm_supplier T8
                                    ON T1.supplier_id = T8.id
                                        AND T8.delete_flag = '0'
                          LEFT JOIN adm_charge_item_definition T9
                                    ON T9.instance_table = 'adm_device_definition'
                                        AND T9.instance_id = T2.id
                                        AND T9.delete_flag = '0'
                          LEFT JOIN LATERAL (
                     SELECT amount
                     FROM adm_charge_item_def_detail
                     WHERE definition_id = T9.id
                       AND condition_value = T1.lot_number
                       AND condition_code = '1'--1:批号进价
                       AND delete_flag = '0'
                     ORDER BY create_time DESC
                         LIMIT 1
             ) T10 ON TRUE
    LEFT JOIN (
        SELECT ls.item_table,
               ls.item_id,
               ls.location_id,
               ls.lot_number,
               SUM(CASE WHEN T10.status_enum = '1' THEN 1 ELSE 0 END) AS in_count
        FROM latest_records ls
        LEFT JOIN adm_trace_no_manage T10
            ON T10.item_table = ls.item_table
            AND T10.item_id = ls.item_id
            AND T10.location_id = ls.location_id
            AND T10.lot_number = ls.lot_number
            AND T10.trace_no = ls.trace_no
            AND T10.create_time = ls.latest_time
        GROUP BY ls.item_table, ls.item_id, ls.location_id, ls.lot_number
    ) in_counts
        ON T1.item_table = in_counts.item_table
            AND T1.item_id = in_counts.item_id
            AND T1.location_id = in_counts.location_id
            AND T1.lot_number = in_counts.lot_number
            LEFT JOIN (
            SELECT ls.item_table,
            ls.item_id,
            ls.location_id,
            ls.lot_number,
            SUM(CASE WHEN T10.status_enum = '2' THEN 1 ELSE 0 END) AS out_count
            FROM latest_records ls
            LEFT JOIN adm_trace_no_manage T10
            ON T10.item_table = ls.item_table
            AND T10.item_id = ls.item_id
            AND T10.location_id = ls.location_id
            AND T10.lot_number = ls.lot_number
            AND T10.trace_no = ls.trace_no
            AND T10.create_time = ls.latest_time
            GROUP BY ls.item_table, ls.item_id, ls.location_id, ls.lot_number
            ) out_counts
            ON T1.item_table = out_counts.item_table
            AND T1.item_id = out_counts.item_id
            AND T1.location_id = out_counts.location_id
            AND T1.lot_number = out_counts.lot_number
        WHERE T1.delete_flag = '0'
            ) AS T7
            ${ew.customSqlSegment}
    </select>
    <select id="selectProductDetailsPageTotal"
            resultType="com.openhis.web.inventorymanage.dto.ProductDetailsTotalDto">
        SELECT
            ROUND( SUM ( sale_price ), 2 ) AS total_sale_price,--总零售价
            ROUND( SUM ( purchase_price ), 2 ) AS total_purchase_price --总进价
        FROM
            (
                <if test="itemType == 99 or itemType == 9">
                SELECT
                    ROUND(SUM (ROUND( T4.amount, 2 ) * ( ROUND( T1.quantity, 2 ) / ROUND( T2.part_percent, 2 ) ) ),2 ) AS sale_price,
                    ROUND(SUM (ROUND( T1.price, 2 ) * ( ROUND( T1.quantity, 2 ) / ROUND( T2.part_percent, 2 ) ) ),2 ) AS purchase_price
                FROM
                    wor_inventory_item T1
                        INNER JOIN adm_device_definition T2 ON T1.item_id = T2.ID
                        AND T2.delete_flag = '0'
                        LEFT JOIN adm_charge_item_definition T3 ON T3.instance_table = 'adm_device_definition'
                        AND T3.instance_id = T1.item_id
                        AND T3.delete_flag = '0'
                        LEFT JOIN LATERAL ( SELECT amount FROM adm_charge_item_def_detail WHERE definition_id = T3.ID AND condition_value = T1.lot_number AND condition_code = '1' AND delete_flag = '0' ORDER BY create_time DESC LIMIT 1 ) T4 ON TRUE
		                LEFT JOIN adm_supplier T5 ON T1.supplier_id = T5.ID
                            AND T5.delete_flag = '0'
                    <if test="sqlWhere != '' and sqlWhere != null">
                        <where>
                            ${sqlWhere}
                        </where>
                    </if>
                </if>
                <if test="itemType == 99 ">
                UNION ALL
                </if>
                <if test="itemType == 99 or itemType == 0">
                SELECT
                    ROUND(SUM (ROUND( T4.amount, 2 ) * ( ROUND( T1.quantity, 2 ) / ROUND( T2.part_percent, 2 ) ) ),2 ) AS sale_price,
                    ROUND(SUM (ROUND( T1.price, 2 ) * ( ROUND( T1.quantity, 2 ) / ROUND( T2.part_percent, 2 ) ) ),2 ) AS purchase_price
                FROM
                    wor_inventory_item T1
                        INNER JOIN med_medication_definition T2 ON T1.item_id = T2.ID
                        AND T2.delete_flag = '0'
                        LEFT JOIN adm_charge_item_definition T3 ON T3.instance_table = 'med_medication_definition'
                        AND T3.instance_id = T1.item_id
                        AND T3.delete_flag = '0'
                        LEFT JOIN LATERAL ( SELECT amount FROM adm_charge_item_def_detail WHERE definition_id = T3.ID AND condition_value = T1.lot_number  AND condition_code = '1' AND delete_flag = '0' ORDER BY create_time DESC LIMIT 1 ) T4 ON TRUE
                        LEFT JOIN adm_supplier T5 ON T1.supplier_id = T5.ID
                        AND T5.delete_flag = '0'
                    <if test="sqlWhere != '' and sqlWhere != null">
                        <where>
                        ${sqlWhere}
                        </where>
                    </if>
                </if>
            )
    </select>
    <select id="selectExpirationWarning"
            resultType="com.openhis.web.inventorymanage.dto.ProductDetailsPageDto">
        select T6.category_code,         --药品类型
               T6.item_type,             --药品类型区分
               T6.bus_no,                --药品编码
               T6.medicine_name,         --药品名称
               T6.py_str,                --药品拼音
               T6.total_volume,          --规格
               T6.manufacturer_text,     --厂家
               T6.lot_number,            --批次号
               T6.production_date,       --生产日期
               T6.expiration_date,       --失效日期
               T6.remaining_days,        --剩余天数
               T6.remaining_month,       --剩余月数
               T6.quantity,              --库存（小单位）
               T6.specification_quantity,--规格库存(小单位)
               T6.item_min_quantity,     --最小库存警戒数量
               T6.item_max_quantity,     --最大库存警戒数量
               T6.min_unit_code,         --库存单位
               T6.status_enum,           --药品状态（药品停用）
               T6.inventory_status_enum, --停供状态
               T6.tenant_id
        from (select T2.category_code,                                             --药品类型
                     '0'                                       as item_type,       --药品类型区分
                     T2.bus_no,                                                    --药品编码
                     T2."name"                                 as medicine_name,   --药品名称
                     T2.py_str,                                                    --药品拼音
                     T3.total_volume,                                              --规格
                     T2.manufacturer_text,                                         --厂家
                     T1.lot_number,                                                --批次号
                     T1.production_date,                                           --生产日期
                     T1.expiration_date,                                           --失效日期
                     (T1.expiration_date::date - CURRENT_DATE) as remaining_days,  --剩余天数
                     ((EXTRACT(YEAR FROM T1.expiration_date) - EXTRACT(YEAR FROM CURRENT_DATE)) * 12
                         + (EXTRACT(MONTH FROM T1.expiration_date) -
                            EXTRACT(MONTH FROM CURRENT_DATE))) as remaining_month, --剩余月数
                     T1.quantity,                                                  --库存（小单位）
                     COALESCE(CAST(T8.specification_quantity AS DECIMAL(18, 6)), 0.00)         AS specification_quantity,--规格库存(小单位)
                     T2.item_min_quantity * T2.part_percent AS item_min_quantity,                                         --最小库存警戒数量
                     T2.item_max_quantity * T2.part_percent AS item_max_quantity,                                         --最大库存警戒数量
                     T2.min_unit_code,                                             --库存单位
                     T3.status_enum,                                               --药品状态（药品停用）
                     T1.inventory_status_enum,                                     --停供状态
                     T1.tenant_id
              from wor_inventory_item T1
                       inner join med_medication_definition T2
                                  on T1.item_id = T2.id
                                      and T2.delete_flag = '0'
                       left join med_medication T3
                                 on T2.id = T3.medication_def_id
                                     and T3.delete_flag = '0'
                       left join adm_location T4
                                 on T1.location_store_id = T4.id
                                     and T4.delete_flag = '0'
                       left join adm_location T5
                                 on T1.location_id = T5.id
                                     and T5.delete_flag = '0'
                        LEFT JOIN (SELECT i1.item_table,
                                          i1.item_id,
                                          COALESCE(CAST(SUM(i1.quantity) AS DECIMAL(18, 6)), 0.00) AS specification_quantity
                                   FROM wor_inventory_item i1
                                       LEFT JOIN med_medication_definition i2 ON i1.item_id = i2.ID
                                          AND i2.delete_flag = '0'
                                   WHERE i1.item_table = 'med_medication_definition'
                                     AND i1.delete_flag = '0'
                                   GROUP BY i1.item_table,
                                            i1.item_id) T8
                                   ON T8.item_table = 'med_medication_definition'
                                      AND T8.item_id = T2.ID
              where T1.delete_flag = '0'
                <if test="flg != null">
                  and (T8.specification_quantity  <![CDATA[ <= ]]> T2.item_min_quantity * T2.part_percent
                  or T8.specification_quantity  <![CDATA[ >= ]]> T2.item_max_quantity * T2.part_percent)
                </if>
              order by T2.bus_no ASC, --药品编码
                       T2."name" ASC --药品名称
             ) as T6
            ${ew.customSqlSegment}
        union all
        select T7.category_code,         --药品类型
               T7.item_type,             --药品类型区分
               T7.bus_no,                --药品编码
               T7.medicine_name,         --药品名称
               T7.py_str,                --药品拼音
               T7.total_volume,          --规格
               T7.manufacturer_text,     --厂家
               T7.lot_number,            --批次号
               T7.production_date,       --生产日期
               T7.expiration_date,       --失效日期
               T7.remaining_days,        --剩余天数
               T7.remaining_month,       --剩余月数
               T7.quantity,              --库存（小单位）
               T7.specification_quantity,--规格库存(小单位)
               T7.item_min_quantity,     --最小库存警戒数量
               T7.item_max_quantity,     --最大库存警戒数量
               T7.min_unit_code,         --库存单位
               T7.status_enum,           --药品状态（药品停用）
               T7.inventory_status_enum, --停供状态
               T7.tenant_id
        from (select T2.category_code,                                             --药品类型
                     '9'                                       as item_type,       --药品类型区分
                     T2.bus_no,                                                    --药品编码
                     T2."name"                                 as medicine_name,   --药品名称
                     T2.py_str,                                                    --药品拼音
                     T2.size                                   as total_volume,    --规格
                     T2.manufacturer_text,                                         --厂家
                     T1.lot_number,                                                --批次号
                     T1.production_date,                                           --生产日期
                     T1.expiration_date,                                           --失效日期
                     (T1.expiration_date::date - CURRENT_DATE) as remaining_days,  --剩余天数
                     ((EXTRACT(YEAR FROM T1.expiration_date) - EXTRACT(YEAR FROM CURRENT_DATE)) * 12
                         + (EXTRACT(MONTH FROM T1.expiration_date) -
                            EXTRACT(MONTH FROM CURRENT_DATE))) as remaining_month, --剩余月数
                     T1.quantity,                                                  --库存（小单位）
                     COALESCE(CAST(T8.specification_quantity AS DECIMAL(18, 6)), 0.00)         AS specification_quantity,--规格库存(小单位)
                     T2.item_min_quantity * T2.part_percent AS item_min_quantity,                                         --最小库存警戒数量
                     T2.item_max_quantity * T2.part_percent AS item_max_quantity,                                         --最大库存警戒数量
                     T2.min_unit_code,                                             --库存单位
                     T2.status_enum,                                               --药品状态（药品停用）
                     T1.inventory_status_enum,                                     --停供状态
                     T1.tenant_id
              from wor_inventory_item T1
                       inner join adm_device_definition T2
                                  on T1.item_id = T2.id
                                      and T2.delete_flag = '0'
                       left join adm_location T4
                                 on T1.location_store_id = T4.id
                                     and T4.delete_flag = '0'
                       left join adm_location T5
                                 on T1.location_id = T5.id
                                     and T5.delete_flag = '0'
                       LEFT JOIN (SELECT i1.item_table,
                                         i1.item_id,
                                         COALESCE(CAST(SUM(i1.quantity) AS DECIMAL(18, 6)), 0.00) AS specification_quantity
                                  FROM wor_inventory_item i1
                                           LEFT JOIN adm_device_definition i2 ON i1.item_id = i2.ID
                                      AND i2.delete_flag = '0'
                                  WHERE i1.item_table = 'adm_device_definition'
                                    AND i1.delete_flag = '0'
                                  GROUP BY i1.item_table,
                                           i1.item_id) T8
                                 ON T8.item_table = 'adm_device_definition'
                                     AND T8.item_id = T2.ID
              where T1.delete_flag = '0'
              <if test="flg != null">
                  and (T8.specification_quantity  <![CDATA[ <= ]]> T2.item_min_quantity * T2.part_percent
                  or T8.specification_quantity  <![CDATA[ >= ]]> T2.item_max_quantity * T2.part_percent)
              </if>
              order by T2.bus_no ASC, --药品编码
                       T2."name" ASC --药品名称
             ) as T7
            ${ew.customSqlSegment}
    </select>
</mapper>
