<?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.dayou.mapper.OrderFundMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.dayou.entity.OrderFund">
        <result column="id" property="id" />
        <result column="deleted" property="deleted" />
        <result column="created" property="created" />
        <result column="modified" property="modified" />
        <result column="business_type" property="businessType" />
        <result column="business_id" property="businessId" />
        <result column="should_amount" property="shouldAmount" />
        <result column="real_amount" property="realAmount" />
        <result column="remark" property="remark" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id,
        deleted,
        created,
        modified,
        business_type, business_id, should_amount, real_amount, remark
    </sql>

    <update id="updateRealAmount">
        update order_fund set real_amount = (ifnull(real_amount,0) + #{thisTimeAmount}) where id = #{id}
    </update>

    <update id="updateRealAmountByOrderId">
        update order_fund set real_amount = (ifnull(real_amount,0) + #{thisTimeAmount}) where order_id = #{orderId} and deleted = 0
    </update>

    <select id="residueNotAllotAmount" parameterType="java.lang.Long" resultType="java.math.BigDecimal">
        SELECT (`of`.real_amount - (SELECT IFNULL(SUM(real_amount), 0) AS ca
                                    FROM production_fund
                                    WHERE deleted = 0 AND order_fund_id = #{orderFundId})
                   ) AS notClaimAmount
        FROM order_fund `of`
        WHERE `of`.id = #{orderFundId}
          AND `of`.deleted = 0
    </select>

    <!--更新折扣比例-->
    <update id="updateDiscountByOrderIdAfter">
        UPDATE order_fund
        SET discount =  order_fund.real_amount / order_fund.should_amount
        WHERE id = #{orderFundId}
    </update>

    <select id="getAllOrderFund" resultType="com.dayou.entity.OrderFund">
        SELECT
            off.*,
            mp.report_no,
            mp.production,
            mp.standard_amount
        FROM
            order_fund off
                LEFT JOIN ( SELECT * FROM major_production WHERE deleted = 0 AND production = 'REPORT' ) mp ON mp.major_id = off.business_id
        WHERE
            off.business_type = 'MAJOR_BUSINESS'
          AND off.real_amount IS NOT NULL
          AND mp.report_no IS NOT NULL
    </select>

</mapper>
