<?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.ruoyi.ibs.visit.mapper.VisitInfoMapper">
    <select id="queryVisitCustomerCount" resultType="VisitCustomerCount">
        select
            T.vis_id,
            case when T.cust_type =2 then '企业' WHEN T.cust_type = 1 then '商户' else '个人' end as cust_type,
            COUNT(DISTINCT T.cid) As customer_count_by_type
        FROM (SELECT DISTINCT
                  campaign_name,
                  vis_id,
                  --- 脱敏客户 ID
                  concat(substr(md5(coalesce(cust_idc,'')),1,8),'^')as cid,
                  -- 脱敏社会信用代码(可选)
                  concat(substr(md5(coalesce(social_credit_code,'')),1,8),'^')as scc,
                  -- 客户类型(关键字段)
                  cust_type,
                  remark,
                  vis_time,
                  day(vis_time) As d
              FROM visit_info_${deptCode}
              WHERE length(remark) > 0
                <if test="year != null and year != ''">
                    AND year(vis_time)= #{year}
                </if>
                <if test="month != null and month != ''">
                    AND month(vis_time)=#{month}
                </if>
              ) T
        GROUP BY T.vis_id, cust_type
        ORDER BY T.vis_id, customer_count_by_type DESC ;
    </select>
    <select id="queryVisitIdRemark" resultType="VisitIdRemark">
        SELECT DISTINCT
            campaign_name,
            CONCAT(cust_name, '') customer_name,
            CONCAT(social_credit_code, '') AS ssc,
            CASE WHEN cust_type = 2 THEN '企业' WHEN cust_type = 1 THEN '商户' ELSE '个人' end as cust_type,
            -- 替换 regexp_replace 为 MySQL 低版本兼容写法
            IF(
                        remark REGEXP '1[3-9][0-9]{4}[0-9]{4}',
                        CONCAT(
                                SUBSTRING(remark, 1, 2),  -- 保留第一位数字和第二位数字
                                '****',                    -- 中间替换为****
                                SUBSTRING(remark, 7)       -- 保留最后四位数字
                        ),
                        remark  -- 不匹配则返回原字符串
            ) AS remark_without_mobile,
            DAY(vis_time) AS d,
            HOUR(vis_time) AS h
        FROM visit_info_${deptCode}
        WHERE LENGTH(remark) > 0
        <if test="year != null and year != ''">
            AND year(vis_time)= #{year}
        </if>
        <if test="month != null and month != ''">
            AND month(vis_time)=#{month}
        </if>
          AND vis_id = #{visId}
        ORDER BY d, h, campaign_name, customer_name;
    </select>


</mapper>