-- ========================================
-- 定氮仪质检模块 - 重新设计数据库
-- 设计日期: 2025-09-19
-- 业务逻辑: 一对一关系，绑定后隐藏
-- ========================================

USE yjh_mes_plsw;

-- ========================================
-- 1. 定氮仪质检主表设计
-- ========================================
DROP TABLE IF EXISTS `qc_kna_info`;
CREATE TABLE `qc_kna_info` (
  -- 主键和基本信息
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `inspection_no` varchar(50) NOT NULL COMMENT '质检单号',
  
  -- TCP原始数据相关 (接收时直接存储)
  `tcp_received_time` datetime NOT NULL COMMENT 'TCP数据接收时间',
  `tcp_raw_data` text NOT NULL COMMENT 'TCP完整原始数据JSON',
  `tcp_source_ip` varchar(50) DEFAULT NULL COMMENT 'TCP数据来源IP',
  
  -- 样品基本信息 (从TCP解析)
  `sample_name` varchar(100) DEFAULT NULL COMMENT '样品名称(sample_Name)',
  `sample_id` varchar(50) DEFAULT NULL COMMENT '样品ID(sample_id)', 
  `sample_value` decimal(10, 6) DEFAULT NULL COMMENT '样品重量g(sample_Value)',
  `sample_unit` varchar(20) DEFAULT 'g' COMMENT '样品单位(sample_Unit)',
  `analysis_time` datetime DEFAULT NULL COMMENT '分析时间(analysis_time)',
  
  -- 检测结果核心数据 (从TCP解析)
  `result_value` decimal(10, 6) DEFAULT NULL COMMENT '检测结果值(result_Value)',
  `result_type` varchar(50) DEFAULT NULL COMMENT '结果类型(result_type)',
  `nitrogen_content` decimal(10, 6) DEFAULT NULL COMMENT '氮含量% - 计算字段',
  `protein_content` decimal(10, 6) DEFAULT NULL COMMENT '蛋白质含量% - 计算字段',
  
  -- 设备和方法信息 (从TCP解析)
  `apparatus_name` varchar(100) DEFAULT NULL COMMENT '设备名称(apparatusName)',
  `manufacturer_name` varchar(100) DEFAULT NULL COMMENT '制造商名称(manufacturerName)',
  `method_name` varchar(100) DEFAULT NULL COMMENT '检测方法(method_name)',
  
  -- 关键检测参数 (从TCP解析)
  `conversion_coefficient` decimal(10, 6) DEFAULT NULL COMMENT '转换系数(conversion_coefficient)',
  `protein_factor` decimal(10, 6) DEFAULT NULL COMMENT '蛋白质因子(protein_factor)',
  `alkali_volume` decimal(10, 3) DEFAULT NULL COMMENT '碱液体积mL(alkali_volume)',
  `dilution_volume` decimal(10, 3) DEFAULT NULL COMMENT '稀释体积mL(dilution_volume)',
  `receiver_volume` decimal(10, 3) DEFAULT NULL COMMENT '接收器体积mL(receiver_volume)',
  `titrant_volume_blank` decimal(12, 8) DEFAULT NULL COMMENT '空白滴定液体积mL(titrant_volume_for_blank)',
  `titrant_volume_sample` decimal(12, 8) DEFAULT NULL COMMENT '样品滴定液体积mL(titrant_volume_for_sample)',
  `titration_acid_concentration` decimal(12, 8) DEFAULT NULL COMMENT '滴定酸浓度%(titration_acid_concentration)',
  `distillation_value` decimal(10, 3) DEFAULT NULL COMMENT '蒸馏值(distillation_Value)',
  `steam_power` decimal(5, 2) DEFAULT NULL COMMENT '蒸汽功率%(steam_power)',
  `water_coefficient` decimal(10, 6) DEFAULT NULL COMMENT '水系数(water_coefficient)',
  
  -- 质量控制参数 (从TCP解析)
  `high_error_limit` decimal(10, 6) DEFAULT NULL COMMENT '高错误限值(high_error_limit)',
  `low_error_limit` decimal(10, 6) DEFAULT NULL COMMENT '低错误限值(low_error_limit)',
  `intercept` decimal(10, 6) DEFAULT NULL COMMENT '截距(intercept)',
  `slope` decimal(10, 6) DEFAULT NULL COMMENT '斜率(slope)',
  
  -- 设备配置参数 (从TCP解析，存为JSON)
  `device_config` json DEFAULT NULL COMMENT '设备配置参数JSON(cleaning,emptying,mode等)',
  
  -- 绑定关系字段 (用户操作)
  `bind_status` varchar(20) NOT NULL DEFAULT 'unbound' COMMENT '绑定状态(unbound=未绑定/bound=已绑定)',
  `bind_type` varchar(20) DEFAULT NULL COMMENT '绑定的质检类型(material/intermediate/foreign/final)',
  `bind_inspection_id` bigint DEFAULT NULL COMMENT '绑定的质检单ID',
  `bind_time` datetime DEFAULT NULL COMMENT '绑定时间',
  `bind_operator` varchar(64) DEFAULT NULL COMMENT '绑定操作人',
  
  -- 业务字段
  `data_creator` varchar(50) DEFAULT NULL COMMENT 'TCP数据创建者(created)',
  `inspector` varchar(50) DEFAULT NULL COMMENT '检验员',
  `inspection_date` datetime DEFAULT NULL COMMENT '检验日期',
  `remark` varchar(500) DEFAULT NULL COMMENT '备注',
  
  -- 系统字段
  `create_by` varchar(64) DEFAULT 'system' COMMENT '创建者',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` varchar(64) DEFAULT NULL COMMENT '更新者',
  `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `del_flag` char(1) NOT NULL DEFAULT '0' COMMENT '删除标志(0=存在/2=删除)',
  
  -- 主键和索引
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_inspection_no` (`inspection_no`),
  UNIQUE KEY `uk_bind_unique` (`bind_type`, `bind_inspection_id`),
  KEY `idx_tcp_received_time` (`tcp_received_time`),
  KEY `idx_sample_id` (`sample_id`),
  KEY `idx_analysis_time` (`analysis_time`),
  KEY `idx_apparatus_name` (`apparatus_name`),
  KEY `idx_bind_status` (`bind_status`),
  KEY `idx_bind_type_id` (`bind_type`, `bind_inspection_id`),
  KEY `idx_create_time` (`create_time`),
  
  -- 约束
  CONSTRAINT `chk_bind_status` CHECK (`bind_status` IN ('unbound', 'bound')),
  CONSTRAINT `chk_bind_type` CHECK (`bind_type` IN ('material', 'intermediate', 'foreign', 'final')),
  CONSTRAINT `chk_bind_consistency` CHECK (
    (`bind_status` = 'unbound' AND `bind_type` IS NULL AND `bind_inspection_id` IS NULL) OR
    (`bind_status` = 'bound' AND `bind_type` IS NOT NULL AND `bind_inspection_id` IS NOT NULL)
  )
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='定氮仪信息主表';

-- ========================================
-- 2. 定氮仪信息详情表 (存储data数组)
-- ========================================
DROP TABLE IF EXISTS `qc_kna_info_detail`;
CREATE TABLE `qc_kna_info_detail` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `kna_info_id` bigint NOT NULL COMMENT '定氮仪信息主表ID',
  
  -- TCP data数组字段
  `circulate_order` int DEFAULT NULL COMMENT '循环顺序(circulateOrder)',
  `inspection_date` date DEFAULT NULL COMMENT '检验日期(inspectionDate)',
  `inspection_time` time DEFAULT NULL COMMENT '检验时间(inspectionTime)',
  `inspection_project` varchar(100) DEFAULT NULL COMMENT '检验项目(inspectionProject)',
  `inspection_result` varchar(500) DEFAULT NULL COMMENT '检验结果(inspectionResult)',
  `sequence_no` int DEFAULT 0 COMMENT '序列号(从0开始)',
  
  -- 系统字段
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  
  PRIMARY KEY (`id`),
  KEY `idx_kna_info_id` (`kna_info_id`),
  KEY `idx_inspection_date` (`inspection_date`),
  KEY `idx_sequence_no` (`sequence_no`),
  
  -- 外键约束
  CONSTRAINT `fk_detail_kna_info` FOREIGN KEY (`kna_info_id`) 
    REFERENCES `qc_kna_info` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='定氮仪信息详情表';

-- ========================================
-- 3. 定氮仪配置表
-- ========================================
DROP TABLE IF EXISTS `qc_kna_info_config`;
CREATE TABLE `qc_kna_info_config` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `config_name` varchar(100) NOT NULL COMMENT '配置名称',
  `config_type` varchar(50) NOT NULL COMMENT '配置类型(tcp/device/method/standard)',
  `config_content` json NOT NULL COMMENT '配置内容JSON',
  `is_active` char(1) NOT NULL DEFAULT '1' COMMENT '是否启用(0=否/1=是)',
  `sort_order` int NOT NULL DEFAULT 0 COMMENT '排序序号',
  `description` varchar(500) DEFAULT NULL COMMENT '配置说明',
  
  -- 系统字段
  `create_by` varchar(64) NOT NULL DEFAULT 'admin' COMMENT '创建者',
  `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_by` varchar(64) DEFAULT NULL COMMENT '更新者',
  `update_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `del_flag` char(1) NOT NULL DEFAULT '0' COMMENT '删除标志(0=存在/2=删除)',
  
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_config_name` (`config_name`),
  KEY `idx_config_type` (`config_type`),
  KEY `idx_is_active` (`is_active`),
  KEY `idx_sort_order` (`sort_order`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='定氮仪信息配置表';

-- ========================================
-- 4. 为现有质检表添加反向关联字段
-- ========================================

-- 原料质检表添加定氮仪关联
ALTER TABLE `qc_material_inspection` 
  ADD COLUMN `kna_info_id` bigint DEFAULT NULL COMMENT '关联的定氮仪信息ID',
  ADD COLUMN `kna_bind_time` datetime DEFAULT NULL COMMENT '定氮仪绑定时间',
  ADD KEY `idx_kna_info` (`kna_info_id`);

-- 中间产品质检表添加定氮仪关联
ALTER TABLE `qc_intermediate_inspection`
  ADD COLUMN `kna_info_id` bigint DEFAULT NULL COMMENT '关联的定氮仪信息ID',
  ADD COLUMN `kna_bind_time` datetime DEFAULT NULL COMMENT '定氮仪绑定时间',
  ADD KEY `idx_kna_info` (`kna_info_id`);

-- 外来品质检表添加定氮仪关联
ALTER TABLE `qc_foreign_inspection`
  ADD COLUMN `kna_info_id` bigint DEFAULT NULL COMMENT '关联的定氮仪信息ID',
  ADD COLUMN `kna_bind_time` datetime DEFAULT NULL COMMENT '定氮仪绑定时间',
  ADD KEY `idx_kna_info` (`kna_info_id`);

-- 最终产品质检表添加定氮仪关联
ALTER TABLE `qc_final_inspection`
  ADD COLUMN `kna_info_id` bigint DEFAULT NULL COMMENT '关联的定氮仪信息ID',
  ADD COLUMN `kna_bind_time` datetime DEFAULT NULL COMMENT '定氮仪绑定时间',
  ADD KEY `idx_kna_info` (`kna_info_id`);

-- ========================================
-- 5. 创建查询视图 (过滤未绑定的质检单)
-- ========================================

-- 未绑定的原料质检单
CREATE OR REPLACE VIEW `v_unbound_material_inspections` AS
SELECT 
  id, inspection_no, material_name, batch_no, sample_quantity, 
  inspection_date, inspector, create_time
FROM `qc_material_inspection` 
WHERE `kna_info_id` IS NULL 
  AND `del_flag` = '0';

-- 未绑定的中间产品质检单
CREATE OR REPLACE VIEW `v_unbound_intermediate_inspections` AS
SELECT 
  id, inspection_no, product_name, batch_no, sample_quantity,
  inspection_date, inspector, create_time
FROM `qc_intermediate_inspection`
WHERE `kna_info_id` IS NULL 
  AND `del_flag` = '0';

-- 未绑定的外来品质检单
CREATE OR REPLACE VIEW `v_unbound_foreign_inspections` AS
SELECT 
  id, inspection_no, product_name, sample_no, 
  quantity as sample_quantity, -- 外来品表用的是quantity字段
  inspection_date, inspector, create_time
FROM `qc_foreign_inspection`
WHERE `kna_info_id` IS NULL 
  AND `del_flag` = '0';

-- 未绑定的最终产品质检单
CREATE OR REPLACE VIEW `v_unbound_final_inspections` AS
SELECT 
  id, inspection_no, product_name, batch_no, sample_quantity,
  inspection_date, inspector, create_time
FROM `qc_final_inspection`
WHERE `kna_info_id` IS NULL 
  AND `del_flag` = '0';

-- 定氮仪绑定关系汇总视图
CREATE OR REPLACE VIEW `v_kna_info_bindings` AS
SELECT 
  n.id as kna_info_id,
  n.inspection_no as kna_info_no,
  n.sample_name,
  n.bind_status,
  n.bind_type,
  n.bind_inspection_id,
  n.bind_time,
  n.bind_operator,
  CASE 
    WHEN n.bind_type = 'material' THEN m.inspection_no
    WHEN n.bind_type = 'intermediate' THEN i.inspection_no
    WHEN n.bind_type = 'foreign' THEN f.inspection_no
    WHEN n.bind_type = 'final' THEN fi.inspection_no
    ELSE NULL
  END as bound_inspection_no,
  CASE 
    WHEN n.bind_type = 'material' THEN m.material_name
    WHEN n.bind_type = 'intermediate' THEN i.product_name
    WHEN n.bind_type = 'foreign' THEN f.product_name
    WHEN n.bind_type = 'final' THEN fi.product_name
    ELSE NULL
  END as bound_inspection_name,
  n.create_time as kna_info_create_time
FROM `qc_kna_info` n
LEFT JOIN `qc_material_inspection` m ON n.bind_type = 'material' AND n.bind_inspection_id = m.id
LEFT JOIN `qc_intermediate_inspection` i ON n.bind_type = 'intermediate' AND n.bind_inspection_id = i.id
LEFT JOIN `qc_foreign_inspection` f ON n.bind_type = 'foreign' AND n.bind_inspection_id = f.id
LEFT JOIN `qc_final_inspection` fi ON n.bind_type = 'final' AND n.bind_inspection_id = fi.id
WHERE n.del_flag = '0';

-- ========================================
-- 6. 插入编码规则配置
-- ========================================
INSERT INTO `sys_code_rule` (id, name, basic_domain, status, create_by, create_time, remark) 
VALUES (23, '定氮仪质检编码规则', 'NitrogenInspection', '0', 'admin', NOW(), '定氮仪质检单号生成规则')
ON DUPLICATE KEY UPDATE name = VALUES(name);

INSERT INTO `sys_code_rule_entry` (rule_id, sort, type_id, length_flow, max_flow, constant_char, date_format, code_cover) VALUES 
(23, 1, 'B', 0, 0, 'DN', NULL, ''),
(23, 2, 'C', 0, 0, '', 'yyyyMMdd', ''),  
(23, 3, 'A', 3, 1, '', NULL, '0')
ON DUPLICATE KEY UPDATE sort = VALUES(sort);

-- ========================================
-- 7. 插入基础配置数据
-- ========================================
INSERT INTO `qc_kna_info_config` 
(config_name, config_type, config_content, is_active, sort_order, description, create_by, create_time) VALUES
(
  'TCP服务配置', 
  'tcp', 
  JSON_OBJECT(
    'port', 8890,
    'timeout', 30000,
    'maxConnections', 10,
    'bufferSize', 8192,
    'charset', 'UTF-8'
  ),
  '1', 
  1, 
  'TCP服务器监听配置',
  'admin', 
  NOW()
),
(
  '默认设备配置', 
  'device', 
  JSON_OBJECT(
    'apparatusName', 'KI160',
    'manufacturerName', 'ZDYC',
    'defaultProteinFactor', 6.25,
    'defaultConversionCoefficient', 1.0
  ),
  '1', 
  2, 
  '定氮仪默认设备参数',
  'admin', 
  NOW()
),
(
  '标准检测方法', 
  'method', 
  JSON_OBJECT(
    'methodName', '凯氏定氮法',
    'standardProteinFactor', 6.25,
    'accuracyRequirement', 0.1,
    'repeatabilityLimit', 0.05
  ),
  '1', 
  3, 
  '标准凯氏定氮检测方法配置',
  'admin', 
  NOW()
),
(
  '质量控制标准', 
  'standard', 
  JSON_OBJECT(
    'highErrorLimit', 5.0,
    'lowErrorLimit', -5.0,
    'warningLimit', 3.0,
    'controlChartLimits', JSON_OBJECT('ucl', 5.0, 'lcl', -5.0, 'centerLine', 0.0)
  ),
  '1', 
  4, 
  '质量控制标准参数配置',
  'admin', 
  NOW()
)
ON DUPLICATE KEY UPDATE 
  config_content = VALUES(config_content),
  update_time = NOW();

-- ========================================
-- 8. 创建性能优化索引
-- ========================================

-- 定氮仪主表复合索引
CREATE INDEX `idx_kna_status_date` ON `qc_kna_info` (`bind_status`, `tcp_received_time`);
CREATE INDEX `idx_kna_apparatus_date` ON `qc_kna_info` (`apparatus_name`, `create_time`);
CREATE INDEX `idx_kna_sample_analysis` ON `qc_kna_info` (`sample_id`, `analysis_time`);

-- 详情表复合索引  
CREATE INDEX `idx_detail_kna_seq` ON `qc_kna_info_detail` (`kna_info_id`, `sequence_no`);
CREATE INDEX `idx_detail_date_time` ON `qc_kna_info_detail` (`inspection_date`, `inspection_time`);

-- ========================================
-- 执行结果验证
-- ========================================

SELECT '数据库重新设计完成！' AS '执行结果',
       '一对一关系，绑定后隐藏机制' AS '设计特点',
       '支持TCP数据接收和质检单绑定' AS '主要功能';

-- 验证表创建
SELECT 
  '表创建验证' AS '检查项目',
  COUNT(*) AS '定氮仪相关表数'
FROM information_schema.tables 
WHERE table_schema = 'yjh_mes_plsw' 
  AND table_name LIKE 'qc_kna%';

-- 验证视图创建
SELECT 
  '视图创建验证' AS '检查项目',
  COUNT(*) AS '未绑定视图数'
FROM information_schema.views
WHERE table_schema = 'yjh_mes_plsw'
  AND (table_name LIKE 'v_%kna%' OR table_name LIKE 'v_unbound%');

-- 验证字段添加
SELECT 
  '字段添加验证' AS '检查项目',
  COUNT(*) AS '添加字段数'
FROM information_schema.columns
WHERE table_schema = 'yjh_mes_plsw'
  AND column_name = 'kna_info_id';

-- 验证配置数据
SELECT 
  '配置数据验证' AS '检查项目',
  COUNT(*) AS '配置项数'
FROM qc_kna_info_config
WHERE del_flag = '0';

SELECT 
  '编码规则验证' AS '检查项目',
  COUNT(*) AS '规则数'
FROM sys_code_rule 
WHERE basic_domain = 'NitrogenInspection';
