<?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.cyksj.mapper.corp.CorpTagMapper">

    <resultMap type="com.cyksj.model.entity.CorpTag" id="corpTagRulesMap">
        <result column="id" property="id"/>

        <collection property="ruleRelationList" column="tagId=id" ofType="com.cyksj.model.entity.CorpTagRuleRelation" select="getCorpRulesListByTagId"/>

    </resultMap>

    <select id="getCorpTagBackView" resultType="com.cyksj.model.views.CorpTagBackView">
        select * from (select ct.id as tagId,
        ct.tag_id as tagIdStr,
        ct.group_id groupIdStr,
        ct.type,
        ct.group_name,
        ct.name as tagName,
        ct.update_time,
        ct.rule_name_list_str
        from `corp_tag` ct
        <where>
            <if test="tagName != null">
                ct.name like '%${tagName}%'
            </if>
            <if test="groupIds != null and groupIds.length > 0">
                and ct.group_id in
                <foreach collection="groupIds" item="item" open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
        </where>
        ) s
        order by tagId desc
    </select>

    <select id="selectTagsIdByGroupId" resultType="java.lang.String">
        select tag_id from corp_tag where group_id = #{groupId}
    </select>

    <select id="getCorpTagById" resultMap="corpTagRulesMap">
        select * from `corp_tag` where id = #{corpTagId} limit 1
    </select>

    <select id="getCorpRulesListByTagId" resultType="com.cyksj.model.entity.CorpTagRuleRelation">
        select * from `corp_tag_rule_relation` where tag_id = #{tagId}
    </select>

    <select id="getCorpTagHeadDataView" resultType="com.cyksj.model.views.CorpTagHeadDataView">
        select count(distinct ct.tag_id) as numOfTag,
               count(distinct cg.group_id) as numOfGroup
        from `corp_tag_group` cg
                 left join corp_tag ct on ct.group_id = cg.group_id
    </select>

    <select id="selectCountOfCustomer" resultType="java.lang.Integer">
        select count(distinct ca.corp_user_id)
        from corp_user_tag cut
                 left join corp_user_follow_relation cufr
                           on cufr.id = cut.relation_id
                 left join corp_user_auth ca on ca.external_userid = cufr.corp_user_id
        where cufr.wx_corp_id = #{wxCorpId}
          and cut.tag_id = #{tagId}
    </select>
</mapper>