-- ---------------------------------------------------------------------------
-- 历史补录（可选）：从 wecom_inbound_trace 批量写入 wecom_share_link_logistics_job
--
-- 优先使用后台「企微分享链物流」页「从追踪补录历史」按钮（Java 与线上一致，支持 http/https、备注行含链等）。
--
-- 需 MySQL 8.0.14+（LATERAL、REGEXP_SUBSTR）。可重复执行（按 job_key 去重）。
-- ---------------------------------------------------------------------------

INSERT INTO wecom_share_link_logistics_job (
  job_key, from_user_name, tracking_url, remark, touser_push, status, scan_attempts, last_note,
  create_time, update_time
)
SELECT
  CONCAT('tracebf', t.id),
  t.from_user_name,
  COALESCE(
    NULLIF(REGEXP_SUBSTR(t.content, 'https://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(t.content, 'http://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(p.content, 'https://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(p.content, 'http://3\\.cn/[A-Za-z0-9\\-]+'), '')
  ),
  t.content,
  t.from_user_name,
  'IMPORTED',
  0,
  CONCAT('from_trace_id=', t.id, '|sql_batch'),
  t.create_time,
  t.create_time
FROM wecom_inbound_trace t
LEFT JOIN LATERAL (
  SELECT p0.content
  FROM wecom_inbound_trace p0
  WHERE p0.from_user_name = t.from_user_name
    AND p0.id < t.id
    AND (p0.content LIKE '%https://3.cn/%' OR p0.content LIKE '%http://3.cn/%')
  ORDER BY p0.id DESC
  LIMIT 1
) AS p ON TRUE
WHERE t.reply_content LIKE '%已加入查询队列%'
  AND COALESCE(
    NULLIF(REGEXP_SUBSTR(t.content, 'https://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(t.content, 'http://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(p.content, 'https://3\\.cn/[A-Za-z0-9\\-]+'), ''),
    NULLIF(REGEXP_SUBSTR(p.content, 'http://3\\.cn/[A-Za-z0-9\\-]+'), '')
  ) IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM wecom_share_link_logistics_job e WHERE e.job_key = CONCAT('tracebf', t.id)
  );
