-- LMS 管芯实例、托盘绑定、字典及编码规则初始化。
CREATE TABLE IF NOT EXISTS `lms_core_tube` (
    `core_tube_id` bigint NOT NULL COMMENT '管芯实例ID',
    `core_tube_code` varchar(64) NOT NULL COMMENT '虚拟管芯编号',
    `bind_request_no` varchar(64) NOT NULL COMMENT 'PDA绑定请求号',
    `material_id` bigint NOT NULL COMMENT '管芯物料ID',
    `material_code` varchar(64) NOT NULL COMMENT '管芯物料编码',
    `material_name` varchar(128) NOT NULL COMMENT '管芯物料名称',
    `material_spec` varchar(128) DEFAULT NULL COMMENT '管芯规格',
    `core_weight` decimal(12,3) NOT NULL COMMENT '管芯重量',
    `weight_unit` varchar(16) NOT NULL DEFAULT 'kg' COMMENT '重量单位',
    `stage` tinyint NOT NULL COMMENT '生命周期阶段',
    `status` tinyint NOT NULL COMMENT '占用状态',
    `vehicle_code` varchar(32) DEFAULT NULL COMMENT '当前管芯托盘号',
    `row_num` tinyint DEFAULT NULL COMMENT '托盘行号',
    `col_num` tinyint DEFAULT NULL COMMENT '托盘列号',
    `active_slot` tinyint DEFAULT 1 COMMENT '有效托盘格位唯一标记，解绑后置空',
    `current_location_type` tinyint NOT NULL COMMENT '当前位置类型',
    `current_location_id` bigint DEFAULT NULL COMMENT '当前位置记录ID',
    `current_location_code` varchar(64) DEFAULT NULL COMMENT '当前位置编码',
    `source_daily_plan_id` bigint DEFAULT NULL COMMENT '来源日计划ID',
    `reserved_daily_plan_id` bigint DEFAULT NULL COMMENT '当前预占日计划ID',
    `reserved_claim_token` varchar(64) DEFAULT NULL COMMENT '当前调度领取标识',
    `reserved_task_id` bigint DEFAULT NULL COMMENT '当前现场任务ID',
    `reserve_expire_time` datetime(6) DEFAULT NULL COMMENT '预占过期时间',
    `version` int NOT NULL DEFAULT 0 COMMENT '乐观锁版本号',
    `creator` varchar(64) DEFAULT '' COMMENT '创建者',
    `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    `updater` varchar(64) DEFAULT '' COMMENT '更新者',
    `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
    `deleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
    `tenant_id` bigint NOT NULL DEFAULT 0 COMMENT '租户编号',
    PRIMARY KEY (`core_tube_id`),
    UNIQUE KEY `uk_core_tube_code_tenant` (`core_tube_code`, `tenant_id`),
    UNIQUE KEY `uk_core_tube_bind_request_slot` (`tenant_id`, `bind_request_no`, `row_num`, `col_num`),
    UNIQUE KEY `uk_core_tube_active_slot` (`tenant_id`, `vehicle_code`, `row_num`, `col_num`, `active_slot`),
    KEY `idx_core_tube_schedule` (`tenant_id`, `material_id`, `stage`, `status`, `deleted`),
    KEY `idx_core_tube_reserved_task` (`tenant_id`, `reserved_task_id`, `deleted`)
) COMMENT='LMS管芯实例主表';

-- 兼容已有托盘明细表，幂等补充管芯关联字段和索引。
SET @lms_core_tube_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_base_papervehicle' AND column_name = 'core_tube_id'),
    'SELECT 1',
    'ALTER TABLE lms_base_papervehicle ADD COLUMN core_tube_id BIGINT DEFAULT NULL COMMENT ''管芯实例ID'' AFTER ivt_id');
PREPARE lms_core_tube_stmt FROM @lms_core_tube_ddl;
EXECUTE lms_core_tube_stmt;
DEALLOCATE PREPARE lms_core_tube_stmt;

SET @lms_core_tube_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan_claim' AND column_name = 'task_created'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan_claim ADD COLUMN task_created BIT(1) NOT NULL DEFAULT b''0'' COMMENT ''是否已创建现场任务'' AFTER active_flag');
PREPARE lms_core_tube_stmt FROM @lms_core_tube_ddl;
EXECUTE lms_core_tube_stmt;
DEALLOCATE PREPARE lms_core_tube_stmt;

SET @lms_core_tube_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_base_papervehicle' AND column_name = 'core_tube_code'),
    'SELECT 1',
    'ALTER TABLE lms_base_papervehicle ADD COLUMN core_tube_code VARCHAR(64) DEFAULT NULL COMMENT ''虚拟管芯编号'' AFTER core_tube_id');
PREPARE lms_core_tube_stmt FROM @lms_core_tube_ddl;
EXECUTE lms_core_tube_stmt;
DEALLOCATE PREPARE lms_core_tube_stmt;

SET @lms_core_tube_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE()
            AND table_name = 'lms_base_papervehicle' AND index_name = 'idx_papervehicle_vehicle_slot'),
    'SELECT 1',
    'ALTER TABLE lms_base_papervehicle ADD INDEX idx_papervehicle_vehicle_slot (vehicle_code, row_num, col_num)');
PREPARE lms_core_tube_stmt FROM @lms_core_tube_ddl;
EXECUTE lms_core_tube_stmt;
DEALLOCATE PREPARE lms_core_tube_stmt;

SET @lms_core_tube_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan_strategy' AND column_name = 'cursor_executed_qty'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan_strategy ADD COLUMN cursor_executed_qty INT NOT NULL DEFAULT 0 COMMENT ''当前权重轮转已执行数量'' AFTER cursor_daily_plan_id');
PREPARE lms_core_tube_stmt FROM @lms_core_tube_ddl;
EXECUTE lms_core_tube_stmt;
DEALLOCATE PREPARE lms_core_tube_stmt;

-- 管芯编码规则：GX + yyyyMMdd + 6位日流水。
INSERT INTO base_code_rule
    (id, rule_name, rule_code, segment_config, code_separator, letter_case, total_length,
     seq_strategy, status, remark, creator, create_time, updater, update_time, deleted)
SELECT 2094000000000000001, 'LMS管芯编码', 'CORE_TUBE_CODE',
       JSON_ARRAY(
           JSON_OBJECT('type', 'PREFIX', 'value', 'GX', 'format', NULL, 'resetBy', NULL, 'startAt', NULL, 'maxValue', NULL, 'paddingLen', NULL, 'paddingChar', NULL),
           JSON_OBJECT('type', 'DATE', 'value', NULL, 'format', 'yyyyMMdd', 'resetBy', NULL, 'startAt', NULL, 'maxValue', NULL, 'paddingLen', NULL, 'paddingChar', NULL),
           JSON_OBJECT('type', 'SEQUENCE', 'value', NULL, 'format', NULL, 'resetBy', 'DAY', 'startAt', 1, 'maxValue', 999999, 'paddingLen', 6, 'paddingChar', '0')
       ), '', 0, 16, 'segment', 0, 'LMS管芯编码，格式GXyyyyMMdd000001', '1', NOW(), '1', NOW(), 0
WHERE NOT EXISTS (SELECT 1 FROM base_code_rule WHERE rule_code = 'CORE_TUBE_CODE');

-- 管芯生命周期和占用状态字典。
INSERT INTO system_dict_type
    (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2094000000000000010, 'LMS管芯生命周期阶段', 'lms_core_tube_stage', 0,
       'LMS管芯生命周期阶段', '1', NOW(), '1', NOW(), b'0', '1970-01-01 00:00:00'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_type WHERE type = 'lms_core_tube_stage' AND deleted = b'0');

INSERT INTO system_dict_type
    (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2094000000000000020, 'LMS管芯占用状态', 'lms_core_tube_status', 0,
       'LMS管芯占用状态', '1', NOW(), '1', NOW(), b'0', '1970-01-01 00:00:00'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_type WHERE type = 'lms_core_tube_status' AND deleted = b'0');

INSERT INTO system_dict_data
    (id, sort, label, value, dict_type, status, color_type, css_class, remark,
     creator, create_time, updater, update_time, deleted)
SELECT 2094000000000000010 + stage.code, stage.code, stage.label, CAST(stage.code AS CHAR),
       'lms_core_tube_stage', 0, stage.color_type, '', CONCAT('管芯', stage.label),
       '1', NOW(), '1', NOW(), b'0'
FROM (
    SELECT 1 code, '备货区' label, 'info' color_type UNION ALL
    SELECT 2, '备货抓取中', 'warning' UNION ALL
    SELECT 3, '管芯库', 'success' UNION ALL
    SELECT 4, '管芯出库中', 'warning' UNION ALL
    SELECT 5, '套管中', 'primary' UNION ALL
    SELECT 6, '套管缓存位', 'success' UNION ALL
    SELECT 7, '已消耗', 'info' UNION ALL
    SELECT 8, '异常', 'danger'
) stage
WHERE NOT EXISTS (
    SELECT 1 FROM system_dict_data existing
    WHERE existing.dict_type = 'lms_core_tube_stage'
      AND existing.value = CONVERT(stage.code, CHAR) COLLATE utf8mb4_unicode_ci
      AND existing.deleted = b'0');

INSERT INTO system_dict_data
    (id, sort, label, value, dict_type, status, color_type, css_class, remark,
     creator, create_time, updater, update_time, deleted)
SELECT 2094000000000000020 + state.code, state.code, state.label, CAST(state.code AS CHAR),
       'lms_core_tube_status', 0, state.color_type, '', CONCAT('管芯', state.label),
       '1', NOW(), '1', NOW(), b'0'
FROM (
    SELECT 1 code, '可用' label, 'success' color_type UNION ALL
    SELECT 2, '已预占', 'warning' UNION ALL
    SELECT 3, '作业中', 'primary' UNION ALL
    SELECT 4, '已使用', 'info' UNION ALL
    SELECT 5, '冻结', 'warning' UNION ALL
    SELECT 6, '异常', 'danger'
) state
WHERE NOT EXISTS (
    SELECT 1 FROM system_dict_data existing
    WHERE existing.dict_type = 'lms_core_tube_status'
      AND existing.value = CONVERT(state.code, CHAR) COLLATE utf8mb4_unicode_ci
      AND existing.deleted = b'0');
