<?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.yc.ship.module.product.dal.mysql.voyagestockdistribute.VoyageStockDistributeMapper">

    <!--
        一般情况下，尽可能使用 Mapper 进行 CRUD 增删改查即可。
        无法满足的场景，例如说多表关联查询，才使用 XML 编写 SQL。
        代码生成器暂时只生成 Mapper XML 文件本身，更多推荐 MybatisX 快速开发插件来生成查询。
        文档可见：https://www.iocoder.cn/MyBatis/x-plugins/
     -->

    <select id="selectPage" resultType="com.yc.ship.module.product.controller.admin.voyagestockdistribute.vo.VoyageStockDistributeRespPageVO">
        SELECT
        t1.id voyage_id,
        t1.NAME voyage_name,
        t3.NAME ship_name,
        t2.distributor_id,
        t2.store_id,
        sum( ifnull( t2.surplus_num, 0 ) ) sum_surplus_num,
        sum( ifnull( t2.book_num, 0 ) ) sum_book_num
        FROM
        product_voyage t1
        LEFT JOIN product_voyage_stock_distribute t2 ON t1.id = t2.voyage_id
        AND t2.distributor_id = #{params.distributorId}
        <choose>
            <when test="params.storeId != null and params.storeId != ''">
                AND t2.store_id = #{storeId}
            </when>
            <otherwise>
                AND t2.store_id IS NULL
            </otherwise>
        </choose>
        LEFT JOIN resource_ship t3 ON t1.ship_id = t3.id
        WHERE t1.deleted = 0 and t2.deleted = 0 and t3.deleted = 0

        <if test="params.shipId != null and params.shipId != ''">
            AND t1.ship_id = #{params.shipId}
        </if>
        <if test="params.voyageName != null and params.voyageName != ''">
            AND t1.name LIKE CONCAT(CONCAT('%', #{params.voyageName}), '%')
        </if>
        GROUP BY
        t1.id
        order by t1.ship_id asc, t1.start_time asc
    </select>
</mapper>