<?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.CloudTeacherOrderDao">
    <resultMap id="CloudTeacherOrder" type="com.ym.mec.biz.dal.entity.CloudTeacherOrder">
        <!--@mbg.generated-->
        <!--@Table cloud_teacher_order-->
        <id column="id_" property="id"/>
        <result column="organ_id_" property="organId"/>
        <result column="student_id_" property="studentId"/>
        <result column="type_" property="type" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="level_" property="level"/>
        <result column="time_" property="time"/>
        <result column="amount_" property="amount"/>
        <result column="refund_amount_" property="refundAmount"/>
        <result column="status_" property="status"/>
        <result column="start_time_" property="startTime"/>
        <result column="end_time_" property="endTime"/>
        <result column="order_id_" property="orderId"/>
        <result column="platform_order_id_" property="platformOrderId"/>
        <result column="remark_" property="remark"/>
        <result column="active_remark_" property="activeRemark"/>
        <result column="version_" property="version"/>
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="music_group_id_" property="musicGroupId"/>
		<result column="tenant_id_" property="tenantId" />
    </resultMap>
    
    <resultMap type="com.ym.mec.biz.dal.dto.CloudTeacherOrderDto" id="CloudTeacherOrderDto">
    	<id column="id_" property="cloudTeacherOrder.id"/>
        <result column="organ_id_" property="cloudTeacherOrder.organId"/>
        <result column="student_id_" property="cloudTeacherOrder.studentId"/>
        <result column="type_" property="cloudTeacherOrder.type" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="level_" property="cloudTeacherOrder.level"/>
        <result column="time_" property="cloudTeacherOrder.time"/>
        <result column="amount_" property="cloudTeacherOrder.amount"/>
        <result column="refund_amount_" property="cloudTeacherOrder.refundAmount"/>
        <result column="status_" property="cloudTeacherOrder.status"/>
        <result column="start_time_" property="cloudTeacherOrder.startTime"/>
        <result column="end_time_" property="cloudTeacherOrder.endTime"/>
        <result column="order_id_" property="cloudTeacherOrder.orderId"/>
        <result column="platform_order_id_" property="cloudTeacherOrder.platformOrderId"/>
        <result column="trans_status_" property="studentPaymentOrder.status"/>
        <result column="expect_amount_" property="studentPaymentOrder.expectAmount"/>
        <result column="pay_time_" property="studentPaymentOrder.payTime"/>
        <result column="order_create_time_" property="studentPaymentOrder.createTime"/>
        <result column="name_" property="memberRankSetting.name"/>
        <result column="icon_" property="memberRankSetting.icon"/>
        <result column="music_group_id_" property="studentPaymentOrder.musicGroupId"/>
    </resultMap>

    <select id="get" resultMap="CloudTeacherOrder">
        select * from cloud_teacher_order where id_ = #{id}
    </select>
    <delete id="delete">
        delete from cloud_teacher_order
        where id_ = #{id}
    </delete>
    <insert id="insert" keyColumn="id_" keyProperty="id" parameterType="com.ym.mec.biz.dal.entity.CloudTeacherOrder"
            useGeneratedKeys="true">
        INSERT INTO cloud_teacher_order (organ_id_,student_id_, type_, level_, time_, amount_, refund_amount_, status_,
        order_id_,platform_order_id_,start_time_,end_time_,remark_, create_time_, update_time_,music_group_id_,active_remark_,tenant_id_)
        VALUES (#{organId},#{studentId}, #{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{level}, #{time}, #{amount}, #{refundAmount},
        #{status},#{orderId},#{platformOrderId},#{startTime},#{endTime}, #{remark}, NOW(), NOW(),#{musicGroupId},#{activeRemark},#{tenantId})
    </insert>
    <update id="update" parameterType="com.ym.mec.biz.dal.entity.CloudTeacherOrder">
        <!--@mbg.generated-->
        update cloud_teacher_order
        <set>
            <if test="activeRemark != null">
                active_remark_ = #{activeRemark},
            </if>
            <if test="musicGroupId != null">
                music_group_id_ = #{musicGroupId},
            </if>
            <if test="organId != null">
                organ_id_ = #{organId},
            </if>
            <if test="studentId != null">
                student_id_ = #{studentId},
            </if>
            <if test="type != null">
                type_ = #{type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},
            </if>
            <if test="level != null">
                level_ = #{level},
            </if>
            <if test="time != null">
                time_ = #{time},
            </if>
            <if test="amount != null">
                amount_ = #{amount},
            </if>
            <if test="refundAmount != null">
                refund_amount_ = #{refundAmount},
            </if>
            <if test="status != null">
                status_ = #{status},
            </if>
            <if test="startTime != null">
                start_time_ = #{startTime},
            </if>
            <if test="endTime != null">
                end_time_ = #{endTime},
            </if>
            <if test="orderId != null">
                order_id_ = #{orderId},
            </if>
            <if test="platformOrderId != null">
                platform_order_id_ = #{platformOrderId},
            </if>
            <if test="remark != null">
                remark_ = #{remark},
            </if>
            version_ = version_+1,
            update_time_ = NOW(),
        </set>
        where id_ = #{id} AND version_ = #{version} and tenant_id_ = #{tenantId}
    </update>

    <select id="findByPlatformOrderId" resultMap="CloudTeacherOrder">
        select * from cloud_teacher_order cto
        left join sys_user su on cto.student_id_ = su.id_
        where cto.platform_order_id_ = #{platformOrderId} and su.del_flag_ = 0
    </select>

    <resultMap type="com.ym.mec.biz.dal.dto.Mapper" id="mapper">
        <result column="userId" property="key"/>
        <result column="phone" property="value"/>
    </resultMap>
    <select id="findUserNameByOrderId" resultMap="mapper">
        select su.id_ as userId, su.phone_ as phone from cloud_teacher_order cto
        left join sys_user su on cto.student_id_ = su.id_
        where platform_order_id_ = #{platformOrderId} and su.del_flag_ = 0
    </select>

    <update id="updateOrderStatusOK">
        update cloud_teacher_order set status_ = 2,
       `start_time_` = CURRENT_DATE(),
       `end_time_` = case
         when type_ = 1 then concat(date_add(CURRENT_DATE(), interval `time_` day) , ' 00:00:00')
         when type_ = 2 then concat(date_add(CURRENT_DATE(), interval `time_` month) , ' 00:00:00')
         when type_ = 3 then concat(date_add(CURRENT_DATE(), interval `time_` * 3 month) , ' 00:00:00')
         when type_ = 4 then concat(date_add(CURRENT_DATE(), interval `time_` * 6 month) , ' 00:00:00')
         when type_ = 5 then concat(date_add(CURRENT_DATE(), interval `time_` year) , ' 00:00:00')
        end
        where platform_order_id_ = #{platformOrderId}
    </update>
    <update id="updateOrderId">
        update cloud_teacher_order
        set platform_order_id_ = #{platformOrderId} , pay_amount_ = #{amount}
        where id_ = #{cloudTeacherOrderId}
    </update>

    <!-- 全查询 -->
    <select id="findAll" resultMap="CloudTeacherOrder">
        SELECT *
        FROM cloud_teacher_order where tenant_id_ = #{tenantId}
    </select>

    <!-- 分页查询 -->
    <select id="queryPage" resultMap="CloudTeacherOrderDto" parameterType="map">
        SELECT cto.*,spo.status_ trans_status_,spo.expect_amount_,spo.pay_time_,spo.create_time_ order_create_time_,mrs.name_,mrs.icon_ FROM cloud_teacher_order cto
        left join student_payment_order spo on cto.order_id_ = spo.id_
        left join member_rank_setting mrs on mrs.id_ = cto.level_
        where spo.type_ = 'MEMBER'
        <if test="status != null">
        	and cto.status_ = #{status}
        </if>
        <if test="studentId != null">
        	and cto.student_id_ = #{studentId}
        </if>
        <if test="tenantId != null">
        	and cto.tenant_id_ = #{tenantId}
        </if>
        order by spo.pay_time_ desc,spo.id_ desc
        <include refid="global.limit"/>
    </select>

    <!-- 查询当前表的总记录数 -->
    <select id="queryCount" resultType="int">
        SELECT COUNT(cto.id_)
        FROM cloud_teacher_order cto LEFT JOIN student_payment_order spo on cto.order_id_ = spo.id_
        where spo.type_ = 'MEMBER'
        <if test="status != null">
        	and cto.status_ = #{status}
        </if>
        <if test="studentId != null">
        	and cto.student_id_ = #{studentId}
        </if>
        <if test="tenantId != null">
        	and cto.tenant_id_ = #{tenantId}
        </if>
        order by cto.create_time_ desc
    </select>

    <select id="getNoStartCloudTeacherOrder" resultMap="CloudTeacherOrder">
        SELECT cto.*
        FROM cloud_teacher_order cto
        WHERE cto.status_ = 1 and cto.tenant_id_ = #{tenantId}
    </select>

    <select id="getStudentCloudTeacherOrders" resultMap="CloudTeacherOrder">
        SELECT *
        FROM cloud_teacher_order
        WHERE order_id_ IN (
        SELECT id_
        FROM student_payment_order
        WHERE status_ = 'SUCCESS'
        AND user_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
        GROUP BY user_id_
        )
        AND student_id_ IN
        <foreach collection="studentIds" item="studentId" open="(" close=")" separator=",">
            #{studentId}
        </foreach>
        AND status_ IN (1,2)
    </select>

    <select id="getStudentCloudTeacherOrder" resultMap="CloudTeacherOrder">
        SELECT *
        FROM cloud_teacher_order
        WHERE student_id_ = #{studentId}
        <if test="musicGroupId != null and musicGroupId != ''">
          AND music_group_id_ = #{musicGroupId}
        </if>
          AND status_ IN (1, 2)
    </select>

    <select id="queryByOrderId" resultMap="CloudTeacherOrder">
        SELECT cto.* FROM cloud_teacher_order cto
        WHERE order_id_ = #{orderId}
    </select>
    
    <select id="queryOrderInfoByOrderId" resultMap="CloudTeacherOrderDto">
	SELECT cto.*,spo.status_ trans_status_,spo.expect_amount_,mrs.name_,mrs.icon_ FROM cloud_teacher_order cto
        left join student_payment_order spo on cto.order_id_ = spo.id_
        left join member_rank_setting mrs on mrs.id_ = cto.level_
        where spo.type_ = 'MEMBER' and order_id_ = #{orderId}
    </select>
    <select id="queryNoStartByUserIds" resultType="java.util.Map">
        SELECT student_id_ 'key',create_time_ 'value' FROM cloud_teacher_order
        WHERE status_ = 1
        <if test="userIds != null and userIds.size > 0">
            AND student_id_ IN
            <foreach collection="userIds" separator="," item="userId" open="(" close=")">
                #{userId}
            </foreach>
        </if>
        GROUP BY student_id_
    </select>
    <resultMap id="CloudTeacherActiveTargetDetailDto" type="com.ym.mec.biz.dal.dto.CloudTeacherActiveTargetDetailDto">
        <result property="userId" column="student_id_"/>
        <result property="username" column="username_"/>
        <result property="amount" column="amount_"/>
        <result property="remark" column="remark_"/>
        <result property="cooperationName" column="cooperation_name_"/>
        <result property="musicGroupName" column="music_group_name_"/>
        <result property="chargeType" column="charge_type_name_"/>
        <result property="subjectName" column="subject_name_"/>
        <result property="currentGradeNum" column="current_grade_num_"/>
        <result property="teacherName" column="teacher_name_"/>
        <result property="createTime" column="create_time_"/>
    </resultMap>
    <select id="queryCloudTeacherActiveDetail" resultMap="CloudTeacherActiveTargetDetailDto">
        SELECT su.username_,cto.remark_,cto.amount_,cto.student_id_,GROUP_CONCAT(DISTINCT co.name_) cooperation_name_,
        GROUP_CONCAT(DISTINCT mg.name_) music_group_name_,GROUP_CONCAT(DISTINCT ct.name_) charge_type_name_,
        sj.name_ subject_name_,st.current_grade_num_,sus.real_name_ teacher_name_,cto.create_time_
        FROM cloud_teacher_order cto
        LEFT JOIN sys_user su ON su.id_ = cto.student_id_
        LEFT JOIN student_registration sr ON sr.user_id_ = cto.student_id_ AND sr.music_group_status_ = 'NORMAL'
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_ AND mg.status_ = 'PROGRESS'
        LEFT JOIN cooperation_organ co ON co.id_ = mg.cooperation_organ_id_
        LEFT JOIN charge_type ct ON ct.id_ = mg.charge_type_id_
        LEFT JOIN student st ON st.user_id_ = cto.student_id_
        LEFT JOIN sys_user sus ON sus.id_ = st.teacher_id_
        LEFT JOIN `subject` sj ON sj.id_ = st.subject_id_list_
        <include refid="queryCloudTeacherActiveDetailSql"/>
        GROUP BY cto.id_
        ORDER BY cto.id_ DESC
        <include refid="global.limit"/>
    </select>
    <select id="countCloudTeacherActiveDetail" resultType="int">
        SELECT COUNT(DISTINCT cto.id_)
        FROM cloud_teacher_order cto
        LEFT JOIN sys_user su ON su.id_ = cto.student_id_
        LEFT JOIN student st ON st.user_id_ = cto.student_id_
        LEFT JOIN student_registration sr ON sr.user_id_ = cto.student_id_ AND sr.music_group_status_ = 'NORMAL'
        LEFT JOIN music_group mg ON mg.id_ = sr.music_group_id_ AND mg.status_ = 'PROGRESS'
        <include refid="queryCloudTeacherActiveDetailSql"/>
    </select>
    <select id="queryActiveOrderPage" resultType="string">
        SELECT GROUP_CONCAT(DISTINCT cto.remark_) FROM cloud_teacher_order cto
        LEFT JOIN student_payment_order spo ON spo.id_ = cto.order_id_
        WHERE spo.status_ = 'SUCCESS' AND cto.active_remark_ = #{activeRemark}
        AND cto.student_id_ = #{userId} AND cto.remark_ != '单月'
        <if test="remark != null and remark != ''">
            AND cto.remark_ = #{remark}
        </if>
    </select>
    <select id="getStudentIds" resultType="java.lang.Integer">
        SELECT DISTINCT student_id_ FROM cloud_teacher_order WHERE active_remark_ IS NULL AND status_ != 0 and tenant_id_ = #{tenantId}
    </select>
    <select id="queryActiveAmountMap" resultType="java.util.Map">
        SELECT student_id_ 'key',SUM(amount_) 'value' FROM cloud_teacher_order
        WHERE status_ != 0 AND active_remark_ = '202109'
        <if test="studentIds != null and studentIds.size > 0">
            AND student_id_ IN
            <foreach collection="studentIds" separator="," item="userId" open="(" close=")">
                #{userId}
            </foreach>
        </if>
        GROUP BY student_id_
    </select>

    <resultMap id="cloudTeacherStudent" type="com.ym.mec.biz.dal.entity.CloudTeacherStudent">
        <result property="type" column="type" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler" />
    </resultMap>

    <!-- 查询激活或未激活记录 -->
    <select id="queryInactive" resultMap="cloudTeacherStudent">
        select
               cto.id_ as cloudTeacherOrderId,
               cto.student_id_ as studentId,
               cto.type_ as type,
               case cto.type_
					WHEN 'DAY' THEN '天'
                    WHEN 'MONTH' THEN '月'
                    WHEN 'QUARTERLY' THEN '季'
                    WHEN 'YEAR_HALF' THEN '半年'
                    WHEN 'YEAR' THEN '年' ELSE ''
               end as typeName,
               cto.time_ as time,
               sj.id_ as subject,
               sj.name_ as subjectName,
               cto.tenant_id_ as tenantId,
               u.username_ as name,
               u.phone_ as phone
        from cloud_teacher_order cto
        left join student s on cto.student_id_ = s.user_id_
        left join sys_user u on cto.student_id_ = u.id_
        left join subject sj on s.subject_id_list_ = sj.id_
        <if test="musicGroupId != null and musicGroupId != ''">
            left join student_registration sr ON cto.student_id_ = sr.user_id_
        </if>
        <where>
            cto.status_ = #{status} AND cto.tenant_id_ = #{tenantId}
            <if test="organIds != null and organIds != ''">
                AND FIND_IN_SET(u.organ_id_ , #{organIds})
            </if>
            <if test="musicGroupId != null and musicGroupId != ''">
            	AND sr.music_group_id_ = #{musicGroupId}
            </if>
            <if test="queryCondition != null and queryCondition != ''">
                AND (u.username_ LIKE CONCAT('%', #{queryCondition}, '%') or u.phone_ = #{queryCondition} or u.id_ = #{queryCondition})
            </if>
            <if test="subjectId">
                AND (s.subject_id_list_ = #{subjectId})
            </if>
        </where>
        ORDER BY cto.id_ DESC
        <include refid="global.limit"/>
    </select>

    <select id="findInactiveCount" resultType="java.lang.Integer">
        select count(1) from cloud_teacher_order cto
        left join student s on cto.student_id_ = s.user_id_
        left join sys_user u on cto.student_id_ = u.id_
        left join subject sj on s.subject_id_list_ = sj.id_
        <if test="musicGroupId != null and musicGroupId != ''">
            left join student_registration sr ON cto.student_id_ = sr.user_id_
        </if>
        <where>
            cto.status_ = #{status} AND cto.tenant_id_ = #{tenantId}
            <if test="organIds != null and organIds != ''">
                AND FIND_IN_SET(u.organ_id_ , #{organIds})
            </if>
            <if test="musicGroupId != null and musicGroupId != ''">
            	AND sr.music_group_id_ = #{musicGroupId}
            </if>
            <if test="queryCondition != null and queryCondition != ''">
                AND (u.username_ LIKE CONCAT('%', #{queryCondition}, '%') or u.phone_ = #{queryCondition} or u.id_ = #{queryCondition})
            </if>
            <if test="subjectId">
                AND (s.subject_id_list_ = #{subjectId})
            </if>
        </where>
    </select>

    <!-- 查询订单记录 -->
    <select id="findRecordCount" resultType="java.lang.Integer">
        SELECT count(1) FROM tenant_order_record tor
        LEFT JOIN cloud_teacher_order cto ON tor.id_ = cto.platform_order_id_
        LEFT JOIN student s ON cto.student_id_ = s.user_id_
        LEFT JOIN sys_user u ON cto.student_id_ = u.id_
        <where>
            cto.tenant_id_ = #{tenantId} AND tor.order_type_ = 'CLOUD_TEACHER' AND tor.order_state_ = 1
            <if test="queryCondition != null and queryCondition != ''">
                AND (u.username_ LIKE CONCAT('%', #{queryCondition}, '%') or u.phone_ = #{queryCondition} or u.id_ = #{queryCondition})
            </if>
            <if test="orderNo != null and orderNo != ''">
                AND tor.order_no_ LIKE CONCAT('%', #{orderNo}, '%')
            </if>
            <if test="startTime != null">
                <![CDATA[ AND tor.created_time_ >= #{startTime} ]]>
            </if>
            <if test="endTime != null">
                <![CDATA[ AND tor.created_time_ <= #{endTime} ]]>
            </if>
        </where>
    </select>
    <select id="queryRecord"  resultMap="cloudTeacherStudent">
        SELECT
            cto.id_ AS cloudTeacherOrderId,
            cto.student_id_ AS studentId,
            cto.type_ AS type,
            CASE cto.type_ WHEN 'DAY' THEN '天'
                WHEN 'MONTH' THEN '月'
                WHEN 'QUARTERLY' THEN '季'
                WHEN 'YEAR_HALF' THEN '半年'
                WHEN 'YEAR' THEN '年' ELSE ''
                END AS typeName,
            cto.time_ AS time,
            u.tenant_id_ AS tenantId,
            u.username_ AS name,
            u.phone_ AS phone,
            tor.order_no_ as orderNo,
            tor.trans_no_ as transNo,
            tor.created_time_ as orderTime,
            cto.pay_amount_ as amount
        FROM tenant_order_record tor
        LEFT JOIN cloud_teacher_order cto ON tor.id_ = cto.platform_order_id_
        LEFT JOIN student s ON cto.student_id_ = s.user_id_
        LEFT JOIN sys_user u ON cto.student_id_ = u.id_
        <where>
            cto.tenant_id_ = #{tenantId} AND tor.order_type_ = 'CLOUD_TEACHER' AND tor.order_state_ = 1
            <if test="queryCondition != null and queryCondition != ''">
                AND (u.username_ LIKE CONCAT('%', #{queryCondition}, '%') or u.phone_ = #{queryCondition} or u.id_ = #{queryCondition})
            </if>
            <if test="orderNo != null and orderNo != ''">
                AND tor.order_no_ LIKE CONCAT('%', #{orderNo}, '%')
            </if>
            <if test="startTime != null">
                <![CDATA[ AND tor.created_time_ >= #{startTime} ]]>
            </if>
            <if test="endTime != null">
                <![CDATA[ AND tor.created_time_ <= #{endTime} ]]>
            </if>
        </where>
        <include refid="global.limit"/>
    </select>
    <select id="checkOrdered" resultType="java.lang.Integer">
        select count(1) from cloud_teacher_order where id_ in (${cloudTeacherStudentIds}) and status_ = 2 and platform_order_id_ is not null
    </select>

    <sql id="queryCloudTeacherActiveDetailSql">
        <where>
            cto.status_ != 0 AND cto.active_remark_ = '202109'
            <if test="organIds != null and organIds != ''">
                AND FIND_IN_SET(su.organ_id_,#{organIds})
            </if>
            <if test="search != null and search != ''">
                AND (su.id_ = #{search} OR su.username_ LIKE CONCAT('%',#{search},'%') OR mg.id_ LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="chargeType != null">
                AND mg.charge_type_id_ = #{chargeType}
            </if>
            <if test="subjectId != null">
                AND st.subject_id_list_ = #{subjectId}
            </if>
            <if test="teacherId != null">
                AND st.teacher_id_ = #{teacherId}
            </if>
            <if test="tenantId != null">
                AND cto.tenant_id_ = #{tenantId}
            </if>
            <if test="remarkType != null and remarkType != ''">
                AND cto.remark_ = #{remarkType}
            </if>
        </where>
    </sql>

    <insert id="batchInsert">
        INSERT INTO cloud_teacher_order (organ_id_,student_id_, type_, level_, time_, amount_,status_,
        remark_,create_time_, update_time_,tenant_id_)
        VALUES
        <foreach collection="userIds" item="userId" separator=",">
            (#{bean.organId},#{userId},#{bean.type,typeHandler=com.ym.mec.common.dal.CustomEnumTypeHandler},#{bean.level},
            #{bean.time}, #{bean.amount},#{bean.status},#{bean.remark},NOW(),NOW(),#{bean.tenantId})
        </foreach>
    </insert>
    
    <select id="queryByUserIdAndStatus" resultMap="CloudTeacherOrder">
        select cto.* from cloud_teacher_order cto where cto.student_id_ = #{userId} and cto.status_ = #{status}
    </select>
</mapper>