-- 创建标签模板表
CREATE TABLE IF NOT EXISTS `tag_templates` (
  `Id` INT NOT NULL AUTO_INCREMENT,
  `TagType` VARCHAR(50) NOT NULL,
  `Name` VARCHAR(100) NOT NULL,
  `TemplateConfig` TEXT NOT NULL,
  `TriggerRule` TEXT NOT NULL,
  `IsActive` TINYINT(1) NOT NULL DEFAULT '1',
  `CreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`),
  UNIQUE KEY `uk_tag_type` (`TagType`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 创建标签实例表
CREATE TABLE IF NOT EXISTS `tag_instances` (
  `Id` BIGINT NOT NULL AUTO_INCREMENT,
  `TagType` VARCHAR(50) NOT NULL,
  `TemplateId` INT NOT NULL,
  `NeutralWaybillNumber` VARCHAR(100) NOT NULL,
  `CustomerId` INT NOT NULL,
  `Status` VARCHAR(20) NOT NULL DEFAULT 'ACTIVE',
  `TriggerTime` DATETIME NOT NULL,
  `CreatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`Id`),
  KEY `idx_tag_type` (`TagType`),
  KEY `idx_neutral_waybill` (`NeutralWaybillNumber`),
  KEY `idx_customer_id` (`CustomerId`),
  CONSTRAINT `fk_tag_template` FOREIGN KEY (`TemplateId`) REFERENCES `tag_templates` (`Id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- 插入默认的STOP标签模板
INSERT IGNORE INTO `tag_templates` (`TagType`, `Name`, `TemplateConfig`, `TriggerRule`, `IsActive`) VALUES
('STOP', 'STOP标签模板', '{"content": "STOP", "fields": ["neutralWaybillNumber", "customerId", "triggerTime"]}', '{"type": "time_based", "condition": "elapsed_time > 3600"}', 1);
