<?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.ym.mec.biz.dal.dao.StudentPaymentRouteOrderDao">
    <resultMap id="StudentPaymentRouteOrder" type="com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder">
        <!--@mbg.generated-->
        <!--@Table student_payment_route_order-->
        <id column="id_" property="id"/>
        <result column="route_organ_id_" property="routeOrganId"/>
        <result column="route_amount_" property="routeAmount"/>
        <result column="route_balance_amount_" property="routeBalanceAmount"/>
        <result column="mer_no_" property="merNo"/>
        <result column="order_no_" property="orderNo"/>
        <result column="fee_flag_" property="feeFlag"/>
        <result column="user_id_" property="userId"/>
        <result column="school_id_" property="schoolId"/>
        <result column="trans_no_" property="transNo"/>
        <result column="pay_time_" property="payTime"/>
        <result column="sale_amount_" property="saleAmount"/>
        <result column="service_amount_" property="serviceAmount"/>
        <result column="service_fee_" property="serviceFee"/>
        <result column="memo_" property="memo"/>
        <result column="goods_json_" property="goodsJson"/>
        <result column="audit_status_" property="auditStatus" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler" />
        <result column="audit_comment_" property="auditComment"/>
        <result column="calender_id_" property="calenderId"/>
        <result column="create_time_" property="createTime"/>
        <result column="create_by_" property="createBy"/>
        <result column="update_time_" property="updateTime"/>
        <result column="update_by_" property="updateBy"/>
        <result column="tenant_id_" property="tenantId"/>
        <result column="type_" property="type" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
    </resultMap>

    <resultMap id="StudentPaymentRouteOrderDto" type="com.ym.mec.biz.dal.dto.StudentPaymentRouteOrderDto"
               extends="com.ym.mec.biz.dal.dao.StudentPaymentOrderDao.StudentPaymentOrder">
        <result column="username_" property="user.username"/>
        <result column="phone_" property="user.phone"/>
        <result column="route_organ_id_" property="routeOrganId"/>
        <result column="route_amount_" property="routeAmount"/>
        <result column="route_balance_amount_" property="routeBalanceAmount"/>
        <result column="mer_no_" property="merNo"/>
        <result column="order_no_" property="orderNo"/>
        <result column="fee_flag_" property="feeFlag"/>
        <result column="route_organ_name_" property="routeOrganName"/>
    </resultMap>

    <resultMap id="StudentPaymentRouteOrderMap" type="com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder" extends="StudentPaymentRouteOrder">
        <result column="username_" property="student.username"/>
        <result column="phone_" property="student.phone"/>
        <result column="school_name_" property="cooperationOrgan.name"/>
        <result column="organ_name_" property="organ.name"/>
        <result column="operator_name_" property="operator.username"/>
    </resultMap>

    <sql id="Base_Column_List">
        <!--@mbg.generated-->
        id_, route_organ_id_, route_amount_,route_balance_amount_, mer_no_, order_no_, fee_flag_,user_id_,
school_id_,trans_no_,pay_time_,sale_amount_,service_amount_,service_fee_,memo_,goods_json_,audit_status_,audit_comment_,
calender_id_,create_time_,create_by_,update_time_,update_by_,tenant_id_,type_
    </sql>
    <select id="get" parameterType="java.lang.Long" resultMap="StudentPaymentRouteOrderMap">
        <!--@mbg.generated-->
       SELECT spro.*,u.username_,u.phone_,s.name_ school_name_,o.name_ organ_name_,ou.username_ operator_name_ FROM student_payment_route_order spro
        left join sys_user u on spro.user_id_ = u.id_
        left join sys_user ou on ou.id_ = spro.create_by_
        left join school s on s.id_ = spro.school_id_
        left join organization o on o.id_ = spro.route_organ_id_
        where spro.id_ = #{id}
    </select>
    <delete id="delete" parameterType="java.lang.Long">
        <!--@mbg.generated-->
        delete from student_payment_route_order
        where id_ = #{id}
    </delete>
    <insert id="insert" keyColumn="id_" keyProperty="id"
            parameterType="com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder" useGeneratedKeys="true">
        <!--@mbg.generated-->
        insert into student_payment_route_order (route_organ_id_, route_amount_,route_balance_amount_, mer_no_,
        order_no_, fee_flag_,user_id_,school_id_,trans_no_,pay_time_,sale_amount_,service_amount_,service_fee_,
        memo_,goods_json_,audit_status_,audit_comment_,calender_id_,create_time_,update_time_,create_by_,update_by_,tenant_id_,type_)
        values (#{routeOrganId}, #{routeAmount},#{routeBalanceAmount}, #{merNo}, #{orderNo}, #{feeFlag},#{userId},
                #{schoolId},#{transNo},#{payTime},#{saleAmount},#{serviceAmount},#{serviceFee},#{memo},#{goodsJson},
                #{auditStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{auditComment},#{calenderId},
                #{createTime},#{updateTime},#{createBy},#{updateBy},#{tenantId},#{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler})
    </insert>
    <update id="update" parameterType="com.ym.mec.biz.dal.entity.StudentPaymentRouteOrder">
        <!--@mbg.generated-->
        update student_payment_route_order
        <set>
            <if test="routeOrganId != null">
                route_organ_id_ = #{routeOrganId},
            </if>
            <if test="routeAmount != null">
                route_amount_ = #{routeAmount},
            </if>
            <if test="routeBalanceAmount != null">
                route_balance_amount_ = #{routeBalanceAmount},
            </if>
            <if test="merNo != null">
                mer_no_ = #{merNo},
            </if>
            <if test="orderNo != null">
                order_no_ = #{orderNo},
            </if>
            <if test="feeFlag != null">
                fee_flag_ = #{feeFlag},
            </if>
                user_id_ = #{userId},
            <if test="schoolId != null and schoolId==999999999">
                school_id_ = null,
            </if>
            <if test="schoolId != null and schoolId!=999999999">
                school_id_ = #{schoolId},
            </if>
            <if test="transNo != null">
                trans_no_ = #{transNo},
            </if>
            <if test="payTime != null">
                pay_time_ = #{payTime},
            </if>
                sale_amount_ = #{saleAmount},
                service_amount_ = #{serviceAmount},
            <if test="serviceFee != null">
                service_fee_ = #{serviceFee},
            </if>
            <if test="memo != null">
                memo_ = #{memo},
            </if>
                goods_json_ = #{goodsJson},
            <if test="auditStatus != null">
                audit_status_ = #{auditStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
            </if>
            <if test="auditComment != null">
                audit_comment_ = #{auditComment},
            </if>
                calender_id_ = #{calenderId},
            <if test="updateTime != null">
                update_time_ = #{updateTime},
            </if>
            <if test="updateBy != null">
                update_by_ = #{updateBy},
            </if>
        </set>
        where id_ = #{id} and tenant_id_ = #{tenantId}
    </update>

    <insert id="batchAdd" parameterType="java.util.List" useGeneratedKeys="true" keyColumn="id"
            keyProperty="id">
        INSERT INTO student_payment_route_order
        (order_no_,route_organ_id_, route_amount_,route_balance_amount_, mer_no_,fee_flag_,user_id_,
        school_id_,trans_no_,pay_time_,sale_amount_,service_amount_,service_fee_,memo_,goods_json_,audit_status_,
        audit_comment_,calender_id_,create_time_,update_time_,create_by_,update_by_,tenant_id_,type_)
        VALUE
        <foreach collection="routeOrders" item="routeOrder" separator=",">
            (#{routeOrder.orderNo},#{routeOrder.routeOrganId},#{routeOrder.routeAmount},
            #{routeOrder.routeBalanceAmount},#{routeOrder.merNo},#{routeOrder.feeFlag},
            #{routeOrder.userId},#{routeOrder.schoolId},#{routeOrder.transNo},#{routeOrder.payTime},
            #{routeOrder.saleAmount},#{routeOrder.serviceAmount},#{routeOrder.serviceFee},#{routeOrder.memo},#{routeOrder.goodsJson},
            #{routeOrder.auditStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{routeOrder.auditComment},
            #{routeOrder.calenderId},NOW(),NOW(),#{routeOrder.createBy},#{routeOrder.updateBy},#{routeOrder.tenantId},
            #{routeOrder.type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler})
        </foreach>
    </insert>

    <select id="queryPageOrder" parameterType="map" resultMap="StudentPaymentRouteOrderDto">
        SELECT spo.*,spro.*,u.username_,u.phone_,o.name_ route_organ_name_ FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro ON spo.order_no_ = spro.order_no_
        left join sys_user u on spo.user_id_ = u.id_
        left join organization o on o.id_ = spro.route_organ_id_
        <include refid="queryPaymentOrder"/>
        ORDER BY spo.id_ DESC
        <include refid="global.limit"/>
    </select>
    <select id="getOrderMoneyAmount" parameterType="map" resultMap="StudentPaymentRouteOrderDto">
        SELECT SUM(spro.route_amount_) actual_amount_,SUM(spro.route_balance_amount_)
        balance_payment_amount_ FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro on spo.order_no_ = spro.order_no_
        <include refid="queryPaymentOrder"/>
    </select>

    <select id="getChargeAmount" parameterType="map" resultType="java.math.BigDecimal">
        SELECT SUM(spro.route_amount_) FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro ON spo.order_no_=spro.order_no_
        LEFT JOIN sporadic_charge_info sci ON spo.music_group_id_ = sci.id_
        <include refid="queryPaymentOrder"/>
    </select>

    <!-- 查询当前表的总记录数 -->
    <select id="queryCount" resultType="int" parameterType="map">
        SELECT COUNT(spo.id_) FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro ON spo.order_no_ = spro.order_no_
        LEFT JOIN sys_user u on spo.user_id_ = u.id_
        <include refid="queryPaymentOrder"/>
    </select>

    <sql id="queryPaymentOrder">
        <where>
        	spo.tenant_id_ = #{tenantId}
            <if test="userIds != null">
                AND spo.user_id_ IN
                <foreach collection="userIds" item="userId" open="(" close=")" separator=",">
                    #{userId}
                </foreach>
            </if>
            <if test="organId != null and organId != ''">
                AND FIND_IN_SET(spo.organ_id_,#{organId})
            </if>
            <if test="orderStartDate != null">
                AND DATE_FORMAT(spo.create_time_,'%Y-%m-%d') &gt;= #{orderStartDate}
            </if>
            <if test="orderEndDate != null">
                AND DATE_FORMAT(spo.create_time_,'%Y-%m-%d') &lt;= #{orderEndDate}
            </if>
            <if test="paymentType != null">
                AND spo.type_ = #{paymentType}
            </if>
            <if test="remark != null">
                AND spo.memo_ LIKE CONCAT('%',#{remark},'%')
            </if>
            <if test="studentId != null">
                AND spo.user_id_ = #{studentId}
            </if>
            <if test="paymentStatus != null">
                AND spo.status_ = #{paymentStatus}
            </if>
            <if test="paymentChannel != null">
                AND spo.payment_channel_ NOT IN (#{paymentChannel})
            </if>
            <if test='orderType != null and orderType.toString()=="1".toString()'>
                AND spo.com_amount_ > 0
            </if>
            <if test='orderType != null and orderType.toString()=="2".toString()'>
                AND spo.per_amount_ > 0
            </if>
            <if test="routingOrganId != null and routingOrganId != ''">
                AND FIND_IN_SET(spro.route_organ_id_,#{routingOrganId})
            </if>
            <if test="actualAmount != null">
                AND spo.actual_amount_ >= #{actualAmount}
            </if>

            <if test="balancePaymentAmount != null">
                AND spo.balance_payment_amount_ >= #{balancePaymentAmount}
            </if>
            <if test="lessActualAmount != null">
                <![CDATA[ AND spo.actual_amount_ <= #{lessActualAmount}]]>
            </if>
            <if test="lessBalancePaymentAmount != null">
                <![CDATA[AND spo.balance_payment_amount_ <= #{lessBalancePaymentAmount}]]>
            </if>
            <if test="orderNo != null">
                AND spo.order_no_ = #{orderNo}
            </if>
            <if test="merNos != null">
                AND spro.mer_no_ = #{merNos}
            </if>
            <if test="transNo != null">
                AND spo.trans_no_ = #{transNo}
            </if>
            <if test="chargeType != null">
                AND spo.group_type_='SPORADIC'
                AND sci.charge_type_ = #{chargeType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
            </if>
            <if test="noneTqType != null">
                AND (spo.mer_nos_ IS NULL OR spo.mer_nos_ != '淘器微信')
            </if>
        </where>
    </sql>
    <select id="getRouteOrders" resultMap="StudentPaymentRouteOrder">
        SELECT *
        FROM student_payment_route_order
        WHERE order_no_ = #{orderNo}
    </select>

    <!-- 统计已收款项 -->
    <select id="getRouteOrderAmount" resultType="java.math.BigDecimal">
        SELECT SUM(route_amount_)
        FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro ON spo.order_no_ = spro.order_no_
        WHERE spro.route_organ_id_ = #{routeOrganId} AND spo.status_ IN ('SUCCESS','ING') AND spo.payment_channel_ IN
        <foreach collection="paymentChannelEnumList" item="paymentChannel" open="(" close=")" separator=",">
            #{paymentChannel,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
        </foreach>
        <if test="startTime != null">
            AND spo.create_time_ >= #{startTime,jdbcType=DATE}
        </if>
    </select>

    <select id="ExportQueryPage1" resultMap="com.ym.mec.biz.dal.dao.StudentPaymentOrderDao.orderAndDetail"
            parameterType="map">
        SELECT spo.*,
        SUM(spro.route_amount_) routeAmount,
        SUM(spro.route_balance_amount_) routeBalance,
        SUM(spro.sale_amount_) sale_amount_,
        SUM(spro.service_amount_) service_amount_,
        SUM(spro.service_fee_) service_fee_,
        spro.mer_no_ routeMerNo,
        spro.fee_flag_ feeFlag,
        sci.charge_type_,
        spo.expect_amount_ + spo.coupon_remit_fee_ orderAmount,
        o.name_ organ_name
        FROM student_payment_route_order spro
        LEFT JOIN student_payment_order spo ON spo.order_no_ = spro.order_no_
        LEFT JOIN sporadic_charge_info sci ON spo.music_group_id_ = sci.id_
        LEFT JOIN organization o on spro.route_organ_id_ = o.id_
        <include refid="queryPaymentOrder"/>
        GROUP BY spro.order_no_,spro.mer_no_
        ORDER BY spro.id_
    </select>



    <select id="ExportQueryPage" resultMap="com.ym.mec.biz.dal.dao.StudentPaymentOrderDao.orderAndDetail"
            parameterType="map">
        SELECT spo.*,u.username_,spod.id_ detail_id_,spod.type_ detail_type_,spod.price_
        detail_price_,spod.kit_group_purchase_type_ detail_kit_group_purchase_type_,spod.income_item_,spod.income_,
        sci.charge_type_,g.id_ goods_id, g.name_ goods_name,o.name_ organ_name,spro.route_amount_
        routeAmount,spro.route_balance_amount_ routeBalance,spro.sale_amount_,spro.service_amount_,spro.service_fee_,
        spro.mer_no_ routeMerNo,spro.fee_flag_ feeFlag
        FROM student_payment_order spo
        LEFT JOIN student_payment_route_order spro ON spro.order_no_ = spo.order_no_
        LEFT JOIN sys_user u on spo.user_id_ = u.id_
        LEFT JOIN student_payment_order_detail spod on spo.id_ = spod.payment_order_id_
        LEFT JOIN organization o on spro.route_organ_id_ = o.id_
        LEFT JOIN sporadic_charge_info sci on spo.music_group_id_ = sci.id_
        LEFT JOIN goods g on FIND_IN_SET(g.id_,spod.goods_id_list_)
        <include refid="queryPaymentOrder"/>
        ORDER BY spro.id_
    </select>
    <select id="countByTransNo" resultType="java.lang.String">
        SELECT trans_no_ FROM student_payment_route_order WHERE trans_no_ IN
        <foreach collection="transNos" open="(" close=")" item="item" separator=",">
            #{item}
        </foreach>
    </select>

    <delete id="deleteByOrderNo">
        DELETE
        FROM student_payment_route_order
        where order_no_ = #{orderNo}
    </delete>

    <!-- 向数据库增加一条记录 -->
    <insert id="insertOrder" parameterType="com.ym.mec.biz.dal.entity.StudentPaymentOrder" useGeneratedKeys="true"
            keyColumn="id" keyProperty="id">
        INSERT INTO student_payment_order
        (id_, group_type_, user_id_, organ_id_, routing_organ_id_, type_, expect_amount_, actual_amount_, com_amount_,
         per_amount_,
         balance_payment_amount_, remit_fee_, course_remit_fee_, trans_no_,
         status_, memo_, create_time_, update_time_, payment_channel_, payment_business_channel_,
         payment_account_no_, mer_nos_, order_no_, music_group_id_, class_group_id_, pay_time_,tenant_id_)
        VALUES (#{id}, #{groupType,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
                #{userId}, #{organId}, #{routingOrganId},
                #{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
                #{expectAmount}, #{actualAmount}, #{comAmount}, #{perAmount}, #{balancePaymentAmount},
                #{remitFee}, #{courseRemitFee}, #{transNo},
                #{status,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}, #{memo}, #{createTime}, now(),
                #{paymentChannel}, #{paymentBusinessChannel}, #{paymentAccountNo}, #{merNos}, #{orderNo},
                #{musicGroupId},
                #{classGroupId}, #{payTime},#{tenantId})
    </insert>

    <select id="queryAuditCount" parameterType="map" resultType="int">
		SELECT count(spro.id_) FROM student_payment_route_order spro
        left join sys_user u on spro.user_id_ = u.id_
        <where>
        	spro.tenant_id_ = #{tenantId}
        	<if test="transNo != null and transNo != ''">
        		and spro.trans_no_ = #{transNo}
        	</if>
        	<if test="organId != null and organId != ''">
        		and find_in_set(spro.route_organ_id_, #{organId})
        	</if>
        	<if test="auditStatus != null">
        		and spro.audit_status_ = #{auditStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
        	</if>
            <if test="type != null and type != ''">
                <if test="type == 'SERVICE'">
                    and (spro.service_amount_ is not null and spro.service_amount_ &gt; 0)
                </if>
                <if test="type == 'SELL'">
                    and (spro.sale_amount_ is not null and spro.sale_amount_ &gt; 0)
                </if>
            </if>
            <if test="noneTqType != null">
                and (spro.mer_no_ IS NULL OR spro.mer_no_ != '淘器微信')
            </if>
        </where>
		order by spro.id_ desc
	</select>

	<select id="queryAuditPage" parameterType="map" resultMap="StudentPaymentRouteOrderMap">
		SELECT spro.*,u.username_,u.phone_,s.name_ school_name_,o.name_ organ_name_,ou.real_name_ operator_name_ FROM student_payment_route_order spro
        left join sys_user u on spro.user_id_ = u.id_
        left join sys_user ou on ou.id_ = spro.create_by_
        left join cooperation_organ s on s.id_ = spro.school_id_
        left join organization o on o.id_ = spro.route_organ_id_
        <where>
        	spro.tenant_id_ = #{tenantId}
        	<if test="transNo != null and transNo != ''">
        		and spro.trans_no_ = #{transNo}
        	</if>
        	<if test="organId != null and organId != ''">
        		and find_in_set(spro.route_organ_id_, #{organId})
        	</if>
        	<if test="auditStatus != null">
        		and spro.audit_status_ = #{auditStatus,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler}
        	</if>
        	<if test="type != null and type != ''">
        		<if test="type == 'SERVICE'">
                    and (spro.service_amount_ is not null and spro.service_amount_ &gt; 0)
        		</if>
        		<if test="type == 'SELL'">
                    and (spro.sale_amount_ is not null and spro.sale_amount_ &gt; 0)
        		</if>
        	</if>
            <if test="noneTqType != null">
                and (spro.mer_no_ IS NULL OR spro.mer_no_ != '淘器微信')
            </if>
        </where>
		order by spro.id_ desc
		<include refid="global.limit" />
	</select>
    <select id="sumAmountByCalenderId" resultType="java.math.BigDecimal">
        SELECT IF(SUM(route_amount_) IS NULL,0, SUM(route_amount_)) FROM student_payment_route_order WHERE calender_id_ = #{calenderId} AND audit_status_='PASS'
    </select>
    <select id="getByOrderNo" resultMap="StudentPaymentRouteOrder">
        SELECT * FROM student_payment_route_order WHERE order_no_ = #{orderNo} LIMIT 1
    </select>
    <select id="getCountFeeFlagNum" resultType="com.ym.mec.biz.dal.dto.FeeFlagNumDto">
        SELECT SUM(1) totalNum,
               SUM(IF(fee_flag_='Y',1, 0)) yesNum
        FROM student_payment_route_order WHERE order_no_=#{orderNo}
    </select>

    <select id="queryCountFeeFlagNum" resultType="com.ym.mec.biz.dal.dto.FeeFlagNumDto">
        SELECT SUM(1) totalNum,
               SUM(IF(fee_flag_='Y',1, 0)) yesNum, order_no_ orderNo
        FROM student_payment_route_order WHERE order_no_ IN
        <foreach collection="orderNos" item="orderNo" open="(" close=")" separator=",">
            #{orderNo}
        </foreach>
    </select>


</mapper>