<?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.zcloud.personnel.positioning.persistence.mapper.AlarmRuleMapper">
    <select id="listCompanyStats"
            resultType="com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleCompanyStatDO">
        SELECT corpinfo_id,
               corpinfo_name,
               COUNT(1) AS config_count,
               SUM(CASE WHEN enable = 1 OR rule_status = 'ENABLED' THEN 1 ELSE 0 END) AS enabled_count,
               COALESCE(MAX(last_sync_time), MAX(update_time)) AS last_sync_time
        FROM alarm_rule
        WHERE (delete_enum IS NULL OR delete_enum = 'FALSE')
        <if test="params.eqCorpinfoId != null and params.eqCorpinfoId != ''">
            AND corpinfo_id = #{params.eqCorpinfoId}
        </if>
        <if test="params.likeCorpinfoName != null and params.likeCorpinfoName != ''">
            AND corpinfo_name LIKE CONCAT('%', #{params.likeCorpinfoName}, '%')
        </if>
        <if test="params.likeContactName != null and params.likeContactName != ''">
            AND EXISTS (
                SELECT 1
                FROM corp_info ci
                WHERE CAST(ci.corpinfo_id AS CHAR) = CAST(alarm_rule.corpinfo_id AS CHAR)
                  AND (ci.delete_enum IS NULL OR ci.delete_enum = 'FALSE')
                  AND ci.contacts LIKE CONCAT('%', #{params.likeContactName}, '%')
            )
        </if>
        <if test="params.eqRuleStatus != null and params.eqRuleStatus != ''">
            AND rule_status = #{params.eqRuleStatus}
        </if>
        <if test="params.eqEnable != null">
            AND enable = #{params.eqEnable}
        </if>
        GROUP BY corpinfo_id, corpinfo_name
        ORDER BY COALESCE(MAX(last_sync_time), MAX(update_time)) DESC
    </select>

    <select id="listCompanyOptions"
            resultType="com.zcloud.personnel.positioning.persistence.dataobject.CompanyOptionDO">
        SELECT corp_name AS label, CAST(corpinfo_id AS CHAR) AS value
        FROM corp_info
        WHERE (delete_enum IS NULL OR delete_enum = 'FALSE')
          AND corpinfo_id IS NOT NULL
          AND corp_name IS NOT NULL
        <if test="params.eqCorpinfoId != null and params.eqCorpinfoId != ''">
            AND corpinfo_id = #{params.eqCorpinfoId}
        </if>
        <if test="params.keyword != null and params.keyword != ''">
            AND (corp_name LIKE CONCAT('%', #{params.keyword}, '%')
                OR code LIKE CONCAT('%', #{params.keyword}, '%')
                OR contacts LIKE CONCAT('%', #{params.keyword}, '%')
                OR lr_name LIKE CONCAT('%', #{params.keyword}, '%'))
        </if>
        ORDER BY corp_name ASC
        LIMIT 200
    </select>
</mapper>
