CREATE TABLE IF NOT EXISTS pp_production_batch_ledger (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '生产台账ID',
  material_lot_id BIGINT NOT NULL COMMENT '材料库存批次ID',
  material_lot_no VARCHAR(128) NOT NULL COMMENT '材料库存批次号',
  material_item_id BIGINT NOT NULL COMMENT '原材料物料ID',
  product_item_id BIGINT NOT NULL COMMENT '产品物料ID',
  status VARCHAR(32) NOT NULL DEFAULT '在生产' COMMENT '状态：在生产/锁单',
  miniapp_selectable TINYINT(1) NOT NULL DEFAULT 1 COMMENT '小程序是否可选',
  total_issued_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '累计领料重量',
  outside_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '库外未闭环重量',
  finished_inbound_qty DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '累计成品入库数量',
  surplus_inbound_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '累计余料入库重量',
  scrap_inbound_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '累计废料入库重量',
  writeoff_weight_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '结单核销重量',
  first_issue_time DATETIME NULL COMMENT '首次生产出库时间',
  last_issue_time DATETIME NULL COMMENT '最近生产出库时间',
  locked_at DATETIME NULL COMMENT '最近锁单时间',
  reopened_at DATETIME NULL COMMENT '最近重新开工时间',
  lock_count INT NOT NULL DEFAULT 0 COMMENT '锁单次数',
  remark VARCHAR(500) NULL COMMENT '备注',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  UNIQUE KEY uk_production_batch_ledger_lot_product (material_lot_id, product_item_id),
  KEY idx_production_batch_ledger_status (status),
  KEY idx_production_batch_ledger_lot_no (material_lot_no),
  KEY idx_production_batch_ledger_material (material_item_id),
  KEY idx_production_batch_ledger_product (product_item_id),
  CONSTRAINT fk_production_batch_ledger_lot FOREIGN KEY (material_lot_id) REFERENCES wh_stock_lot(id),
  CONSTRAINT fk_production_batch_ledger_material FOREIGN KEY (material_item_id) REFERENCES md_item(id),
  CONSTRAINT fk_production_batch_ledger_product FOREIGN KEY (product_item_id) REFERENCES md_item(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='生产台账：材料库存批次号+产品';

CREATE TABLE IF NOT EXISTS pp_production_batch_ledger_txn (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '生产台账流水ID',
  production_ledger_id BIGINT NOT NULL COMMENT '生产台账ID',
  txn_type VARCHAR(32) NOT NULL COMMENT '流水类型：生产出库/成品入库/生产余料入库/生产废料入库/该批材料结单/重新开工/结单核销',
  qty_delta DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '数量变化',
  weight_delta_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '重量变化kg',
  outside_weight_after_kg DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '变更后库外未闭环重量',
  source_doc_type VARCHAR(64) NULL COMMENT '来源单据类型',
  source_doc_id BIGINT NULL COMMENT '来源单据ID',
  source_line_id BIGINT NULL COMMENT '来源明细ID',
  biz_time DATETIME NOT NULL COMMENT '业务时间',
  operator_user_id BIGINT NULL COMMENT '操作人用户ID',
  remark VARCHAR(500) NULL COMMENT '备注',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  KEY idx_production_batch_ledger_txn_ledger (production_ledger_id),
  KEY idx_production_batch_ledger_txn_type (txn_type),
  KEY idx_production_batch_ledger_txn_source (source_doc_type, source_doc_id, source_line_id),
  CONSTRAINT fk_production_batch_ledger_txn_ledger FOREIGN KEY (production_ledger_id) REFERENCES pp_production_batch_ledger(id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='生产台账流水';

SET @has_operation_report_ledger_id := (
  SELECT COUNT(*)
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'pp_operation_report'
    AND COLUMN_NAME = 'production_ledger_id'
);

SET @alter_operation_report_ledger_id := IF(
  @has_operation_report_ledger_id = 0,
  'ALTER TABLE pp_operation_report ADD COLUMN production_ledger_id BIGINT NULL COMMENT ''生产台账ID'' AFTER work_order_operation_id',
  'SELECT 1'
);

PREPARE stmt FROM @alter_operation_report_ledger_id;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

ALTER TABLE pp_operation_report
  MODIFY COLUMN work_order_id BIGINT NULL COMMENT '生产工单ID（旧工单/返工使用，正常生产可为空）',
  MODIFY COLUMN work_order_operation_id BIGINT NULL COMMENT '生产工序ID（旧工单/返工使用，正常生产可为空）';

CREATE TABLE IF NOT EXISTS sys_system_config (
  id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '主键ID',
  config_code VARCHAR(100) NOT NULL COMMENT '配置编码',
  config_name VARCHAR(100) NOT NULL COMMENT '配置名称',
  config_value VARCHAR(500) NOT NULL COMMENT '配置值',
  remark VARCHAR(500) NULL COMMENT '备注',
  status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT '状态：ACTIVE/INACTIVE',
  created_by BIGINT NULL COMMENT '创建用户ID',
  updated_by BIGINT NULL COMMENT '更新用户ID',
  created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  UNIQUE KEY uk_system_config_code (config_code),
  KEY idx_system_config_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='系统配置';

INSERT INTO sys_system_config (config_code, config_name, config_value, remark, status)
SELECT
  'SMART_OPERATION_REPORT_ENABLED',
  '对接智能报工小程序',
  '开启',
  '开启后显示工序报工并按小程序报工数据计算生产进度；关闭后按ERP入库数据反推生产进度',
  'ACTIVE'
FROM DUAL
WHERE NOT EXISTS (
  SELECT 1 FROM sys_system_config WHERE config_code = 'SMART_OPERATION_REPORT_ENABLED'
);
