-- LMS 日计划、调度策略、操作日志及基础数据初始化。
CREATE TABLE IF NOT EXISTS `lms_daily_plan` (
    `daily_plan_id` bigint NOT NULL COMMENT '日计划ID',
    `plan_code` varchar(32) NOT NULL COMMENT '日计划编码',
    `source_type` tinyint NOT NULL COMMENT '来源类型：1 ERP，2 人工',
    `erp_order_code` varchar(64) DEFAULT NULL COMMENT 'ERP订单号',
    `manual_order_code` varchar(64) DEFAULT NULL COMMENT '人工订单号',
    `plan_date` date NOT NULL COMMENT '计划日期',
    `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 '物料规格',
    `plan_qty` int NOT NULL DEFAULT 0 COMMENT '计划数量',
    `append_qty` int NOT NULL DEFAULT 0 COMMENT '追加数量',
    `stocked_qty` int NOT NULL DEFAULT 0 COMMENT '已备货数量',
    `sleeved_qty` int NOT NULL DEFAULT 0 COMMENT '已套管数量',
    `packing_info` text COMMENT '包装信息',
    `sort_seq` int NOT NULL COMMENT '排序序号',
    `weight` int NOT NULL DEFAULT 1 COMMENT '调度权重',
    `order_status` tinyint NOT NULL DEFAULT 0 COMMENT '订单状态：0未开始，1进行中，2已结束，3已取消',
    `stocking_status` tinyint NOT NULL DEFAULT 0 COMMENT '备货状态：0未开始，1进行中，2已完成，3已取消',
    `sleeving_status` tinyint NOT NULL DEFAULT 0 COMMENT '套管状态：0未开始，1进行中，2已完成，3已取消',
    `previous_order_status` tinyint DEFAULT NULL COMMENT '前一订单状态',
    `previous_stocking_status` tinyint DEFAULT NULL COMMENT '前一备货状态',
    `previous_sleeving_status` tinyint DEFAULT NULL COMMENT '前一套管状态',
    `order_start_time` datetime DEFAULT NULL COMMENT '订单开始时间',
    `order_end_time` datetime DEFAULT NULL COMMENT '订单结束时间',
    `stocking_start_time` datetime DEFAULT NULL COMMENT '备货开始时间',
    `stocking_complete_time` datetime DEFAULT NULL COMMENT '备货完成时间',
    `sleeving_start_time` datetime DEFAULT NULL COMMENT '套管开始时间',
    `sleeving_complete_time` datetime 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 (`daily_plan_id`),
    UNIQUE KEY `uk_plan_code_tenant` (`plan_code`, `tenant_id`),
    UNIQUE KEY `uk_erp_order_code_tenant` (`erp_order_code`, `tenant_id`),
    KEY `idx_stocking_candidate` (`tenant_id`, `deleted`, `order_status`, `stocking_status`, `sort_seq`, `daily_plan_id`),
    KEY `idx_sleeving_candidate` (`tenant_id`, `deleted`, `order_status`, `sleeving_status`, `sort_seq`, `daily_plan_id`)
) COMMENT='LMS日计划';

CREATE TABLE IF NOT EXISTS `lms_daily_plan_strategy` (
    `strategy_id` bigint NOT NULL COMMENT '策略ID',
    `strategy_type` tinyint NOT NULL COMMENT '策略类型：1备货，2套管',
    `strategy_mode` tinyint NOT NULL DEFAULT 1 COMMENT '策略模式：1顺序，2权重',
    `cursor_daily_plan_id` bigint DEFAULT NULL COMMENT '当前游标日计划ID',
    `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 (`strategy_id`),
    UNIQUE KEY `uk_strategy_type_tenant` (`strategy_type`, `tenant_id`)
) COMMENT='LMS日计划调度策略';

CREATE TABLE IF NOT EXISTS `lms_daily_plan_claim` (
    `claim_id` bigint NOT NULL COMMENT '领取ID',
    `claim_token` varchar(64) NOT NULL COMMENT '对外领取标识',
    `daily_plan_id` bigint NOT NULL COMMENT '日计划ID',
    `strategy_type` tinyint NOT NULL COMMENT '作业类型：1备货，2套管',
    `claimed_qty` int NOT NULL COMMENT '本次预占数量',
    `plan_version` int NOT NULL COMMENT '领取时日计划版本号（仅审计，不作为确认并发边界）',
    `progress_qty` int NOT NULL COMMENT '领取时对应作业已完成数量',
    `version` int NOT NULL DEFAULT 0 COMMENT '领取乐观锁版本号',
    `claim_status` tinyint NOT NULL DEFAULT 0 COMMENT '领取状态：0执行中，1已确认，2已释放，3已过期',
    `active_flag` tinyint DEFAULT 1 COMMENT '有效领取唯一标记，终态置空',
    `expire_time` datetime NOT NULL COMMENT '租约过期时间',
    `confirmed_time` datetime DEFAULT NULL COMMENT '确认时间',
    `operator` varchar(64) NOT NULL 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 (`claim_id`),
    UNIQUE KEY `uk_claim_token_tenant` (`claim_token`, `tenant_id`),
    UNIQUE KEY `uk_active_plan_type_tenant` (`daily_plan_id`, `strategy_type`, `active_flag`, `tenant_id`),
    KEY `idx_claim_expire` (`tenant_id`, `claim_status`, `expire_time`)
) COMMENT='LMS日计划调度领取';

CREATE TABLE IF NOT EXISTS `lms_daily_plan_operation_log` (
    `operation_log_id` bigint NOT NULL COMMENT '操作日志ID',
    `daily_plan_id` bigint DEFAULT NULL COMMENT '日计划ID',
    `operation_target` varchar(32) NOT NULL COMMENT '操作对象',
    `operation_type` varchar(32) NOT NULL COMMENT '操作类型',
    `before_value` text COMMENT '操作前值',
    `after_value` text COMMENT '操作后值',
    `change_qty` int DEFAULT NULL COMMENT '变更数量',
    `operation_reason` varchar(500) DEFAULT NULL COMMENT '操作原因',
    `operator` varchar(64) NOT NULL COMMENT '操作人',
    `operation_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
    `deleted` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
    `tenant_id` bigint NOT NULL DEFAULT 0 COMMENT '租户编号',
    PRIMARY KEY (`operation_log_id`)
) COMMENT='LMS日计划操作日志';

-- 兼容已执行过旧版脚本的数据库，幂等补充候选组合索引。
SET @lms_claim_progress_upgrade = NOT EXISTS(
    SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
    AND table_name = 'lms_daily_plan_claim' AND column_name = 'progress_qty');
SET @lms_daily_plan_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan' AND index_name = 'idx_stocking_candidate'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan ADD INDEX idx_stocking_candidate (tenant_id, deleted, order_status, stocking_status, sort_seq, daily_plan_id)');
PREPARE lms_daily_plan_stmt FROM @lms_daily_plan_ddl;
EXECUTE lms_daily_plan_stmt;
DEALLOCATE PREPARE lms_daily_plan_stmt;
SET @lms_daily_plan_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan_claim' AND column_name = 'progress_qty'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan_claim ADD COLUMN progress_qty INT NOT NULL DEFAULT 0 COMMENT ''领取时对应作业已完成数量'' AFTER plan_version');
PREPARE lms_daily_plan_stmt FROM @lms_daily_plan_ddl;
EXECUTE lms_daily_plan_stmt;
DEALLOCATE PREPARE lms_daily_plan_stmt;
-- 旧版活跃 Claim 没有可靠的领取时进度快照，首次升级时统一释放，避免按默认 0 错误确认。
SET @lms_daily_plan_ddl = IF(
    @lms_claim_progress_upgrade,
    'UPDATE lms_daily_plan_claim SET claim_status = 2, active_flag = NULL, updater = ''SQL_UPGRADE'' WHERE claim_status = 0 AND active_flag = 1 AND deleted = b''0''',
    'SELECT 1');
PREPARE lms_daily_plan_stmt FROM @lms_daily_plan_ddl;
EXECUTE lms_daily_plan_stmt;
DEALLOCATE PREPARE lms_daily_plan_stmt;
SET @lms_daily_plan_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan_claim' AND column_name = 'version'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan_claim ADD COLUMN version INT NOT NULL DEFAULT 0 COMMENT ''领取乐观锁版本号'' AFTER progress_qty');
PREPARE lms_daily_plan_stmt FROM @lms_daily_plan_ddl;
EXECUTE lms_daily_plan_stmt;
DEALLOCATE PREPARE lms_daily_plan_stmt;
SET @lms_daily_plan_ddl = IF(
    EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema = DATABASE()
            AND table_name = 'lms_daily_plan' AND index_name = 'idx_sleeving_candidate'),
    'SELECT 1',
    'ALTER TABLE lms_daily_plan ADD INDEX idx_sleeving_candidate (tenant_id, deleted, order_status, sleeving_status, sort_seq, daily_plan_id)');
PREPARE lms_daily_plan_stmt FROM @lms_daily_plan_ddl;
EXECUTE lms_daily_plan_stmt;
DEALLOCATE PREPARE lms_daily_plan_stmt;

-- 2093号段用于 LMS 日计划固定基础数据；编码格式：DP + yyyyMMdd + 4位日流水。
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 2093000000000000001, 'LMS日计划编码', 'LMS_DAILY_PLAN_CODE',
       JSON_ARRAY(
           JSON_OBJECT('type', 'PREFIX', 'value', 'DP', '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', 9999, 'paddingLen', 4, 'paddingChar', '0')
       ), '', 0, 14, 'segment', 0, 'LMS日计划编码，格式DPyyyyMMdd0001', '1', NOW(), '1', NOW(), 0
WHERE NOT EXISTS (SELECT 1 FROM base_code_rule WHERE rule_code = 'LMS_DAILY_PLAN_CODE');

-- 字典类型。
INSERT INTO system_dict_type (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2093000000000000010, 'LMS日计划来源类型', 'lms_daily_plan_source_type', 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_daily_plan_source_type' AND deleted = b'0');
INSERT INTO system_dict_type (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2093000000000000020, 'LMS日计划订单状态', 'lms_daily_plan_order_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_daily_plan_order_status' AND deleted = b'0');
INSERT INTO system_dict_type (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2093000000000000030, 'LMS日计划作业状态', 'lms_daily_plan_work_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_daily_plan_work_status' AND deleted = b'0');
INSERT INTO system_dict_type (id, name, type, status, remark, creator, create_time, updater, update_time, deleted, deleted_time)
SELECT 2093000000000000040, 'LMS日计划策略模式', 'lms_daily_plan_strategy_mode', 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_daily_plan_strategy_mode' 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 2093000000000000011, 1, 'ERP', '1', 'lms_daily_plan_source_type', 0, 'primary', '', 'ERP订单', '1', NOW(), '1', NOW(), b'0'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data WHERE dict_type='lms_daily_plan_source_type' AND value='1' 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 2093000000000000012, 2, '人工', '2', 'lms_daily_plan_source_type', 0, 'success', '', '人工订单', '1', NOW(), '1', NOW(), b'0'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data WHERE dict_type='lms_daily_plan_source_type' AND value='2' 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 2093000000000000021 + seq.n, seq.n + 1, seq.label, CAST(seq.n AS CHAR), 'lms_daily_plan_order_status', 0, seq.color_type, '', CONCAT('订单', seq.label), '1', NOW(), '1', NOW(), b'0'
FROM (SELECT 0 n, '未开始' label, 'info' color_type UNION ALL SELECT 1, '进行中', 'primary' UNION ALL SELECT 2, '已结束', 'success' UNION ALL SELECT 3, '已取消', 'danger') seq
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data d WHERE d.dict_type='lms_daily_plan_order_status' AND d.value=CONVERT(seq.n, CHAR) COLLATE utf8mb4_unicode_ci AND d.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 2093000000000000031 + seq.n, seq.n + 1, seq.label, CAST(seq.n AS CHAR), 'lms_daily_plan_work_status', 0, seq.color_type, '', CONCAT('作业', seq.label), '1', NOW(), '1', NOW(), b'0'
FROM (SELECT 0 n, '未开始' label, 'info' color_type UNION ALL SELECT 1, '进行中', 'primary' UNION ALL SELECT 2, '已完成', 'success' UNION ALL SELECT 3, '已取消', 'danger') seq
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data d WHERE d.dict_type='lms_daily_plan_work_status' AND d.value=CONVERT(seq.n, CHAR) COLLATE utf8mb4_unicode_ci AND d.deleted=b'0');
UPDATE system_dict_data
SET label = '已完成', remark = '作业已完成', updater = '1', update_time = NOW()
WHERE dict_type = 'lms_daily_plan_work_status' AND value = '2' AND deleted = b'0'
  AND (label <> '已完成' OR remark <> '作业已完成');
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 2093000000000000041, 1, '顺序模式', '1', 'lms_daily_plan_strategy_mode', 0, 'primary', '', '按计划顺序调度', '1', NOW(), '1', NOW(), b'0'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data WHERE dict_type='lms_daily_plan_strategy_mode' AND value='1' 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 2093000000000000042, 2, '权重轮转', '2', 'lms_daily_plan_strategy_mode', 0, 'warning', '', '按权重轮转调度', '1', NOW(), '1', NOW(), b'0'
WHERE NOT EXISTS (SELECT 1 FROM system_dict_data WHERE dict_type='lms_daily_plan_strategy_mode' AND value='2' AND deleted=b'0');

-- 为全部有效租户分别初始化备货、套管顺序策略。
INSERT INTO lms_daily_plan_strategy
    (strategy_id, strategy_type, strategy_mode, cursor_daily_plan_id, version, creator, create_time, updater, update_time, deleted, tenant_id)
SELECT CAST(CONV(SUBSTRING(SHA2(CONCAT('lms_daily_plan_strategy:', tenant.id, ':', strategy.strategy_type), 256), 1, 15), 16, 10) AS UNSIGNED),
       strategy.strategy_type, 1, NULL, 0, '1', NOW(), '1', NOW(), b'0', tenant.id
FROM system_tenant tenant
CROSS JOIN (SELECT 1 strategy_type UNION ALL SELECT 2) strategy
WHERE tenant.deleted = b'0'
  AND tenant.status = 0
  AND NOT EXISTS (
      SELECT 1 FROM lms_daily_plan_strategy existing
      WHERE existing.tenant_id = tenant.id AND existing.strategy_type = strategy.strategy_type
  );
