<?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="cn.iocoder.yudao.module.wealth.dal.mysql.receipt.ReceiptMapper">

    <select id="getReceiptBackPage" resultType="cn.iocoder.yudao.module.wealth.vo.receipt.ReceiptBackVO">
        <!--添加关联订单和应收款表的关联-->
        select er.*,rb.order_no as orderNo,o.tidan_no as tidanNo,
        rb.order_id as orderId
        from ecw_receipt er left join ecw_receivable rb
        on rb.receipt_id=er.id and rb.deleted=0
        left join ecw_order o on o.order_no=rb.order_no and o.deleted=0
        where er.deleted = 0
        <if test="query.receiptNo != null">
            AND er.`receipt_no` = #{query.receiptNo}
        </if>
        <if test="query.customerId != null">
            AND er.`customer_id` = #{query.customerId}
        </if>
        <if test="query.customerName != null">
            AND er.`customer_name` = #{query.customerName}
        </if>
        <if test="query.state != null">
            AND er.`state` = #{query.state}
        </if>
        <if test="query.salesmanId != null">
            AND (er.`salesman_id` = #{query.salesmanId} or er.`customer_id` in(select cus.id from ecw_customer cus where cus.is_customer_service_confirmed = 1 and cus.customer_service = #{query.salesmanId} ))
        </if>
        <if test="query.salesmanName != null">
            AND er.`salesman_name` = #{query.salesmanName}
        </if>
        <if test = "query.beginCreateTime != null and query.endCreateTime != null ">
            AND er.`create_time` between #{query.beginCreateTime} and #{query.endCreateTime}
        </if>
        <if test = "query.numberNo != null and query.numberNo != '' ">
          and er.id in ( SELECT DISTINCT
            t.receipt_id
            FROM
            ecw_receivable t
            LEFT JOIN ecw_order o ON t.order_id = o.order_id
            WHERE
            t.deleted = 0 and t.receipt_id is not null
            AND (
            t.order_no = #{query.numberNo}
            OR o.tidan_no = #{query.numberNo}
            OR o.container_number = #{query.numberNo})
            )
        </if>
        GROUP BY er.receipt_no
    </select>
</mapper>