<?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.ruoyi.web.v2.mapper.JsDivideCircleMapper">
    <!--获取待宰圈盘点数据-->
    <select id="review" resultType="com.ruoyi.web.v2.model.JsDivideCircle">
        SELECT
            eb.animal_type ,
            p.id as pigpen_id,

            p.pigpen_name,
            jdc.divide_time,
            jdc.id,
            jdc.supplier_id,
            jdc.supplier_name,
            jdc.animal_cert_no,
            jdc.variety,
            COALESCE(jdc.amount, 0) - COALESCE(jri.deal_amount_total, 0) AS amount,
            jdc.create_time,
            jdc.entrance_batch_id,
            jdc.series_no,
            COALESCE(jdc.status_flag, 'closed') AS status_flag
        FROM pigpen AS p
        LEFT JOIN
             (
                 SELECT
                     *
                 FROM
                     js_divide_circle
                 WHERE status_flag='opened'

             )
                 AS jdc ON jdc.id = (
                 SELECT
                     id
                 FROM
                     js_divide_circle
                 WHERE pigpen_id = p.id
                 ORDER BY id DESC
                 LIMIT 1
            )
        LEFT JOIN (
            SELECT
                divide_circle_id,SUM(deal_amount) AS deal_amount_total
            FROM
                js_rest_inspection
            GROUP BY divide_circle_id
            ) AS jri ON jdc.id = jri.divide_circle_id
        left  join entrance_batch  eb  on   jdc.entrance_batch_id = eb.id
        WHERE p.del_flag = '0'
        ORDER BY p.pigpen_name ASC
    </select>

    <!--根据待宰圈ID获取最新的分圈，或者根据分圈ID获取分圈信息-->
    <select id="selectDivideCircle" parameterType="com.ruoyi.web.v2.model.JsDivideCircle" resultType="com.ruoyi.web.v2.model.JsDivideCircle">
        SELECT *
        FROM js_divide_circle
        <where>
            <if test="pigpenId !=null">
                and pigpen_id = #{pigpenId}
            </if>
            <if test="id !=null">
                and id = #{id}
            </if>
        </where>
        ORDER BY id DESC
        LIMIT 1
    </select>
</mapper>
