<?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.fs.qw.mapper.QwExternalContactMapper">

    <resultMap type="QwExternalContact" id="QwExternalContactResult">
        <result property="id"    column="id"    />
        <result property="userId"    column="user_id"    />
        <result property="corpId"    column="corp_id"    />
        <result property="externalUserId"    column="external_user_id"    />
        <result property="name"    column="name"    />
        <result property="avatar"    column="avatar"    />
        <result property="type"    column="type"    />
        <result property="gender"    column="gender"    />
        <result property="remark"    column="remark"    />
        <result property="description"    column="description"    />
        <result property="tagIds"    column="tag_ids"    />
        <result property="remarkMobiles"    column="remark_mobiles"    />
        <result property="remarkCorpName"    column="remark_corp_name"    />
        <result property="addWay"    column="add_way"    />
        <result property="operUserid"    column="oper_userid"    />
        <result property="companyId"    column="company_id"    />
        <result property="companyUserId"    column="company_user_id"    />
        <result property="customerId"    column="customer_id"    />
        <result property="transferStatus"    column="transfer_status"    />
        <result property="status"    column="status"    />
        <result property="createTime"    column="create_time"    />
        <result property="transferTime"    column="transfer_time"    />
        <result property="transferNum"    column="transfer_num"    />
        <result property="lossTime"    column="loss_time"    />
        <result property="delTime"    column="del_time"    />
        <result property="qwUserId"    column="qw_user_id"    />
        <result property="state"    column="state"    />
        <result property="wayId"    column="way_id"    />
        <result property="stageStatus"    column="stage_status"    />
        <result property="fsUserId"    column="fs_user_id"    />
        <result property="openId"    column="open_id"    />
        <result property="unionid"    column="unionid"    />
        <result property="isInteract"    column="is_interact"    />
        <result property="level"    column="level"    />
    </resultMap>

    <sql id="selectQwExternalContactVo">
        select id,qw_user_id,state,way_id,stage_status,open_id,is_interact,level, unionid, user_id,transfer_time,loss_time,del_time,transfer_num, external_user_id,transfer_status,status,create_time, name, avatar, type, gender, remark, description, tag_ids, remark_mobiles, remark_corp_name, add_way, oper_userid, corp_id, company_id, company_user_id, customer_id, fs_user_id from qw_external_contact
    </sql>

    <select id="selectQwExternalContactList" parameterType="QwExternalContact" resultMap="QwExternalContactResult">
        <include refid="selectQwExternalContactVo"/>
        <where>
            <if test="userId != null  and userId != ''"> and user_id = #{userId}</if>
            <if test="corpId != null  and corpId != ''"> and corp_id = #{corpId}</if>
            <if test="externalUserId != null  and externalUserId != ''"> and external_user_id = #{externalUserId}</if>
            <if test="name != null  and name != ''"> and name like concat('%', #{name}, '%')</if>
            <if test="avatar != null  and avatar != ''"> and avatar = #{avatar}</if>
            <if test="type != null "> and type = #{type}</if>
            <if test="gender != null "> and gender = #{gender}</if>
            <if test="description != null  and description != ''"> and description = #{description}</if>
            <if test="tagIds != null  and tagIds != ''"> and tag_ids = #{tagIds}</if>
            <if test="remarkMobiles != null  and remarkMobiles != ''"> and remark_mobiles = #{remarkMobiles}</if>
            <if test="remarkCorpName != null  and remarkCorpName != ''"> and remark_corp_name like concat('%', #{remarkCorpName}, '%')</if>
            <if test="addWay != null "> and add_way = #{addWay}</if>
            <if test="operUserid != null  and operUserid != ''"> and oper_userid = #{operUserid}</if>
            <if test="companyId != null "> and company_id = #{companyId}</if>
            <if test="companyUserId != null "> and company_user_id = #{companyUserId}</if>
            <if test="customerId != null "> and customer_id = #{customerId}</if>
            <if test="fsUserId != null "> and fs_user_id = #{fsUserId}</if>
            <if test="unionid != null "> and unionid = #{unionid}</if>
        </where>
    </select>

    <select id="selectAllQwJoinAdClickLog" resultType="com.fs.qw.result.QwExternalContactVo">
        select a.*,MAX(b.url) url,MAX(b.vid) vid,MAX(b.aid) aid from qw_external_contact a
        inner join ad_html_click_log b on a.state = b.vid
        where a.state is not null and b.type = #{type}
        <if test="type == 0">
            and b.click_type = 67 and (upload_add_wx_status = 0 or upload_register_status = 0 or upload_finished_status = 0)
        </if>
        <if test="type == 1">
            and b.click_type = 'wechat' and upload_add_wx_status = 0
        </if>
        group by a.id
    </select>

    <select id="selectQwExternalContactListVOByIds" resultType="com.fs.qw.param.QwExternalContactVOTime">
            select id,tag_ids,remark,create_time from qw_external_contact
          where id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                #{id}
                </foreach>
    </select>

    <select id="selectQwExternalContactListVOByUserIds" resultType="com.fs.qw.param.QwExternalContactVOTime">
            select id,tag_ids,remark,create_time,external_user_id from qw_external_contact
          where external_user_id in
                <foreach collection="ids" item="id" open="(" separator="," close=")">
                #{id}
                </foreach>
            group by external_user_id
    </select>

    <select id="selectAllFormAd" resultType="com.fs.qw.result.QwExternalContactLogVo">
        select a.*
        ,user.nick_name
        ,b.aid,b.pid,b.uid,b.userid accountId,b.comb_id,b.create_time as `time`
        ,creative.creative_feed_name
        ,plan.campaign_feed_name
        ,unit.adgroup_feed_name
        ,account.account_name
        ,info.sex,info.age,info.address
        from qw_external_contact a
        left join qw_external_contact_info info on a.id = info.external_contact_id
        inner join ad_html_click_log b on a.state = b.vid
        left join bd_creative creative on b.aid = creative.creative_feed_id
        left join bd_plan plan on b.pid = plan.campaign_feed_id
        left join bd_unit unit on b.uid = unit.adgroup_feed_id
        <if test="accountId == null and userId == null">left join </if>
        <if test="accountId != null || userId != null">inner join </if>
        bd_account account on b.userid = account.account_id
        left join company_user user on account.user_id = user.user_id
        where a.state is not null and b.click_type = 67
        AND date_format(b.create_time,'%Y-%m-%d %h:%i:%s') &gt;= #{start}
        and date_format(b.create_time,'%Y-%m-%d %h:%i:%s') &lt;= #{end}
        <if test="accountId != null">
            and account.account_id = #{accountId}
        </if>
        <if test="userId != null">
            and account.user_id = #{userId}
        </if>
        <if test="aid != null">
            and b.aid = #{aid}
        </if>
        <if test="pid != null">
            and b.pid = #{pid}
        </if>
        <if test="uid != null">
            and b.uid = #{uid}
        </if>
        group by a.id
    </select>

    <select id="selectQwExternalContactById" parameterType="Long" resultMap="QwExternalContactResult">
        <include refid="selectQwExternalContactVo"/>
        where id = #{id}
    </select>

    <update id="batchUpdateQwExternalContactStatus" parameterType="map">
        UPDATE qw_external_contact
        SET status = 4
        WHERE user_id = #{qwUserId}
        AND corp_id = #{corpId}
        AND external_user_id IN
        <foreach collection="notInExternalUseridList" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </update>


    <insert id="insertQwExternalContact" parameterType="QwExternalContact" useGeneratedKeys="true" keyProperty="id" >
        insert into qw_external_contact
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">id,</if>
            <if test="userId != null">user_id,</if>
            <if test="externalUserId != null">external_user_id,</if>
            <if test="name != null">name,</if>
            <if test="avatar != null">avatar,</if>
            <if test="type != null">type,</if>
            <if test="gender != null">gender,</if>
            <if test="remark != null">remark,</if>
            <if test="description != null">description,</if>
            <if test="tagIds != null">tag_ids,</if>
            <if test="remarkMobiles != null">remark_mobiles,</if>
            <if test="remarkCorpName != null">remark_corp_name,</if>
            <if test="addWay != null">add_way,</if>
            <if test="operUserid != null">oper_userid,</if>
            <if test="corpId != null">corp_id,</if>
            <if test="companyId != null">company_id,</if>
            <if test="companyUserId != null">company_user_id,</if>
            <if test="customerId != null">customer_id,</if>
            <if test="transferStatus != null">transfer_status,</if>
            <if test="status != null">status,</if>
            <if test="createTime != null">create_time,</if>
            <if test="transferTime != null">transfer_time,</if>
            <if test="transferNum != null">transfer_num,</if>
            <if test="lossTime != null">loss_time,</if>
            <if test="delTime != null">del_time,</if>
            <if test="qwUserId != null">qw_user_id,</if>
            <if test="state != null">`state`,</if>
            <if test="wayId != null">way_id,</if>
            <if test="stageStatus != null">stage_status,</if>
            <if test="fsUserId != null">fs_user_id,</if>
            <if test="openId != null">open_id,</if>
            <if test="unionid != null">unionid,</if>
            <if test="isInteract != null">is_interact,</if>
            <if test="level != null">level,</if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">#{id},</if>
            <if test="userId != null">#{userId},</if>
            <if test="externalUserId != null">#{externalUserId},</if>
            <if test="name != null">#{name},</if>
            <if test="avatar != null">#{avatar},</if>
            <if test="type != null">#{type},</if>
            <if test="gender != null">#{gender},</if>
            <if test="remark != null">#{remark},</if>
            <if test="description != null">#{description},</if>
            <if test="tagIds != null">#{tagIds},</if>
            <if test="remarkMobiles != null">#{remarkMobiles},</if>
            <if test="remarkCorpName != null">#{remarkCorpName},</if>
            <if test="addWay != null">#{addWay},</if>
            <if test="operUserid != null">#{operUserid},</if>
            <if test="corpId != null">#{corpId},</if>
            <if test="companyId != null">#{companyId},</if>
            <if test="companyUserId != null">#{companyUserId},</if>
            <if test="customerId != null">#{customerId},</if>
            <if test="transferStatus != null">#{transferStatus},</if>
            <if test="status != null">#{status},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="transferTime != null">#{transferTime},</if>
            <if test="transferNum != null">#{transferNum},</if>
            <if test="lossTime != null">#{lossTime},</if>
            <if test="delTime != null">#{delTime},</if>
            <if test="qwUserId != null">#{qwUserId},</if>
            <if test="state != null">#{state},</if>
            <if test="wayId != null">#{wayId},</if>
            <if test="stageStatus != null">#{stageStatus},</if>
            <if test="fsUserId != null">#{fsUserId},</if>
            <if test="openId != null">#{openId},</if>
            <if test="unionid != null">#{unionid},</if>
            <if test="isInteract != null">#{isInteract},</if>
            <if test="level != null">#{level},</if>
         </trim>
    </insert>

    <update id="updateQwExternalContact" parameterType="QwExternalContact">
        update qw_external_contact
        <trim prefix="SET" suffixOverrides=",">
            <if test="userId != null">user_id = #{userId},</if>
            <if test="corpId != null">corp_id = #{corpId},</if>
            <if test="externalUserId != null">external_user_id = #{externalUserId},</if>
            <if test="name != null">name = #{name},</if>
            <if test="avatar != null">avatar = #{avatar},</if>
            <if test="type != null">type = #{type},</if>
            <if test="gender != null">gender = #{gender},</if>
            <if test="remark != null">remark = #{remark},</if>
            <if test="description != null">description = #{description},</if>
            <if test="tagIds != null">tag_ids = #{tagIds},</if>
            <if test="remarkMobiles != null">remark_mobiles = #{remarkMobiles},</if>
            <if test="remarkCorpName != null">remark_corp_name = #{remarkCorpName},</if>
            <if test="addWay != null">add_way = #{addWay},</if>
            <if test="operUserid != null">oper_userid = #{operUserid},</if>
            <if test="companyId != null">company_id = #{companyId},</if>
            <if test="companyUserId != null">company_user_id = #{companyUserId},</if>
            <if test="customerId != null">customer_id = #{customerId},</if>
            <if test="transferStatus != null">transfer_status = #{transferStatus},</if>
            <if test="status != null">status = #{status},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="transferTime != null">transfer_time = #{transferTime},</if>
            <if test="transferNum != null">transfer_num = #{transferNum},</if>
            <if test="lossTime != null">loss_time = #{lossTime},</if>
            <if test="delTime != null">del_time = #{delTime},</if>
            <if test="qwUserId != null">qw_user_id = #{qwUserId},</if>
            <if test="state != null">`state` = #{state},</if>
            <if test="wayId != null">way_id = #{wayId},</if>
            <if test="stageStatus != null">stage_status = #{stageStatus},</if>
            <if test="fsUserId != null">fs_user_id = #{fsUserId},</if>
            <if test="openId != null">open_id = #{openId},</if>
            <if test="unionid != null">unionid = #{unionid},</if>
            <if test="isInteract != null">is_interact = #{isInteract},</if>
            <if test="level != null">level = #{level},</if>
        </trim>
        where id = #{id}
    </update>

    <delete id="deleteQwExternalContactById" parameterType="Long">
        delete from qw_external_contact where id = #{id}
    </delete>

    <delete id="deleteQwExternalContactByIds" parameterType="String">
        delete from qw_external_contact where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>

    <select id="selectExternalContactPageList" resultType="ExternalContactListVO">
        SELECT
        DISTINCT qw_external_contact.id,
        qw_external_contact.qw_user_id,
        qw_external_contact.user_id,
        qw_external_contact.external_user_id,
        qw_external_contact.remark_mobiles AS mobile,
        qw_external_contact.STATUS,
        qw_external_contact.create_time,
        qw_external_contact.NAME AS nickName,
        qw_external_contact.avatar,
        qw_external_contact.gender AS sex,
        qw_external_contact.tag_ids,
        qw_external_contact.corp_id,
        company_user.user_id AS companyUserId,
        company_user.user_name AS companyUserName,
        company_user.nick_name AS companyUserNickName
        FROM
        qw_external_contact
        LEFT JOIN qw_user ON qw_external_contact.user_id = qw_user.qw_user_id
        LEFT JOIN company_user ON qw_user.company_user_id = company_user.user_id
        LEFT JOIN qw_tag on qw_tag.corp_id = qw_external_contact.corp_id
        WHERE  company_user.user_id = #{userId}
        <choose>
            <when test = "isBlack">
                AND qw_external_contact.status = 7
            </when>
            <otherwise>
                AND qw_external_contact.status != 7
            </otherwise>
        </choose>
        <if test="keyword != null and keyword !='' ">
            AND (qw_external_contact.NAME LIKE concat('%',#{keyword},'%')
                or  qw_external_contact.remark_mobiles LIKE concat('%',#{keyword},'%')
                or  qw_tag.`name` LIKE concat('%',#{keyword},'%')
                )
        </if>
        <if test="registerStartTime != null and registerStartTime !='' ">
        AND qw_external_contact.create_time &gt;= #{registerStartTime}
        </if>
        <if test="registerEndTime != null and registerEndTime !='' ">
        AND qw_external_contact.create_time &lt;= #{registerEndTime}
        </if>
        <if test="tagIds != null and tagIds.length > 0">
            AND
            <foreach collection="tagIds" item="item" index="index" open="(" separator="or" close=")">
                tag_ids LIKE concat('%"',#{item},'"%')
            </foreach>
        </if>
        <if test="tabValue != null and tabValue !='' ">
            <choose>
                <when test = "tabValue == 1">
                    AND DAY(qw_external_contact.create_time) = DAY(NOW())
                </when>
                <when test = "tabValue == 2">
--                     暂时不做
                    AND 1!=1
                </when>
                <when test = "tabValue == 3">
                    --                     暂时不做
                    AND 1!=1
                </when>
            </choose>
        </if>
        <if test="watchCourseType != null and watchCourseType !='' ">
            <choose>
                <when test = "watchCourseType == 1">
                    AND 1!=1
                </when>
                <when test = "watchCourseType == 2">
                    AND 1!=1
                </when>
                <when test = "watchCourseType == 3">
                    AND 1!=1
                </when>
            </choose>
        </if>
    </select>

    <select id="getContactNumber" resultType="ExternalContactNumVO">
        SELECT
            qw_external_contact.STATUS as status,
            count( qw_external_contact.id ) as num
        FROM
            qw_external_contact
                LEFT JOIN qw_user ON qw_external_contact.user_id = qw_user.qw_user_id
                LEFT JOIN company_user ON qw_user.company_user_id = company_user.user_id
        WHERE
            company_user.user_id = #{userId}
        GROUP BY
            qw_external_contact.STATUS
    </select>

    <select id="getCountAnswer" resultType="ExternalContactDetailsVO">
        SELECT
            count( DISTINCT log_id ) AS answerTime,
            is_right,
            qw_external_contact.id,
            qw_external_contact.external_user_id,
            qw_external_contact.qw_user_id
        FROM
            fs_course_answer_logs
                LEFT JOIN qw_user ON qw_user.id = fs_course_answer_logs.qw_user_id
                LEFT JOIN qw_external_contact ON qw_external_contact.user_id = qw_user.qw_user_id
        WHERE
            fs_course_answer_logs.company_user_id = #{userId}
        <if test="dateTag != null and dateTag !='' ">
            <choose>
                <when test = "dateTag == '今天'">
                    and to_days(fs_course_answer_logs.create_time) = to_days(now())
                </when>
                <when test = "dateTag == ' 昨天'">
                    and to_days(now()) - to_days(fs_course_answer_logs.create_time) &lt;= 1
                </when>
                <when test = "dateTag == '前天'">
                    and to_days(now()) - to_days(fs_course_answer_logs.create_time) &lt;= 2
                </when>
                <when test = "dateTag == '近七天'">
                    and DATE_SUB(CURDATE(), INTERVAL 7 DAY) &lt;= date(fs_course_answer_logs.create_time)
                </when>
            </choose>
        </if>
        GROUP BY
            qw_external_contact.id
        HAVING
            qw_external_contact.id = #{contactId}

        union all

        SELECT
            count( DISTINCT log_id ) AS answerRightTime,
            is_right,
            qw_external_contact.id,
            qw_external_contact.external_user_id,
            qw_external_contact.qw_user_id
        FROM
            fs_course_answer_logs
                LEFT JOIN qw_user ON qw_user.id = fs_course_answer_logs.qw_user_id
                LEFT JOIN qw_external_contact ON qw_external_contact.user_id = qw_user.qw_user_id
        WHERE
            fs_course_answer_logs.company_user_id = #{userId} and fs_course_answer_logs.is_right = 1
            <if test="dateTag != null and dateTag !='' ">
                <choose>
                    <when test = "dateTag == '今天'">
                        and to_days(fs_course_answer_logs.create_time) = to_days(now())
                    </when>
                    <when test = "dateTag == ' 昨天'">
                        and to_days(now()) - to_days(fs_course_answer_logs.create_time) &lt;= 1
                    </when>
                    <when test = "dateTag == '前天'">
                        and to_days(now()) - to_days(fs_course_answer_logs.create_time) &lt;= 2
                    </when>
                    <when test = "dateTag == '近七天'">
                        and DATE_SUB(CURDATE(), INTERVAL 7 DAY) &lt;= date(fs_course_answer_logs.create_time)
                    </when>
                </choose>
            </if>
        GROUP BY
            qw_external_contact.id
        HAVING
            qw_external_contact.id = #{contactId}
    </select>

    <select id="getCountRedPacket" resultType="ExternalContactDetailsVO">
        SELECT
            count( DISTINCT log_id ) AS answerRedPacketTime,
            sum( amount ) AS answerRedPacketAmount,
            amount,
            qw_external_contact.id,
            qw_external_contact.external_user_id,
            qw_external_contact.qw_user_id
        FROM
            fs_course_red_packet_log
                LEFT JOIN qw_user ON qw_user.id = fs_course_red_packet_log.qw_user_id
                LEFT JOIN qw_external_contact ON qw_external_contact.user_id = qw_user.qw_user_id
        WHERE
            fs_course_red_packet_log.company_user_id = #{userId}
            <if test="dateTag != null and dateTag !='' ">
            <choose>
                <when test = "dateTag == '今天'">
                    and to_days(fs_course_red_packet_log.create_time) = to_days(now())
                </when>
                <when test = "dateTag == ' 昨天'">
                    and to_days(now()) - to_days(fs_course_red_packet_log.create_time) &lt;= 1
                </when>
                <when test = "dateTag == '前天'">
                    and to_days(now()) - to_days(fs_course_red_packet_log.create_time) &lt;= 2
                </when>
                <when test = "dateTag == '近七天'">
                    and DATE_SUB(CURDATE(), INTERVAL 7 DAY) &lt;= date(fs_course_red_packet_log.create_time)
                </when>
            </choose>
            </if>
        GROUP BY
            qw_external_contact.id
        HAVING
            qw_external_contact.id = #{contactId}
    </select>


    <select id="selectContactByIds" resultType="QwExternalContact">
    SELECT
    qw_external_contact.id,
    qw_external_contact.STATUS
    from qw_external_contact
    where id in
          <foreach collection="ids" item="id" index="index" open="(" separator="," close=")">
             (#{id})
          </foreach>
    </select>
    <select id="selectByGroupUser" resultType="com.fs.qw.vo.GroupUserExternalVo">
        select id,user_id,external_user_id from qw_external_contact where external_user_id in
            <foreach collection="ids" open="(" separator="," close=")" item="item">#{item}</foreach>
        GROUP BY user_id,external_user_id
    </select>

    <select id="getBuyStatusByExtId" resultType="java.lang.Boolean">
        select IF(u.pay_order = 1, true, false)
        from qw_external_contact ec
        left join fs_user u on ec.fs_user_id = u.user_id
        where ec.id = #{qwExternalContactId}
    </select>

    <update id="updateContactByIds" parameterType="map">
        update qw_external_contact
        set status = #{status}
        where id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </update>

    <update id="batchUpdateContactByIds" parameterType="map">
        update qw_external_contact
        <trim prefix="set" suffixOverrides=",">
                     <trim prefix="status = case" suffix="end">
                         <foreach collection="list" item="item" index="index">
                             <if test="item.status != null">
                                 when id= #{item.id}
                                  then #{item.status}
                             </if>
                         </foreach>
                     </trim>
        </trim>
        where contact_id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item.id}
        </foreach>
    </update>

</mapper>
