<?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.hys.app.mapper.erp.StockStatisticsMapper">

    <!-- 查询商品库存统计信息 -->
    <select id="selectStockStatisticsPage" resultType="com.hys.app.model.erp.dos.StockStatistics" useCache="false">
        select
            warehouse_entry_sn as stock_sn,
            product_id,
            product_name,
            product_sn,
            product_specification specification,
            category_name,
            product_unit unit,
            SUM(IF(source_type = 'WAREHOUSE_ENTRY', change_num, 0)) as in_num,
            SUM(IF(source_type = 'WAREHOUSE_OUT', change_num, 0)) as out_num,
            SUM(IF(source_type = 'SUPPLIER_RETURN', change_num, 0)) as supplier_return_num,
            SUM(IF(source_type = 'ORDER_RETURN', change_num, 0)) as order_return_num,
            SUM(IF(source_type = 'RETAIL_ORDER', change_num, 0)) as retail_order_num,
            SUM(IF(source_type = 'STOCK_TRANSFER' and change_type = 'Reduce', change_num, 0)) as transfer_out_num,
            SUM(IF(source_type = 'STOCK_TRANSFER' and change_type = 'Increase', change_num, 0)) as transfer_in_num,
            SUM(IF(source_type = 'STOCK_DAMAGE', change_num * (IF(change_type = 'Increase', 1, -1)), 0)) as damage_num,
            SUM(change_num * (IF(change_type = 'Increase', 1, -1))) as stock_num,
            SUM(IF(source_type = 'CHANGE_FORM', change_num, 0)) as change_num
        from erp_stock_batch_flow
        <where>
            <if test="param.deptId != null and param.deptId != 0">
                and dept_id = #{param.deptId}
            </if>
            <if test="param.warehouseId != null and param.warehouseId != 0">
                and warehouse_id = #{param.warehouseId}
            </if>
            <if test="param.categoryId != null and param.categoryId != 0">
                and category_id = #{param.categoryId}
            </if>
            <if test="param.productName != null and param.productName != ''">
                and product_name like concat('%', #{param.productName}, '%')
            </if>
            <if test="param.stockSn != null and param.stockSn != ''">
                and warehouse_entry_sn = #{param.stockSn}
            </if>
        </where>
        group by product_id
        <if test="param.groupByWarehouseEntry != null">
            ,warehouse_entry_id
        </if>
        order by create_time desc
    </select>

</mapper>