<?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.storlead.mail.mapper.EmailsMapper">

        <!-- 通用查询映射结果 -->
        <resultMap id="BaseResultMap" type="com.storlead.mail.pojo.entity.EmailsEntity" extends="com.storlead.framework.mybatis.mapper.SysBaseFieldMapper.BaseResultMap">
            <id column="id" property="id" />
            <result column="smtp_pop_id" property="smtpPopId" />
            <result column="msg_uid" property="msgUid" />
            <result column="message_id" property="messageId" />
            <result column="subject" property="subject" />
            <result column="from" property="from" />
            <result column="from_name" property="fromName" />
            <result column="recipient" property="recipient" />
            <result column="recipient_name" property="recipientName" />
            <result column="recipient_cc" property="recipientCc" />
            <result column="recipient_cc_name" property="recipientCcName" />
            <result column="recipient_bcc" property="recipientBcc" />
            <result column="recipient_bcc_name" property="recipientBccName" />
            <result column="folder" property="folder" />
            <result column="source_type" property="sourceType" />
            <result column="custom_folder_id" property="customFolderId" />
            <result column="content" property="content" />
            <result column="is_star" property="isStar" />
            <result column="is_trash" property="isTrash" />
            <result column="sent_date" property="sentDate" />
            <result column="recipient_date" property="recipientDate" />
            <result column="email_size" property="emailSize" />
            <result column="remark" property="remark" />
            <result column="is_read" property="isRead" />
            <result column="reply_msg_id" property="replyMsgId" />
            <result column="status" property="status" />
            <result column="is_receipt" property="isReceipt" />
            <result column="is_track" property="isTrack" />
            <result column="read_remind" property="readRemind" />
            <result column="delay_send_time" property="delaySendTime" />
            <result column="is_only_head" property="isOnlyHead" />
            <result column="liaison_ids" property="liaisonIds" />
            <result column="customer_ids" property="customerIds" />
            <result column="customer_id" property="customerId" />
            <result column="follow_up_id" property="followUpId" />
            <result column="follow_up_time" property="followUpTime" />
            <result column="customer_mail_id" property="customerMailId" />
            <result column="delete_tag" property="deleteTag" />
        </resultMap>

        <!-- 通用查询结果列 -->
        <sql id="Base_Column_List">
            id, smtp_pop_id, msg_uid,source_type,message_id,follow_up_id,follow_up_time,is_receipt,is_only_head,is_track,delete_tag,read_remind,delay_send_time,customer_ids,liaison_ids, is_star,is_trash,subject,`from`, from_name, recipient, recipient_name, recipient_cc, recipient_cc_name, recipient_bcc, recipient_bcc_name, folder,custom_folder_id, content,remark, sent_date, recipient_date, email_size, is_read, reply_msg_id, status, owner_by, create_time, update_time, is_delete, enabled, create_by, update_by, sort
        </sql>

    <select id="updateCleanBindCustomerMail">
--         UPDATE emails e
--         SET e.customer_id = NULL;
    </select>
    <select id="updateBindCustomerMail">
        UPDATE emails e
            LEFT JOIN customer_company c ON e.from = c.email
            SET e.customer_id = c.customer_id
        WHERE c.customer_id IS NOT NULL AND e.customer_id is null and c.is_delete = 0;
    </select>

    <select id="updateBindLiaisonMail">
        UPDATE emails e
            LEFT JOIN liaison l ON e.from = l.email
            SET e.customer_id = l.customer_id, e.liaison_id = l.id
        WHERE l.customer_id IS NOT NULL AND (e.customer_id is null or e.liaison_id is null)  and l.is_delete = 0;
    </select>

    <select id="getMailCustomerIdByMailIdAndUserId" resultType="java.lang.Long">
        SELECT customer_id FROM customer_company WHERE email is not null AND email != '' AND FIND_IN_SET(LOWER(email),#{mailAddress}) and is_delete = 0
    </select>

    <select id="getLiaisonMailCustomerIdByMailIdAndUserId" resultType="com.storlead.mail.pojo.vo.MailLiaisonVO">
       SELECT id as liaisonId,customer_id as customerId FROM liaison WHERE  email is not null AND email != '' AND FIND_IN_SET(LOWER(email),#{mailAddress})  and is_delete = 0
    </select>

    <select id="bindMailCustomerIdByMailId">
        update emails
        set customer_ids= #{customerIds}
        , liaison_ids = #{liaisonIds}
        where id =  #{mailId}
    </select>

    <select id="getEmailsIdByMessageId" resultType="java.lang.Long">
        select id from emails where message_id = #{messageId} and smtp_pop_id = #{smtpPopId} limit 1
    </select>


    <select id="getEmailsByMessageId" resultType="com.storlead.mail.pojo.entity.EmailsEntity">
        select * from emails where message_id = #{messageId} and folder = #{folder} and smtp_pop_id = #{smtpPopId} limit 1
    </select>

    <select id="getEmailMessageIdsByMessageIds" resultType="java.lang.String">
        select message_id from emails
         <where>
             <if test="messageIds != null and messageIds.size > 0">
                 AND message_id IN
                 <foreach collection="messageIds" item="messageId" open="(" separator="," close=")">
                     #{messageId}
                 </foreach>
             </if>
             and folder = #{folder} and smtp_pop_id = #{smtpPopId}
         </where>
    </select>

    <select id="getEmailMessageIdsByMessageId" resultType="java.lang.String">
        select message_id from emails where message_id = #{messageId} and folder = #{folder} and smtp_pop_id = #{smtpPopId}
    </select>

    <select id="pageList"  resultMap="BaseResultMap">
        select e.id, e.smtp_pop_id, e.msg_uid,e.message_id,e.is_receipt,e.is_only_head,e.is_track,e.read_remind,
        e.delay_send_time,e.customer_ids,e.liaison_ids, e.is_star,e.is_trash,e.subject,e.from, e.from_name, e.recipient,
        e.recipient_name, e.recipient_cc, e.recipient_cc_name,e. recipient_bcc, e.recipient_bcc_name, e.folder,e.remark,
        e.sent_date, e.recipient_date, e.email_size, e.is_read, e.reply_msg_id, e.status, e.owner_by, e.create_time, e.update_time,
        e.is_delete, e.enabled, e.create_by, e.update_by, e.sort from  emails as e
        <where>
            <if test="(dto.customerName != null and dto.customerName != '') or dto.customerId != null">
                AND EXISTS (select 1 from customer as c
                <where>
                    <if test="dto.customerName != null and dto.customerName != ''">
                        AND c.customer_name like concat('%',#{dto.customerName},'%')
                    </if>
                    <if test="dto.customerId != null">
                        and c.id = #{dto.customerId}
                    </if>
                    <if test="dto.customerType == null">
                        <if test="dto.bindCustomer != null and dto.bindCustomer == 1">
                            and c.owner_by = #{dto.ownerBy}
                        </if>
                    </if>
                    and FIND_IN_SET(c.id,e.customer_ids) > 0 )
                </where>
            </if>
            <if test="dto.smtpPopId != null">
                and e.smtp_pop_id = #{dto.smtpPopId}
            </if>
            <if test="dto.emailAddress != null and dto.emailAddress != ''">
                and (e.from like concat('%',#{dto.emailAddress},'%') or e.recipient like concat('%',#{dto.emailAddress},'%') or e.recipient_cc like concat('%',#{dto.emailAddress},'%'))
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            <if test="dto.isStar != null and dto.isStar == 1">
                and e.is_star = #{dto.isStar}
            </if>
            <if test="dto.systemMail != null and dto.systemMail == 1">
                and e.from = 'system@storlead.com'
            </if>
            <if test="dto.systemMail == null">
                and (e.from is null or e.from <![CDATA[<>]]> 'system@storlead.com')
            </if>
            <if test="dto.isTrash != null">
                and is_trash = #{dto.isTrash}
            </if>
            <if test="dto.readStatu != null">
                and is_read = #{dto.readStatu}
            </if>
            <if test="dto.followUpState != null">
                <if test="dto.followUpState == 0">
                    and e.follow_up_id is null
                </if>
                <if test="dto.followUpState == 1">
                    and e.follow_up_id is not null
                </if>
            </if>
            <if test="dto.customerType == null">
                <if test="dto.bindCustomer != null and dto.bindCustomer == 0">
                    and (e.customer_ids = '' or e.customer_ids is null)
                </if>
                <if test="dto.bindCustomer != null and dto.bindCustomer == 1">
                    and e.customer_ids is not null
                </if>
            </if>
            <if test="dto.blurry != null and dto.blurry != ''">
                and (subject like concat('%',#{dto.blurry},'%') or content like concat('%',#{dto.blurry},'%') or `from` like concat('%',#{dto.blurry},'%') or recipient like concat('%',#{dto.blurry},'%'))
            </if>
        </where>
        and e.is_delete = 0
        order by e.recipient_date desc
    </select>


    <select id="pageListCus"  resultMap="BaseResultMap">
        select e.id, e.smtp_pop_id, e.msg_uid,e.message_id,e.is_receipt,e.is_only_head,e.is_track,e.read_remind,
        e.delay_send_time,e.customer_ids,e.liaison_ids, e.is_star,e.is_trash,e.subject,e.from, e.from_name, e.recipient,
        e.recipient_name, e.recipient_cc, e.recipient_cc_name,e. recipient_bcc, e.recipient_bcc_name, e.folder,e.remark,
        e.sent_date, e.recipient_date, e.email_size, e.is_read, e.reply_msg_id, e.status, e.owner_by, e.create_time, e.update_time,
        e.is_delete, e.enabled, e.create_by, e.update_by, e.sort,c.id as customer_id from  emails as e
        left join customer as c
        on FIND_IN_SET(c.id,e.customer_ids)
        <where>
            <if test="dto.ownerBy != null">
                and e.owner_by = #{dto.ownerBy}
            </if>
            <if test="dto.smtpPopId != null">
                and e.smtp_pop_id = #{dto.smtpPopId}
            </if>
            <if test="dto.customerId != null">
                and c.id = #{dto.customerId}
            </if>
            <if test="dto.customerId == null">
                and e.source_type = 0
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            <if test="dto.isStar != null and dto.isStar == 1">
                and e.is_star = #{dto.isStar}
            </if>
            <if test="dto.systemMail != null and dto.systemMail == 1">
                and e.from = 'system@storlead.com'
            </if>
            <if test="dto.systemMail == null">
                and (e.from is null or e.from <![CDATA[<>]]> 'system@storlead.com')
            </if>
            <if test="dto.isTrash != null">
                and is_trash = #{dto.isTrash}
            </if>
            <if test="dto.readStatu != null">
                and is_read = #{dto.readStatu}
            </if>
            <if test="dto.emailAddress != null and dto.emailAddress != ''">
                and (e.from like concat('%',#{dto.emailAddress},'%') or e.recipient like concat('%',#{dto.emailAddress},'%') or e.recipient_cc like concat('%',#{dto.emailAddress},'%'))
            </if>
            <if test="dto.customerName != null and dto.customerName != ''">
                and c.customer_name like concat('%',#{dto.customerName},'%')
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            <if test="dto.followUpState != null">
                <if test="dto.followUpState == 0">
                    and e.follow_up_id is null
                </if>
                <if test="dto.followUpState == 1">
                    and c.owner_by = #{dto.ownerBy}
                    and e.follow_up_id is not null
                    and c.is_delete  = 0
                </if>
                <if test="dto.bindCustomer != null and dto.bindCustomer == 0">
                    and c.id is null
                </if>
                <if test="dto.bindCustomer != null and dto.bindCustomer == 1">
                    and c.id is not null
                    and c.owner_by = #{dto.ownerBy}
                    and c.is_delete  = 0
                </if>
            </if>
            <if test="dto.customerType != null">
                and c.id is not null
                and c.owner_by = #{dto.ownerBy}
                and c.customer_form = #{dto.customerType}
                <if test="dto.customerLevelDictValue != null and dto.customerLevelDictValue != ''">
                    and c.customer_level_dict_value = #{dto.customerLevelDictValue}
                </if>

                <if test="dto.customerSourceDictValue != null and dto.customerSourceDictValue != ''">
                    and c.customer_source_dict_value = #{dto.customerSourceDictValue}
                </if>

                <if test="dto.customerTypeDictValue != null and dto.customerTypeDictValue != ''">
                    and c.customer_type_dict_value = #{dto.customerTypeDictValue}
                </if>
                <if test="dto.clueStatusDictValue != null and dto.clueStatusDictValue != ''">
                    and c.clue_status_dict_value = #{dto.clueStatusDictValue}
                </if>
                <if test="dto.continent != null and dto.continent != '' and dto.country != null and dto.country != ''">
                    and c.continent = #{dto.continent} and c.country = #{dto.country}
                </if>
                and c.is_delete = 0
            </if>
            <if test="dto.blurry != null and dto.blurry != ''">
                and (subject like concat('%',#{dto.blurry},'%') or content like concat('%',#{dto.blurry},'%') or `from` like concat('%',#{dto.blurry},'%') or recipient like concat('%',#{dto.blurry},'%'))
            </if>
            and e.is_delete = 0
            <if test="dto.customerType != null">
                AND e.id IN (
                    SELECT MAX(e1.id) FROM emails e1
                    LEFT JOIN customer c1 ON FIND_IN_SET(c1.id, e1.customer_ids)
                    where e1.is_delete = 0 and c1.is_delete = 0
                    <if test="dto.ownerBy != null">
                        and e1.owner_by =  #{dto.ownerBy}
                    </if>
                    <if test="dto.folder != null and dto.folder != ''">
                        and e1.folder = #{dto.folder}
                    </if>
                    <if test="dto.isTrash != null">
                        and e1.is_trash = #{dto.isTrash}
                    </if>
                    <if test="dto.smtpPopId != null">
                        and e1.smtp_pop_id = #{dto.smtpPopId}
                    </if>
                    <if test="dto.customerType != null">
                        and c.customer_form = #{dto.customerType}
                    </if>
                    GROUP BY c1.id
                )
            </if>
        </where>
        order by e.recipient_date desc
    </select>


    <select id="pageListAllCus"  resultMap="BaseResultMap">
        WITH ranked_emails AS (
        select e.id, e.smtp_pop_id, e.msg_uid,e.message_id,e.is_receipt,e.is_only_head,e.is_track,e.read_remind,
        e.delay_send_time,e.customer_ids,e.liaison_ids, e.is_star,e.is_trash,e.subject,e.from, e.from_name, e.recipient,
        e.recipient_name, e.recipient_cc, e.recipient_cc_name,e. recipient_bcc, e.recipient_bcc_name, e.folder,e.remark,
        e.sent_date, e.recipient_date, e.email_size, e.is_read, e.reply_msg_id, e.status, e.owner_by, e.create_time,
        e.update_time,
        e.is_delete, e.enabled, e.create_by, e.update_by, e.sort,c.id as customer_id
        ,ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY e.id DESC) AS rn
        from emails as e
        left join customer as c
        on FIND_IN_SET(c.id,e.customer_ids)
        <where>
            <if test="dto.ownerBy != null">
                and e.owner_by = #{dto.ownerBy}
            </if>
            <if test="dto.smtpPopId != null">
                and e.smtp_pop_id = #{dto.smtpPopId}
            </if>
            <if test="dto.customerId != null">
                and c.id = #{dto.customerId}
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            <if test="dto.isStar != null and dto.isStar == 1">
                and e.is_star = #{dto.isStar}
            </if>
            <if test="dto.systemMail != null and dto.systemMail == 1">
                and e.from = 'system@storlead.com'
            </if>
            <if test="dto.systemMail == null">
                and (e.from is null or e.from <![CDATA[<>]]> 'system@storlead.com')
            </if>
            <if test="dto.isTrash != null">
                and is_trash = #{dto.isTrash}
            </if>
            <if test="dto.readStatu != null">
                and is_read = #{dto.readStatu}
            </if>
            <if test="dto.emailAddress != null and dto.emailAddress != ''">
                and (e.from like concat('%',#{dto.emailAddress},'%') or e.recipient like
                concat('%',#{dto.emailAddress},'%') or e.recipient_cc like concat('%',#{dto.emailAddress},'%'))
            </if>
            <if test="dto.customerName != null and dto.customerName != ''">
                and c.customer_name like concat('%',#{dto.customerName},'%')
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            and e.source_type = 0
            <if test="dto.followUpState != null">
                <if test="dto.followUpState == 0">
                    and e.follow_up_id is null
                </if>
                <if test="dto.followUpState == 1">
                    and c.owner_by = #{dto.ownerBy}
                    and e.follow_up_id is not null
                    and c.is_delete = 0
                </if>
                <if test="dto.bindCustomer != null and dto.bindCustomer == 0">
                    and c.id is null
                </if>
                <if test="dto.bindCustomer != null and dto.bindCustomer == 1">
                    and c.id is not null
                    and c.owner_by = #{dto.ownerBy}
                    and c.is_delete = 0
                </if>
            </if>
            <if test="dto.customerType != null">
                and c.id is not null
                and c.owner_by = #{dto.ownerBy}
                and c.customer_form = #{dto.customerType}
                <if test="dto.customerLevelDictValue != null and dto.customerLevelDictValue != ''">
                    and c.customer_level_dict_value = #{dto.customerLevelDictValue}
                </if>

                <if test="dto.customerSourceDictValue != null and dto.customerSourceDictValue != ''">
                    and c.customer_source_dict_value = #{dto.customerSourceDictValue}
                </if>

                <if test="dto.customerTypeDictValue != null and dto.customerTypeDictValue != ''">
                    and c.customer_type_dict_value = #{dto.customerTypeDictValue}
                </if>
                <if test="dto.clueStatusDictValue != null and dto.clueStatusDictValue != ''">
                    and c.clue_status_dict_value = #{dto.clueStatusDictValue}
                </if>
                <if test="dto.continent != null and dto.continent != '' and dto.country != null and dto.country != ''">
                    and c.continent = #{dto.continent} and c.country = #{dto.country}
                </if>
                and c.is_delete = 0
            </if>
            <if test="dto.blurry != null and dto.blurry != ''">
                and (subject like concat('%',#{dto.blurry},'%') or content like concat('%',#{dto.blurry},'%') or `from`
                like concat('%',#{dto.blurry},'%') or recipient like concat('%',#{dto.blurry},'%'))
            </if>
            and e.is_delete = 0
        </where>
        order by e.recipient_date desc
        )
        SELECT * FROM ranked_emails re
        WHERE re.rn = 1
    </select>


    <select id="pageListNew"  resultMap="BaseResultMap">
        select e1.*,cb.id as customer_mail_id,cb.follow_up_id,cb.follow_up_time,GROUP_CONCAT(DISTINCT cb.customer_id ORDER BY e1.id ASC) as customer_ids  from
            (
            select e.id, e.smtp_pop_id, e.msg_uid,e.message_id,e.is_receipt,e.is_only_head,e.is_track,e.read_remind,
            e.delay_send_time, e.is_star,e.is_trash,e.subject,e.from, e.from_name, e.recipient,
            e.recipient_name, e.recipient_cc, e.recipient_cc_name,e. recipient_bcc, e.recipient_bcc_name, e.folder,e.remark,
            e.sent_date, e.recipient_date, e.email_size, e.is_read, e.reply_msg_id, e.status, e.owner_by, e.create_time, e.update_time,
            e.is_delete, e.enabled, e.create_by, e.update_by, e.sort from  emails as e
            <where>
                <if test="dto.smtpPopId != null">
                    and e.smtp_pop_id = #{dto.smtpPopId}
                </if>
                <if test="dto.emailAddress != null and dto.emailAddress != ''">
                    and (e.from like concat('%',#{dto.emailAddress},'%') or e.recipient like concat('%',#{dto.emailAddress},'%') or e.recipient_cc like concat('%',#{dto.emailAddress},'%'))
                </if>
                <if test="dto.folder != null and dto.folder != ''">
                    and e.folder = #{dto.folder}
                </if>
                <if test="dto.isStar != null and dto.isStar == 1">
                    and e.is_star = #{dto.isStar}
                </if>
                <if test="dto.systemMail != null and dto.systemMail == 1">
                    and e.from = 'system@storlead.com'
                </if>
                <if test="dto.systemMail == null">
                    and (e.from is null or e.from <![CDATA[<>]]> 'system@storlead.com')
                </if>
                <if test="dto.isTrash != null">
                    and e.is_trash = #{dto.isTrash}
                </if>
                <if test="dto.readStatu != null">
                    and e.is_read = #{dto.readStatu}
                </if>
                <if test="dto.blurry != null and dto.blurry != ''">
                    and (e.subject like concat('%',#{dto.blurry},'%') or e.content like concat('%',#{dto.blurry},'%'))
                </if>
                <if test="dto.folderId != null">
                    and e.custom_folder_id = #{dto.folderId}
                </if>
                <if test="dto.bindCustomer == null and dto.customerId == null">
                    <if test="dto.folderId == null and dto.isTrash == 0">
                        and e.custom_folder_id is null
                    </if>
                </if>
                <if test="dto.customerId == null">
                    and e.source_type = 0
                </if>
                and e.is_delete = 0
            </where>
        ) as e1
        left join customer_mail_bing_mark as cb
        on e1.id = cb.mail_id
        left join customer as c
        on cb.customer_id = c.id and c.is_delete = 0
        <where>
            <if test="dto.customerId != null">
                and c.id = #{dto.customerId}
            </if>
            <if test="(dto.customerName != null and dto.customerName != '')">
                and c.customer_name like concat('%',#{dto.customerName},'%')
                and c.owner_by = #{dto.ownerBy}
            </if>
            <if test="dto.customerLevelDictValue != null and dto.customerLevelDictValue != ''">
                and c.customer_level_dict_value = #{dto.customerLevelDictValue}
            </if>

            <if test="dto.customerSourceDictValue != null and dto.customerSourceDictValue != ''">
                and c.customer_source_dict_value = #{dto.customerSourceDictValue}
            </if>

            <if test="dto.customerTypeDictValue != null and dto.customerTypeDictValue != ''">
                and c.customer_type_dict_value = #{dto.customerTypeDictValue}
            </if>
            <if test="dto.clueStatusDictValue != null and dto.clueStatusDictValue != ''">
                and c.clue_status_dict_value = #{dto.clueStatusDictValue}
            </if>
            <if test="dto.continent != null and dto.continent != '' and dto.country != null and dto.country != ''">
                and c.continent = #{dto.continent} and c.country = #{dto.country}
            </if>
            <if test="dto.customerType != null">
                and c.customer_form = #{dto.customerType}
            </if>
        </where>
        <if test="dto.customerType == null">
            GROUP BY e1.id
        </if>
        <if test="dto.customerType != null">
            GROUP BY e1.id,cb.customer_id
        </if>
        <if test="dto.followUpState != null and dto.followUpState == 0">
            <if test="dto.bindCustomer != null and dto.bindCustomer == 0">
                HAVING customer_ids is null and reply_msg_id is null
            </if>
            <if test="dto.bindCustomer != null and dto.bindCustomer == 1">
                HAVING customer_ids is not null and follow_up_id is null
            </if>
        </if>
        order by e1.recipient_date desc
    </select>


    <select id="pageListNewAllCus"  resultMap="BaseResultMap">
        WITH ranked_emails AS (
        select e1.*,cc.customer_id as customer_ids,ROW_NUMBER() OVER (PARTITION BY cc.customer_id ORDER BY e1.id DESC) AS rn
        from
        (
        select e.id, e.smtp_pop_id, e.msg_uid,e.message_id,e.is_receipt,e.is_only_head,e.is_track,e.read_remind,
        e.delay_send_time, e.is_star,e.is_trash,e.subject,e.from, e.from_name, e.recipient,
        e.recipient_name, e.recipient_cc, e.recipient_cc_name,e. recipient_bcc, e.recipient_bcc_name, e.folder,e.remark,
        e.sent_date, e.recipient_date, e.email_size, e.is_read, e.reply_msg_id, e.status, e.owner_by, e.create_time,
        e.update_time,
        e.is_delete, e.enabled, e.create_by, e.update_by, e.sort from emails as e
        <where>
            <if test="dto.smtpPopId != null">
                and e.smtp_pop_id = #{dto.smtpPopId}
            </if>
            <if test="dto.emailAddress != null and dto.emailAddress != ''">
                and (e.from like concat('%',#{dto.emailAddress},'%') or e.recipient like
                concat('%',#{dto.emailAddress},'%') or e.recipient_cc like concat('%',#{dto.emailAddress},'%'))
            </if>
            <if test="dto.folder != null and dto.folder != ''">
                and e.folder = #{dto.folder}
            </if>
            <if test="dto.isStar != null and dto.isStar == 1">
                and e.is_star = #{dto.isStar}
            </if>
            <if test="dto.systemMail != null and dto.systemMail == 1">
                and e.from = 'system@storlead.com'
            </if>
            <if test="dto.systemMail == null">
                and (e.from is null or e.from <![CDATA[<>]]> 'system@storlead.com')
            </if>
            <if test="dto.isTrash != null">
                and e.is_trash = #{dto.isTrash}
            </if>
            <if test="dto.readStatu != null">
                and e.is_read = #{dto.readStatu}
            </if>
            <if test="dto.followRemind != null">
                and e.subject = '跟进提醒'
            </if>
            <if test="dto.customerId == null">
                and e.source_type = 0
            </if>
            <if test="dto.blurry != null and dto.blurry != ''">
                and (e.subject like concat('%',#{dto.blurry},'%') or e.content like concat('%',#{dto.blurry},'%'))
            </if>
            and e.is_delete = 0
        </where>
        ) as e1
        left join (
            SELECT
            cb.customer_id,
            cb.mail_id,
            c.customer_form
            FROM
            customer_mail_bing_mark AS cb
            LEFT JOIN customer AS c ON cb.customer_id = c.id
            WHERE  c.is_delete = 0
            AND c.owner_by = #{dto.ownerBy}
            <if test="dto.customerId != null">
                and c.id = #{dto.customerId}
            </if>
            <if test="(dto.customerName != null and dto.customerName != '')">
                and c.customer_name like concat('%',#{dto.customerName},'%')
                and c.owner_by = #{dto.ownerBy}
            </if>
            <if test="dto.customerLevelDictValue != null and dto.customerLevelDictValue != ''">
                and c.customer_level_dict_value = #{dto.customerLevelDictValue}
            </if>

            <if test="dto.customerSourceDictValue != null and dto.customerSourceDictValue != ''">
                and c.customer_source_dict_value = #{dto.customerSourceDictValue}
            </if>

            <if test="dto.customerTypeDictValue != null and dto.customerTypeDictValue != ''">
                and c.customer_type_dict_value = #{dto.customerTypeDictValue}
            </if>
            <if test="dto.clueStatusDictValue != null and dto.clueStatusDictValue != ''">
                and c.clue_status_dict_value = #{dto.clueStatusDictValue}
            </if>
            <if test="dto.customerType != null">
                and c.customer_form = #{dto.customerType}
            </if>
            <if test="dto.continent != null and dto.continent != '' and dto.country != null and dto.country != ''">
                and c.continent = #{dto.continent} and c.country = #{dto.country}
            </if>
        ) as cc
         on cc.mail_id = e1.id
         where e1.owner_by = #{dto.ownerBy} and cc.mail_id is not null
         order by e1.recipient_date desc
       )
       SELECT * FROM ranked_emails re
       WHERE re.rn = 1
    </select>

    <select id="countMailSummaryNum" resultType="com.storlead.mail.pojo.vo.NewMailCountTipVO">
        SELECT
                IFNULL(SUM(CASE WHEN folder = 'INBOX' AND is_read = 0 and is_trash = 0 and `from` <![CDATA[<>]]> 'system@storlead.com' THEN 1 ELSE 0 END),0) AS inboxCount,
                IFNULL(SUM(CASE WHEN folder = 'SENT' AND is_delete = 0 and is_trash = 0 THEN 1 ELSE 0 END),0) AS sentCount,
                IFNULL(SUM(CASE WHEN folder = 'SENTING' AND is_delete = 0 and is_trash = 0 THEN 1 ELSE 0 END),0) AS sentingCount,
                IFNULL(SUM(CASE WHEN folder = 'DRAFT' AND is_delete = 0 and is_trash = 0 THEN 1 ELSE 0 END),0) AS draftCount,
                IFNULL(SUM(CASE WHEN `subject` = '跟进提醒' AND is_delete = 0 THEN 1 ELSE 0 END),0) AS followUpCount,
                IFNULL(SUM(CASE WHEN `from` = 'system@storlead.com' AND is_read = 0 THEN 1 ELSE 0 END),0) AS systemCount,
                IFNULL(SUM(CASE WHEN is_star = 1 THEN 1 ELSE 0 END),0) AS starCount,
                IFNULL(SUM(CASE WHEN is_trash = 1 THEN 1 ELSE 0 END),0) AS trashCount
            FROM emails WHERE is_delete = 0 and owner_by = #{ownerBy} and smtp_pop_id = #{smtpPopId} and custom_folder_id is null and source_type = 0
    </select>

    <select id="countCustomerFollowUpMailNum" resultType="com.storlead.mail.pojo.vo.NewMailCountTipVO">
        select
            IFNULL(SUM(CASE WHEN m.customer_ids is null and m.reply_msg_id is null THEN 1 ELSE 0 END),0) AS unknownCount,
                   IFNULL(SUM(CASE WHEN m.customer_ids is not null and m.follow_up_id is null  THEN 1 ELSE 0 END),0) AS knownCount
        from (
        select e1.id,e1.reply_msg_id,cb.follow_up_id as follow_up_id,GROUP_CONCAT(DISTINCT cb.customer_id ORDER BY e1.id ASC) as customer_ids
        from emails as e1
        left join customer_mail_bing_mark as cb
        on e1.id = cb.mail_id
        left join customer as c
        on e1.id = cb.mail_id
        and cb.customer_id = c.id and c.is_delete = 0
        where e1.owner_by = #{ownerBy} and e1.smtp_pop_id = #{smtpPopId} and e1.from <![CDATA[<>]]> 'system@storlead.com'
          AND e1.is_delete = 0
          AND e1.folder = 'INBOX'
          AND e1.is_trash = 0
          AND e1.is_delete = 0
          and e1.source_type = 0
        GROUP BY e1.id
        )	as m
    </select>

    <select id="countCustomerAndClueNumber" resultType="com.storlead.mail.pojo.vo.NewMailCountTipVO">
        SELECT
            IFNULL(SUM( CASE WHEN m.customer_form = 10 THEN 1 ELSE 0 END ),0) AS customerCount,
            IFNULL(SUM( CASE WHEN m.customer_form = 11 THEN 1 ELSE 0 END ),0) AS clueCount
        FROM
            (
                SELECT
                    cb.customer_id,
                    c.customer_form,
                    MAX( cb.mail_id ) AS mail_id
                FROM
                    customer_mail_bing_mark AS cb
                        LEFT JOIN customer AS c ON cb.customer_id = c.id
                        left join emails as e on e.id = cb.mail_id and e.smtp_pop_id = #{smtpPopId}
                WHERE c.is_delete = 0
                 AND c.owner_by = #{ownerBy}
                 AND e.id is not null
                GROUP BY
                    cb.customer_id,
                    c.customer_form
            ) AS m
    </select>

    <select id="selectCustomerLastFollowUpTime" resultType="java.time.LocalDateTime">
        SELECT
            max( follow_up_time ) AS follow_up_time
        FROM
            (
                SELECT
                    max( create_time ) AS follow_up_time
                FROM
                    customer_follow_up
                WHERE
                    customer_id =  #{customerId}
                UNION ALL
                SELECT
                    max( sent_date ) AS follow_up_time
                FROM
                    customer_mail_bing_mark AS mbm
                        LEFT JOIN emails AS e1 ON e1.id = mbm.mail_id
                WHERE
                    mbm.customer_id =  #{customerId}
                    and e1.source_type = 0
            ) AS m

    </select>

    <!-- 获取删除后需要删除服务器的邮件 -->
    <select id="selectDelayDeleteMail" resultMap="BaseResultMap">
--         SELECT id,smtp_pop_id, msg_uid, message_id,folder,create_time,sent_date,delete_tag FROM emails e
--             WHERE e.is_only_head = 0 AND e.smtp_pop_id = 10 and delete_tag = 0
--             AND e.create_time <![CDATA[<]]> DATE_SUB(NOW(), INTERVAL 15 DAY)
--                 an'd'
--             AND EXISTS ( SELECT 1 FROM smtp_pop_settings sp WHERE sp.id = e.smtp_pop_id AND sp.smtp_pop_settings = 1)
--             AND NOT EXISTS ( SELECT 1 FROM mail_attachment ma WHERE ma.email_id = e.id AND ma.download <![CDATA[<>]]> 1) order by sent_date desc limit 10;
        SELECT
            id,
            smtp_pop_id,
            msg_uid,
            message_id,
            folder,
            create_time,
            sent_date,
            delete_tag,
            is_delete
        FROM
            emails e
        WHERE
            e.is_only_head = 0
            AND delete_tag = 0
            AND recipient_date IS NOT NULL
            AND ( e.folder = 'INBOX' OR e.folder = 'SENT' )
            AND ( ( e.recipient_date > '2025-11-13 15:45:09' AND e.recipient_date <![CDATA[<]]> DATE_SUB( NOW( ), INTERVAL 15 DAY ) ) )
            AND e.delete_tag = 0
            AND EXISTS ( SELECT 1 FROM smtp_pop_settings sp WHERE sp.id = e.smtp_pop_id )
            AND NOT EXISTS ( SELECT 1 FROM mail_attachment ma WHERE ma.email_id = e.id AND ma.download <![CDATA[<>]]> 1 )

    </select>

<!--    <select id="selectUserClickTitle" resultType="com.storlead.mail.pojo.vo.UserClickTitleVO">-->
<!--        SELECT a.id as dataId,a.subject as title,b.click_count AS clickCount FROM emails as a LEFT JOIN user_click_record as b ON a.id = b.data_id and b.click_type = 1-->
<!--        where a.owner_by = #{ownerBy} and a.is_delete = 0-->
<!--          <if test="title != null and title != ''">-->
<!--              and a.`subject` like concat('%',#{title},'%')-->
<!--          </if>-->
<!--          order by b.click_count desc limit 10-->
<!--    </select>-->

    <select id="selectUserClickTitle" resultType="com.storlead.mail.pojo.vo.UserClickTitleVO">
        SELECT
        dataId,
        title,
        clickCount
        FROM
        (
        SELECT
        a.id AS dataId,
        a.SUBJECT AS title,
        b.click_count AS clickCount,
        ROW_NUMBER ( ) OVER ( PARTITION BY a.SUBJECT ORDER BY b.click_count DESC ) AS rn
        FROM
        emails AS a
        LEFT JOIN user_click_record AS b ON a.id = b.data_id
        AND b.click_type = 1
        WHERE
        a.owner_by = #{ownerBy}
        <if test="title != null and title != ''">
            AND a.`subject` LIKE CONCAT('%',#{title},'%')
        </if>
        AND a.is_delete = 0
        ) AS t
        WHERE
        t.rn = 1
        ORDER BY
        clickCount DESC
        LIMIT 10;
    </select>

    <select id="selectCustomerEmailPage" resultType="com.storlead.mail.pojo.vo.CustomerEmailVo">
        SELECT
            cm.mail_id AS mailId,
            e.from_name AS fromName,
            e.recipient_date AS recipientDate,
            e.recipient_name AS recipientName,
            e.recipient AS recipient,
            e.subject AS subject,
            e.in_out_mark AS inOutMark
        FROM
            customer_mail_bing_mark AS cm
            LEFT JOIN emails AS e ON e.id = cm.mail_id
            WHERE
            cm.customer_id = #{query.customerId}
        <if test="query.blurry != null and query.blurry != ''">
            AND e.`subject` LIKE CONCAT('%',#{query.blurry},'%')
        </if>
        <if test="query.liaisonId != null and query.liaisonId != ''">
            AND FIND_IN_SET(#{query.liaisonId}, cm.`liaison_ids`)
        </if>
        <if test="query.beginTime != null and query.endTime != null">
            and e.recipient_date >= #{query.beginTime}  and e.recipient_date <![CDATA[<=]]> #{query.endTime}
        </if>
            AND e.is_delete = 0
        ORDER BY
            e.recipient_date
        DESC
    </select>

    <select id="selectCusIdByMailId" resultType="java.lang.Long">
        select customer_id from customer_mail_bing_mark where is_delete = 0
        and mail_id in
        <foreach collection="mailIdls" item="mailId" open="(" separator="," close=")">
            #{mailId}
        </foreach>
    </select>

    <select id="selectCusInfoByCusId" resultType="com.storlead.mail.pojo.vo.CustomerMailVO">
        select customer_name as customerName,country from customer where is_delete = 0
        and id in
        <foreach collection="customerIdls" item="customerId" open="(" separator="," close=")">
            #{customerId}
        </foreach>
    </select>

    <select id="countSmtpMailCount" resultType="java.lang.Integer">
        select count(1) from smtp_pop_settings where is_delete = 0 and owner_by = #{userId}
    </select>
</mapper>
