<?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.lyms.talkonlineweb.mapper.LymsTcardMapper">

    <resultMap id="BaseResultMap" type="com.lyms.talkonlineweb.domain.LymsTcard">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="pid" column="pid" jdbcType="INTEGER"/>
            <result property="fid" column="fid" jdbcType="INTEGER"/>
            <result property="cnt" column="cnt" jdbcType="INTEGER"/>
            <result property="price" column="price" jdbcType="INTEGER"/>
            <result property="startTime" column="start_time" jdbcType="TIMESTAMP"/>
            <result property="endTime" column="end_time" jdbcType="TIMESTAMP"/>
            <result property="orderNo" column="order_no" jdbcType="TIMESTAMP"/>
            <result property="createdby" column="createdby" jdbcType="INTEGER"/>
            <result property="createdtime" column="createdtime" jdbcType="TIMESTAMP"/>
            <result property="updatedby" column="updatedby" jdbcType="INTEGER"/>
            <result property="updatedTime" column="updated_time" jdbcType="TIMESTAMP"/>
    </resultMap>

    <sql id="Base_Column_List">
        id,pid,fid,cnt,price,
        start_time,end_time,order_no,
        createdby,createdtime,updatedby,updated_time
    </sql>

    <select id="queryUnused" parameterType="com.lyms.talkonlineweb.domain.LymsTcard" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"></include>
        from lyms_tcard card
        where 1 = 1
        <if test="pid != null">
            and card.pid = #{pid}
        </if>
        <if test="pcid != null">
            and card.pcid = #{pcid}
        </if>
        <if test="fid != null">
            and card.fid = #{fid}
        </if>
        and not EXISTS ( SELECT r.cid FROM lyms_tkrecord r where r.cid = card.id )
        order by
        card.fid desc,card.createdtime ASC

    </select>

    <select id="queryUnusedCount" parameterType="com.lyms.talkonlineweb.domain.LymsTcard" resultType="java.lang.Integer">

        select
        count(1)
        from lyms_tcard card
        where 1 = 1
        <if test="pid != null">
            and card.pid = #{pid}
        </if>
        <if test="pcid != null">
            and card.pcid = #{pcid}
        </if>
        <if test="fid != null">
            and card.fid = #{fid}
        </if>
        and not EXISTS ( SELECT r.cid FROM lyms_tkrecord r where r.cid = card.id )
        AND EXISTS (
        SELECT
        o.id
        FROM
        lyms_order o
        WHERE
        o.pid = card.pid
        AND o. STATUS = 1
        <![CDATA[ AND o.service_end_time >= #{orderNo}]]>
        )
    </select>
</mapper>
