-- ============================================
-- 商品管理改造 - 数据库迁移脚本
-- 支持二级分类树状结构
-- ============================================

-- 1. 创建新的分类表（树状结构）
CREATE TABLE IF NOT EXISTS category_tree (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,                      -- 分类名称
  parent_id INTEGER DEFAULT NULL,          -- 父分类ID（NULL表示一级分类）
  level INTEGER DEFAULT 1,                 -- 层级（1=一级，2=二级）
  sort_order INTEGER DEFAULT 0,            -- 排序
  description TEXT,                        -- 描述
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (parent_id) REFERENCES category_tree(id) ON DELETE CASCADE
);

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_category_parent ON category_tree(parent_id);
CREATE INDEX IF NOT EXISTS idx_category_level ON category_tree(level);

-- 2. 修改商品表，支持新字段和二级分类
-- 先备份原表
ALTER TABLE products RENAME TO products_backup;

-- 创建新的商品表
CREATE TABLE products (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,                      -- 商品名称
  model TEXT,                              -- 型号
  category_id INTEGER,                     -- 二级分类ID（关联category_tree）
  category_name TEXT,                      -- 分类名称（冗余，方便查询）
  unit TEXT DEFAULT '件',                  -- 单位
  cost_price REAL,                         -- 成本单价（可为空）
  price REAL DEFAULT 0,                    -- 销售单价
  brand TEXT,                              -- 品牌
  specification TEXT,                      -- 规格参数
  source TEXT DEFAULT '老挝',               -- 来源（中国/老挝）
  remark TEXT,                             -- 备注
  stock_quantity REAL DEFAULT 0,           -- 库存数量
  stock_warning REAL DEFAULT 0,            -- 库存预警值
  status TEXT DEFAULT 'active',            -- 状态：active/disabled
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (category_id) REFERENCES category_tree(id)
);

-- 迁移旧数据（简化版，不处理旧数据迁移）
-- 直接创建空的新表结构
-- INSERT INTO products (
--   id, name, model, category_id, category_name, unit, 
--   price, brand, specification, remark, status, created_at, updated_at
-- )
-- SELECT 
--   p.id, 
--   p.name, 
--   NULL as model,
--   NULL as category_id,
--   NULL as category_name,
--   COALESCE(p.unit, '件'),
--   COALESCE(p.price, 0),
--   NULL as brand,
--   NULL as specification,
--   p.remark,
--   'active',
--   p.created_at,
--   p.updated_at
-- FROM products_backup p;

-- 删除备份表
DROP TABLE products_backup;

-- 创建索引
CREATE INDEX IF NOT EXISTS idx_products_category ON products(category_id);
CREATE INDEX IF NOT EXISTS idx_products_name ON products(name);
CREATE INDEX IF NOT EXISTS idx_products_status ON products(status);

-- 3. 删除旧的categories表（数据已迁移到category_tree）
-- 注意：先检查是否还有其他表依赖categories
-- DROP TABLE IF EXISTS categories;

-- ============================================
-- 初始化默认分类数据
-- ============================================

-- 插入一级分类
INSERT INTO category_tree (name, parent_id, level, sort_order, description) VALUES
  ('电杆横担', NULL, 1, 1, '电杆、横担及相关配件'),
  ('电缆电线', NULL, 1, 2, '各类电缆、电线产品'),
  ('变压器', NULL, 1, 3, '变压器及相关设备'),
  ('开关设备', NULL, 1, 4, '开关、断路器等设备'),
  ('金具', NULL, 1, 5, '电力金具、连接件'),
  ('工具仪器', NULL, 1, 6, '施工工具、检测仪器'),
  ('劳保用品', NULL, 1, 7, '安全防护用品'),
  ('其他材料', NULL, 1, 99, '其他未分类材料');

-- 插入二级分类（电杆横担）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '混凝土电杆', id, 2, 1, '混凝土材质电杆'
FROM category_tree WHERE name = '电杆横担' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '钢管电杆', id, 2, 2, '钢管材质电杆'
FROM category_tree WHERE name = '电杆横担' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '横担', id, 2, 3, '各类横担'
FROM category_tree WHERE name = '电杆横担' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '抱箍', id, 2, 4, '电杆抱箍'
FROM category_tree WHERE name = '电杆横担' AND level = 1;

-- 插入二级分类（电缆电线）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '高压电缆', id, 2, 1, '高压电力电缆'
FROM category_tree WHERE name = '电缆电线' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '低压电缆', id, 2, 2, '低压电力电缆'
FROM category_tree WHERE name = '电缆电线' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '架空导线', id, 2, 3, '架空绝缘导线'
FROM category_tree WHERE name = '电缆电线' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '控制电缆', id, 2, 4, '控制用电缆'
FROM category_tree WHERE name = '电缆电线' AND level = 1;

-- 插入二级分类（变压器）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '配电变压器', id, 2, 1, '配电用变压器'
FROM category_tree WHERE name = '变压器' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '箱式变电站', id, 2, 2, '箱式变电站'
FROM category_tree WHERE name = '变压器' AND level = 1;

-- 插入二级分类（开关设备）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '断路器', id, 2, 1, '各类断路器'
FROM category_tree WHERE name = '开关设备' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '隔离开关', id, 2, 2, '隔离开关'
FROM category_tree WHERE name = '开关设备' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '熔断器', id, 2, 3, '熔断器'
FROM category_tree WHERE name = '开关设备' AND level = 1;

-- 插入二级分类（金具）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '耐张线夹', id, 2, 1, '耐张线夹'
FROM category_tree WHERE name = '金具' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '悬垂线夹', id, 2, 2, '悬垂线夹'
FROM category_tree WHERE name = '金具' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '连接金具', id, 2, 3, '连接金具'
FROM category_tree WHERE name = '金具' AND level = 1;

-- 插入二级分类（工具仪器）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '施工工具', id, 2, 1, '电力施工工具'
FROM category_tree WHERE name = '工具仪器' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '检测仪器', id, 2, 2, '检测测试仪器'
FROM category_tree WHERE name = '工具仪器' AND level = 1;

-- 插入二级分类（劳保用品）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '安全帽', id, 2, 1, '安全帽'
FROM category_tree WHERE name = '劳保用品' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '安全带', id, 2, 2, '安全带'
FROM category_tree WHERE name = '劳保用品' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '绝缘手套', id, 2, 3, '绝缘手套'
FROM category_tree WHERE name = '劳保用品' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '绝缘鞋', id, 2, 4, '绝缘鞋'
FROM category_tree WHERE name = '劳保用品' AND level = 1;

-- 插入二级分类（其他材料）
INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '标识标牌', id, 2, 1, '标识标牌'
FROM category_tree WHERE name = '其他材料' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '接地材料', id, 2, 2, '接地装置材料'
FROM category_tree WHERE name = '其他材料' AND level = 1;

INSERT INTO category_tree (name, parent_id, level, sort_order, description) 
SELECT '其他', id, 2, 99, '其他未分类'
FROM category_tree WHERE name = '其他材料' AND level = 1;

-- ============================================
-- 创建触发器：自动更新updated_at
-- ============================================
CREATE TRIGGER IF NOT EXISTS update_category_tree_timestamp 
AFTER UPDATE ON category_tree
BEGIN
  UPDATE category_tree SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END;

CREATE TRIGGER IF NOT EXISTS update_products_timestamp 
AFTER UPDATE ON products
BEGIN
  UPDATE products SET updated_at = CURRENT_TIMESTAMP WHERE id = NEW.id;
END;

-- ============================================
-- 迁移完成
-- ============================================
SELECT '数据库迁移完成' as message;
SELECT '商品表已更新，支持二级分类' as message;
SELECT '分类表已创建，支持树状结构' as message;
