-- ============================================================
-- 装修模板只留 4 套轻奢：素胚 / 珠贝白 / 胡桃木 / 香槟金
-- 其余软删；经销商与应用绑了已删 code 的回落到空（走品牌默认）
-- 本脚本可重复执行：缺列先补，已处理过的行不再变
-- ============================================================

SET @db := DATABASE();
SET @now := UNIX_TIMESTAMP();

-- 有的库还没跑过 2026-08-14/03，cc_wx_user 没有 template_code，先补列再纠偏
SET @exists := (
    SELECT COUNT(*) FROM information_schema.COLUMNS
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'cc_wx_user' AND COLUMN_NAME = 'template_code'
);
SET @sql := IF(@exists = 0,
    'ALTER TABLE `cc_wx_user` ADD COLUMN `template_code` varchar(50) NOT NULL DEFAULT '''' COMMENT ''经销商专属装修模板 code，空=跟随品牌默认'' AFTER `price_number`',
    'SELECT ''skip cc_wx_user.template_code'' AS msg'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

UPDATE `cc_wx_template`
SET `deleted_at` = @now, `updated_at` = @now, `is_default` = 0
WHERE `deleted_at` = 0
  AND `code` NOT IN ('nature-clay', 'lux-pearl', 'lux-walnut', 'lux-champagne');

UPDATE `cc_wx_template`
SET `name` = '素胚', `style_tag` = '轻奢', `updated_at` = @now
WHERE `code` = 'nature-clay' AND `deleted_at` = 0;

UPDATE `cc_wx_user` u
LEFT JOIN `cc_wx_template` t
    ON t.`code` = u.`template_code` AND t.`deleted_at` = 0
SET u.`template_code` = ''
WHERE u.`template_code` <> '' AND t.`id` IS NULL;

-- nl_wx_app 可能尚未建表，没有表就跳过
SET @app_exists := (
    SELECT COUNT(*) FROM information_schema.TABLES
    WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'nl_wx_app'
);
SET @sql := IF(@app_exists = 0,
    'SELECT ''skip nl_wx_app (table missing)'' AS msg',
    'UPDATE `nl_wx_app` a
     LEFT JOIN `cc_wx_template` t
         ON t.`code` = a.`template_code` AND t.`deleted_at` = 0
     SET a.`template_code` = ''lux-champagne'', a.`updated_at` = UNIX_TIMESTAMP()
     WHERE a.`template_code` <> '''' AND t.`id` IS NULL'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
