-- =============================================================================
-- 闲管家 ERP：erp_open_config / erp_goofish_order 一键升级脚本
-- =============================================================================
-- 用法：
--   1. 先备份数据库；连接目标库后执行（或在文件开头加 USE your_database;）
--   2. 可重复执行：已存在的列/索引会自动跳过
--   3. ADD COLUMN 一律不指定 AFTER，避免旧表缺中间列时升级失败（新列落在表尾，不影响业务）
-- 环境：MySQL 5.7+ / 8.x（MariaDB 未逐项验证）
-- =============================================================================

SET @schema := DATABASE();

-- ----------------------------------------------------------------------------- 
-- 1) 表不存在时创建完整结构（与 erp_goofish_init.sql 一致）
-- ----------------------------------------------------------------------------- 
CREATE TABLE IF NOT EXISTS erp_open_config (
  id              bigint(20)   NOT NULL AUTO_INCREMENT COMMENT '主键',
  app_key         varchar(64)  NOT NULL COMMENT '开放平台 AppKey(appid)',
  app_secret      varchar(128) NOT NULL COMMENT '开放平台 AppSecret',
  xy_user_name    varchar(128)          DEFAULT NULL COMMENT '默认闲鱼会员名（展示）',
  express_code    varchar(64)           DEFAULT NULL COMMENT '发货用快递公司编码（日日顺物流在官方列表中为 rrs）',
  express_name    varchar(64)           DEFAULT NULL COMMENT '快递公司名称（展示）',
  status          char(1)      NOT NULL DEFAULT '0' COMMENT '0正常 1停用',
  order_num       int(11)      NOT NULL DEFAULT 0 COMMENT '排序（小优先）',
  create_by       varchar(64)           DEFAULT '',
  create_time     datetime              DEFAULT NULL,
  update_by       varchar(64)           DEFAULT '',
  update_time     datetime              DEFAULT NULL,
  remark          varchar(500)          DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (id),
  UNIQUE KEY uk_app_key (app_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='闲管家开放平台应用配置';

CREATE TABLE IF NOT EXISTS erp_goofish_order (
  id               bigint(20)   NOT NULL AUTO_INCREMENT COMMENT '主键',
  app_key          varchar(64)  NOT NULL COMMENT 'AppKey',
  seller_id        bigint(20)            DEFAULT NULL COMMENT '商家ID',
  user_name        varchar(128)          DEFAULT NULL COMMENT '闲鱼会员名',
  order_no         varchar(64)  NOT NULL COMMENT '闲鱼订单号',
  order_type       int(11)               DEFAULT NULL COMMENT '订单类型',
  order_status     int(11)               DEFAULT NULL COMMENT '订单状态(推送/列表)',
  refund_status    int(11)               DEFAULT NULL COMMENT '退款状态',
  modify_time      bigint(20)            DEFAULT NULL COMMENT '订单更新时间(秒)',
  product_id       bigint(20)            DEFAULT NULL COMMENT '管家商品ID',
  item_id          bigint(20)            DEFAULT NULL COMMENT '闲鱼商品ID',
  goods_title      varchar(512)          DEFAULT NULL COMMENT '商品标题(详情 goods.title)',
  goods_image_url  varchar(1024)         DEFAULT NULL COMMENT '商品主图 URL(goods.images 首图)',
  buyer_nick       varchar(256)          DEFAULT NULL COMMENT '买家昵称(详情 buyer_nick)',
  pay_amount       bigint(20)            DEFAULT NULL COMMENT '实付金额(分) pay_amount',
  detail_waybill_no varchar(128)         DEFAULT NULL COMMENT '闲管家详情回传运单号 waybill_no',
  detail_express_code varchar(64)       DEFAULT NULL COMMENT '详情快递编码 express_code',
  detail_express_name varchar(128)      DEFAULT NULL COMMENT '详情快递名称 express_name',
  receiver_name    varchar(128)          DEFAULT NULL COMMENT '收货人(详情有则落库)',
  receiver_mobile  varchar(64)           DEFAULT NULL COMMENT '收货手机',
  receiver_address varchar(1000)         DEFAULT NULL COMMENT '收货详细地址(address)',
  receiver_region  varchar(256)          DEFAULT NULL COMMENT '省市区街道等拼接展示',
  recv_prov_name   varchar(64)           DEFAULT NULL COMMENT 'prov_name',
  recv_city_name   varchar(64)           DEFAULT NULL COMMENT 'city_name',
  recv_area_name   varchar(64)           DEFAULT NULL COMMENT 'area_name',
  recv_town_name   varchar(128)          DEFAULT NULL COMMENT 'town_name',
  detail_json      longtext COMMENT '订单详情接口全量 JSON',
  last_notify_json longtext COMMENT '最近一次推送原文 JSON',
  jd_order_id      bigint(20)            DEFAULT NULL COMMENT '关联 jd_order.id（第三方单号=闲鱼单号）',
  local_waybill_no varchar(128)          DEFAULT NULL COMMENT '本地物流扫描得到的运单号',
  ship_status      tinyint(4)   NOT NULL DEFAULT '0' COMMENT '0未发货 1已调用发货成功 2发货失败',
  ship_error       varchar(500)          DEFAULT NULL COMMENT '发货失败原因',
  ship_time        datetime              DEFAULT NULL COMMENT '发货调用成功时间',
  ship_express_code varchar(64)          DEFAULT NULL COMMENT '实际发货使用的快递编码',
  create_time      datetime              DEFAULT NULL,
  update_time      datetime              DEFAULT NULL,
  PRIMARY KEY (id),
  UNIQUE KEY uk_app_order (app_key, order_no),
  KEY idx_jd_order (jd_order_id),
  KEY idx_order_status (order_status),
  KEY idx_modify_time (modify_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='闲管家 ERP 订单（全量跟踪）';

-- ----------------------------------------------------------------------------- 
-- 2) 存储过程：列不存在则 ADD
-- ----------------------------------------------------------------------------- 
DROP PROCEDURE IF EXISTS jarvis_erp_goofish_add_column;
DROP PROCEDURE IF EXISTS jarvis_erp_goofish_add_index;

DELIMITER $$

CREATE PROCEDURE jarvis_erp_goofish_add_column(
  IN p_table  VARCHAR(64),
  IN p_column VARCHAR(64),
  IN p_ddl    TEXT
)
BEGIN
  DECLARE col_exists INT DEFAULT 0;
  SELECT COUNT(*) INTO col_exists
    FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = @schema
     AND TABLE_NAME = p_table
     AND COLUMN_NAME = p_column;
  IF col_exists = 0 THEN
    SET @stmt := CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_ddl);
    PREPARE ps FROM @stmt;
    EXECUTE ps;
    DEALLOCATE PREPARE ps;
  END IF;
END$$

CREATE PROCEDURE jarvis_erp_goofish_add_index(
  IN p_table   VARCHAR(64),
  IN p_index   VARCHAR(64),
  IN p_columns VARCHAR(200)
)
BEGIN
  DECLARE idx_exists INT DEFAULT 0;
  SELECT COUNT(*) INTO idx_exists
    FROM information_schema.statistics
   WHERE TABLE_SCHEMA = @schema
     AND TABLE_NAME = p_table
     AND INDEX_NAME = p_index;
  IF idx_exists = 0 THEN
    SET @stmt := CONCAT('ALTER TABLE `', p_table, '` ADD INDEX `', p_index, '` (', p_columns, ')');
    PREPARE ps FROM @stmt;
    EXECUTE ps;
    DEALLOCATE PREPARE ps;
  END IF;
END$$

DELIMITER ;

-- ----------------------------------------------------------------------------- 
-- 3) erp_goofish_order：补齐缺列（与当前 Java 实体 / erp_goofish_init.sql 一致）
-- ----------------------------------------------------------------------------- 
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'seller_id', 'bigint(20) NULL COMMENT ''商家ID''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'user_name', 'varchar(128) NULL COMMENT ''闲鱼会员名''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'order_type', 'int(11) NULL COMMENT ''订单类型''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'order_status', 'int(11) NULL COMMENT ''订单状态(推送/列表)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'refund_status', 'int(11) NULL COMMENT ''退款状态''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'modify_time', 'bigint(20) NULL COMMENT ''订单更新时间(秒)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'product_id', 'bigint(20) NULL COMMENT ''管家商品ID''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'item_id', 'bigint(20) NULL COMMENT ''闲鱼商品ID''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'goods_title', 'varchar(512) NULL COMMENT ''商品标题(详情 goods.title)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'goods_image_url', 'varchar(1024) NULL COMMENT ''商品主图 URL(goods.images 首图)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'buyer_nick', 'varchar(256) NULL COMMENT ''买家昵称(详情 buyer_nick)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'pay_amount', 'bigint(20) NULL COMMENT ''实付金额(分) pay_amount''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'detail_waybill_no', 'varchar(128) NULL COMMENT ''闲管家详情回传运单号 waybill_no''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'detail_express_code', 'varchar(64) NULL COMMENT ''详情快递编码 express_code''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'detail_express_name', 'varchar(128) NULL COMMENT ''详情快递名称 express_name''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'receiver_name', 'varchar(128) NULL COMMENT ''收货人(详情有则落库)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'receiver_mobile', 'varchar(64) NULL COMMENT ''收货手机''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'receiver_address', 'varchar(1000) NULL COMMENT ''收货详细地址(address)''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'receiver_region', 'varchar(256) NULL COMMENT ''省市区街道等拼接展示''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'recv_prov_name', 'varchar(64) NULL COMMENT ''prov_name''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'recv_city_name', 'varchar(64) NULL COMMENT ''city_name''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'recv_area_name', 'varchar(64) NULL COMMENT ''area_name''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'recv_town_name', 'varchar(128) NULL COMMENT ''town_name''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'detail_json', 'longtext NULL COMMENT ''订单详情接口全量 JSON''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'last_notify_json', 'longtext NULL COMMENT ''最近一次推送原文 JSON''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'jd_order_id', 'bigint(20) NULL COMMENT ''关联 jd_order.id（第三方单号=闲鱼单号）''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'local_waybill_no', 'varchar(128) NULL COMMENT ''本地物流扫描得到的运单号''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'ship_status', 'tinyint(4) NOT NULL DEFAULT 0 COMMENT ''0未发货 1已调用发货成功 2发货失败''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'ship_error', 'varchar(500) NULL COMMENT ''发货失败原因''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'ship_time', 'datetime NULL COMMENT ''发货调用成功时间''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'ship_express_code', 'varchar(64) NULL COMMENT ''实际发货使用的快递编码''');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'create_time', 'datetime NULL');
CALL jarvis_erp_goofish_add_column('erp_goofish_order', 'update_time', 'datetime NULL');

-- ----------------------------------------------------------------------------- 
-- 4) 索引（手工建表可能缺）
-- ----------------------------------------------------------------------------- 
CALL jarvis_erp_goofish_add_index('erp_goofish_order', 'idx_jd_order', '`jd_order_id`');
CALL jarvis_erp_goofish_add_index('erp_goofish_order', 'idx_order_status', '`order_status`');
CALL jarvis_erp_goofish_add_index('erp_goofish_order', 'idx_modify_time', '`modify_time`');

-- ----------------------------------------------------------------------------- 
-- 5) 唯一键 uk_app_order
--     若已存在同名约束则跳过；若 (app_key,order_no) 有重复行会报错，需先清洗数据。
--     若已通过其它名称建了 (app_key,order_no) 唯一索引，请勿重复执行本节（可能报 Duplicate key）。
-- ----------------------------------------------------------------------------- 
SET @uk := (
  SELECT COUNT(*) FROM information_schema.table_constraints
   WHERE table_schema = @schema AND table_name = 'erp_goofish_order'
     AND constraint_name = 'uk_app_order' AND constraint_type = 'UNIQUE'
);
SET @sql_uk := IF(@uk = 0,
  'ALTER TABLE erp_goofish_order ADD UNIQUE KEY uk_app_order (app_key, order_no)',
  'SELECT ''uk_app_order 已存在，跳过'' AS note');
PREPARE puk FROM @sql_uk;
EXECUTE puk;
DEALLOCATE PREPARE puk;

-- ----------------------------------------------------------------------------- 
-- 5.5) 订单变更事件日志表
-- -----------------------------------------------------------------------------
CREATE TABLE IF NOT EXISTS erp_goofish_order_event_log (
  id           bigint(20)   NOT NULL AUTO_INCREMENT COMMENT '主键',
  order_id     bigint(20)   NOT NULL COMMENT 'erp_goofish_order.id',
  app_key      varchar(64)           DEFAULT NULL,
  order_no     varchar(64)  NOT NULL,
  event_type   varchar(32)  NOT NULL COMMENT 'ORDER_SYNC/LOGISTICS_SYNC/SHIP',
  source       varchar(64)           NULL COMMENT 'NOTIFY/LIST/DETAIL_REFRESH 等',
  message      varchar(1024) NOT NULL,
  create_time  datetime              DEFAULT NULL,
  PRIMARY KEY (id),
  KEY idx_goofish_evt_order (order_id),
  KEY idx_goofish_evt_time (create_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='闲管家订单状态/物流/发货变更日志';

-- ----------------------------------------------------------------------------- 
-- 6) 清理存储过程
-- ----------------------------------------------------------------------------- 
DROP PROCEDURE IF EXISTS jarvis_erp_goofish_add_column;
DROP PROCEDURE IF EXISTS jarvis_erp_goofish_add_index;

SELECT 'erp_goofish_upgrade.sql 执行结束' AS message;
