-- 用途：从组织库筛选“多个公司 + 多个部门”的被访人样本
-- MySQL：连接主机/端口/账号按**当前环境**填写（开发与生产分离；不要用开发库导出的样本去打生产）
--
-- 已与 component-organization 典型结构对齐（2026-04-30 开发库 INFORMATION_SCHEMA 核对）：
--   cw_is_person 人员主键列为 ID（无 person_id）；删除标记 IS_DEL（无 deleted）；
--   无 labels/business_name/organization_name 列；访客身份通过 cw_is_person_label_ref + cw_is_label 识别。
-- 连接参数可复制 maven-cw-elevator-application/tools/visitor_floor_verification/.env.visitor_verify（勿提交密钥）。

SELECT
  p.BUSINESS_ID AS business_id,
  p.ID AS meng_person_id,
  COALESCE(parent_org.NAME, '') AS company,
  COALESCE(o.NAME, '') AS department
FROM `component-organization`.`cw_is_person` p
INNER JOIN `component-organization`.`cw_is_person_organization_ref` r ON r.PERSON_ID = p.ID
LEFT JOIN `component-organization`.`cw_is_organization` o ON o.ID = r.ORG_ID
LEFT JOIN `component-organization`.`cw_is_organization` parent_org ON parent_org.ID = o.PARENT_ID
WHERE (p.IS_DEL = 0 OR p.IS_DEL IS NULL)
  AND p.BUSINESS_ID IS NOT NULL
  AND p.BUSINESS_ID <> ''
  AND NOT EXISTS (
    SELECT 1
    FROM `component-organization`.`cw_is_person_label_ref` lr
    INNER JOIN `component-organization`.`cw_is_label` lb ON lb.ID = lr.LABEL_ID
    WHERE lr.PERSON_ID = p.ID
      AND lb.BUSINESS_ID = p.BUSINESS_ID
      AND lb.NAME = '访客'
  )
ORDER BY p.BUSINESS_ID, department, p.LAST_UPDATE_TIME DESC;

-- 建议导出后人工抽样：
-- 1) 至少 3 个 business_id
-- 2) 每个 business_id 至少 2 个不同 department
-- 3) 生成 batch_cases.csv，列头固定为：
--    business_id,meng_person_id,company,department
