-- =============================================================================
-- 清理「无 uploadRecordId」的后返备注，便于重新上传后带上批次 ID
-- 执行前请先备份 jd_order 或整库；建议先跑预览 SELECT
-- 库名请按实际执行 USE（示例库名 jd）
-- =============================================================================

-- USE jd;

-- ---------------------------------------------------------------------------
-- 方案 A（推荐）：整条 JSON 里从未出现 "uploadRecordId" 的订单 → 整段清空为 []
-- 适用：历史导入都没有批次 ID，准备整批重传
-- ---------------------------------------------------------------------------

SELECT COUNT(*) AS cnt_will_clear
FROM jd_order
WHERE rebate_remark_json IS NOT NULL
  AND CHAR_LENGTH(TRIM(rebate_remark_json)) > 2
  AND rebate_remark_json NOT LIKE '%"uploadRecordId"%';

/*
START TRANSACTION;

UPDATE jd_order
SET rebate_remark_json = '[]',
    rebate_remark_has_abnormal = 0
WHERE rebate_remark_json IS NOT NULL
  AND CHAR_LENGTH(TRIM(rebate_remark_json)) > 2
  AND rebate_remark_json NOT LIKE '%"uploadRecordId"%';

COMMIT;
-- 若需回滚：ROLLBACK;
*/


-- ---------------------------------------------------------------------------
-- 方案 B（可选，MySQL 8.0+）：从 JSON 数组里只保留带 uploadRecordId 的元素
-- 适用：同一订单里混有新旧备注，只想删掉无批次 ID 的旧条
-- 要求：rebate_remark_json 为合法 JSON；无效行会报错，请先修正或跳过
-- ---------------------------------------------------------------------------

/*
START TRANSACTION;

UPDATE jd_order o
INNER JOIN (
  SELECT o2.id AS oid,
    COALESCE(
      (
        SELECT JSON_ARRAYAGG(j.elem)
        FROM JSON_TABLE(o2.rebate_remark_json, '$[*]'
          COLUMNS (elem JSON PATH '$')
        ) AS j
        WHERE JSON_EXTRACT(j.elem, '$.uploadRecordId') IS NOT NULL
      ),
      JSON_ARRAY()
    ) AS new_j
  FROM jd_order o2
  WHERE o2.rebate_remark_json IS NOT NULL
    AND CHAR_LENGTH(TRIM(o2.rebate_remark_json)) > 2
    AND JSON_VALID(o2.rebate_remark_json)
) t ON o.id = t.oid
SET o.rebate_remark_json = CAST(t.new_j AS CHAR),
    o.rebate_remark_has_abnormal = CASE
      WHEN JSON_LENGTH(t.new_j) = 0 THEN 0
      WHEN CAST(t.new_j AS CHAR) LIKE '%"abnormal":true%' THEN 1
      ELSE 0
    END
WHERE CAST(t.new_j AS CHAR) <> o.rebate_remark_json;

COMMIT;
*/
