-- ============================================================
-- PSI 订单/出库与业务表建表 —— 服装厂成衣标准
-- ============================================================
-- 包含：销售订单、采购订单、出库单 共 6 张表
--       + 修复 psi_purchases 缺少列
--       各表均已补齐品牌/款号/色号/尺码明细/箱重/体积等成衣行业必备字段
-- ============================================================

-- -------------------------------------------
-- 1. 销售订单主表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_sales_orders` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `order_no` VARCHAR(40) NOT NULL COMMENT '订单编号 SO+年月日+流水',
  `customer` VARCHAR(100) NOT NULL COMMENT '客户名称',
  `customer_po` VARCHAR(80) DEFAULT '' COMMENT '客户采购单号（国际成衣贸易必备）',
  `brand` VARCHAR(100) DEFAULT '' COMMENT '品牌',
  `salesman` VARCHAR(50) DEFAULT '' COMMENT '业务员',
  `channel` VARCHAR(20) DEFAULT 'domestic' COMMENT '销售渠道 domestic/export',
  `region` VARCHAR(60) DEFAULT '' COMMENT '销售区域',
  `currency` VARCHAR(10) DEFAULT 'CNY' COMMENT '币种 CNY/USD/EUR',
  `payment_terms` VARCHAR(50) DEFAULT '' COMMENT '付款条件 T/T,L/C,D/P,OA',
  `incoterm` VARCHAR(10) DEFAULT '' COMMENT '贸易术语 FOB/CIF/EXW/CFR/DDP',
  `shipping_mark` VARCHAR(200) DEFAULT '' COMMENT '唛头',
  `style_count` INT DEFAULT 0 COMMENT '款数',
  `total_qty` INT DEFAULT 0 COMMENT '总数量',
  `total_amount` DECIMAL(12,2) DEFAULT 0 COMMENT '总金额',
  `delivery_date` VARCHAR(20) DEFAULT '' COMMENT '预计交付日期',
  `remark` TEXT COMMENT '备注',
  `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态 pending/partial/delivered/closed',
  `created_at` VARCHAR(20) DEFAULT '' COMMENT '创建时间',
  `updated_at` VARCHAR(20) DEFAULT '' COMMENT '最后修改时间',
  INDEX `idx_so_customer` (`customer`),
  INDEX `idx_so_salesman` (`salesman`),
  INDEX `idx_so_status` (`status`),
  INDEX `idx_so_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='销售订单主表';

-- -------------------------------------------
-- 2. 销售订单明细表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_sales_order_items` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `so_id` INT NOT NULL COMMENT '关联销售订单ID',
  `product_id` INT DEFAULT 0 COMMENT '关联成品ID',
  `style_no` VARCHAR(60) DEFAULT '' COMMENT '款号/货号',
  `name` VARCHAR(120) NOT NULL COMMENT '商品名称',
  `spec` VARCHAR(100) DEFAULT '' COMMENT '规格',
  `color_code` VARCHAR(30) DEFAULT '' COMMENT '色号',
  `size_detail` TEXT COMMENT '尺码明细 JSON [{size:\"S\",qty:100},...]',
  `unit` VARCHAR(20) DEFAULT '件' COMMENT '单位',
  `qty` INT DEFAULT 0 COMMENT '数量',
  `price` DECIMAL(10,2) DEFAULT 0 COMMENT '单价',
  `amount` DECIMAL(12,2) DEFAULT 0 COMMENT '金额',
  `unit_price_cny` DECIMAL(10,2) DEFAULT 0 COMMENT '人民币单价（外单换算用）',
  `packing` VARCHAR(60) DEFAULT '' COMMENT '包装方式（独色独码/混色混码）',
  `delivered_qty` INT DEFAULT 0 COMMENT '已交付数量',
  INDEX `idx_soi_so_id` (`so_id`),
  INDEX `idx_soi_product_id` (`product_id`),
  INDEX `idx_soi_style_no` (`style_no`),
  FOREIGN KEY (`so_id`) REFERENCES `psi_sales_orders`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='销售订单明细';

-- -------------------------------------------
-- 3. 采购订单主表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_purchase_orders` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `order_no` VARCHAR(40) NOT NULL COMMENT '订单编号 PO+年月日+流水',
  `contract_no` VARCHAR(80) DEFAULT '' COMMENT '合同号',
  `supplier_id` INT DEFAULT 0 COMMENT '供应商ID',
  `supplier_name` VARCHAR(100) DEFAULT '' COMMENT '供应商名称',
  `brand` VARCHAR(100) DEFAULT '' COMMENT '品牌',
  `salesman` VARCHAR(50) DEFAULT '' COMMENT '采购员',
  `currency` VARCHAR(10) DEFAULT 'CNY' COMMENT '币种',
  `payment_terms` VARCHAR(50) DEFAULT '' COMMENT '付款条件',
  `total_qty` INT DEFAULT 0 COMMENT '总数量',
  `total_amount` DECIMAL(12,2) DEFAULT 0 COMMENT '总金额',
  `expected_at` VARCHAR(20) DEFAULT '' COMMENT '预计到货日期',
  `remark` TEXT COMMENT '备注',
  `status` VARCHAR(20) DEFAULT 'pending' COMMENT '状态 pending/received/closed',
  `created_at` VARCHAR(20) DEFAULT '' COMMENT '创建时间',
  `updated_at` VARCHAR(20) DEFAULT '' COMMENT '最后修改时间',
  INDEX `idx_po_supplier` (`supplier_id`),
  INDEX `idx_po_status` (`status`),
  INDEX `idx_po_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购订单主表';

-- -------------------------------------------
-- 4. 采购订单明细表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_purchase_order_items` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `po_id` INT NOT NULL COMMENT '关联采购订单ID',
  `item_type` VARCHAR(10) DEFAULT 'product' COMMENT '类型 product/material',
  `item_id` INT DEFAULT 0 COMMENT '关联物料/成品ID',
  `style_no` VARCHAR(60) DEFAULT '' COMMENT '款号/货号',
  `name` VARCHAR(120) NOT NULL COMMENT '商品名称',
  `spec` VARCHAR(100) DEFAULT '' COMMENT '规格',
  `color_code` VARCHAR(30) DEFAULT '' COMMENT '色号',
  `size_detail` TEXT COMMENT '尺码明细 JSON',
  `material_code` VARCHAR(60) DEFAULT '' COMMENT '物料编码',
  `unit` VARCHAR(20) DEFAULT '件' COMMENT '单位',
  `qty` INT DEFAULT 0 COMMENT '数量',
  `price` DECIMAL(10,2) DEFAULT 0 COMMENT '单价',
  `amount` DECIMAL(12,2) DEFAULT 0 COMMENT '金额',
  `delivery_date` VARCHAR(20) DEFAULT '' COMMENT '预计交期',
  `received_qty` INT DEFAULT 0 COMMENT '已收货数量',
  INDEX `idx_poi_po_id` (`po_id`),
  INDEX `idx_poi_item_type` (`item_type`),
  INDEX `idx_poi_style_no` (`style_no`),
  FOREIGN KEY (`po_id`) REFERENCES `psi_purchase_orders`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购订单明细';

-- -------------------------------------------
-- 5. 出库单主表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_outbounds` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `order_no` VARCHAR(40) NOT NULL COMMENT '出库单号 OUT+年月日+流水',
  `so_no` VARCHAR(40) DEFAULT '' COMMENT '关联销售订单号',
  `customer` VARCHAR(100) DEFAULT '' COMMENT '客户',
  `customer_po` VARCHAR(80) DEFAULT '' COMMENT '客户采购单号',
  `brand` VARCHAR(100) DEFAULT '' COMMENT '品牌',
  `salesman` VARCHAR(50) DEFAULT '' COMMENT '业务员',
  `warehouse` VARCHAR(60) DEFAULT '' COMMENT '出库仓库',
  `carton_count` INT DEFAULT 0 COMMENT '箱数',
  `container_no` VARCHAR(100) DEFAULT '' COMMENT '柜号/箱号范围',
  `seal_no` VARCHAR(60) DEFAULT '' COMMENT '封条号',
  `packing_list_no` VARCHAR(60) DEFAULT '' COMMENT '装箱单号',
  `shipping_line` VARCHAR(80) DEFAULT '' COMMENT '船公司/快递',
  `voyage` VARCHAR(60) DEFAULT '' COMMENT '航次/航班',
  `port_of_loading` VARCHAR(60) DEFAULT '' COMMENT '装运港',
  `port_of_discharge` VARCHAR(60) DEFAULT '' COMMENT '卸货港',
  `etd` VARCHAR(20) DEFAULT '' COMMENT '预计离港日',
  `eta` VARCHAR(20) DEFAULT '' COMMENT '预计到港日',
  `gross_weight` DECIMAL(10,2) DEFAULT 0 COMMENT '毛重 KG',
  `net_weight` DECIMAL(10,2) DEFAULT 0 COMMENT '净重 KG',
  `volume` DECIMAL(10,3) DEFAULT 0 COMMENT '体积 CBM',
  `status` VARCHAR(20) DEFAULT 'delivered' COMMENT '状态 delivered/partial',
  `delivery_date` VARCHAR(20) DEFAULT '' COMMENT '实际交付日期',
  `remark` TEXT COMMENT '备注',
  `created_at` VARCHAR(20) DEFAULT '' COMMENT '创建时间',
  `updated_at` VARCHAR(20) DEFAULT '' COMMENT '最后修改时间',
  INDEX `idx_ob_so_no` (`so_no`),
  INDEX `idx_ob_customer` (`customer`),
  INDEX `idx_ob_status` (`status`),
  INDEX `idx_ob_created` (`created_at`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='出库单主表';

-- -------------------------------------------
-- 6. 出库单明细表
-- -------------------------------------------
CREATE TABLE IF NOT EXISTS `psi_outbound_items` (
  `id` INT AUTO_INCREMENT PRIMARY KEY,
  `ob_id` INT NOT NULL COMMENT '关联出库单ID',
  `so_item_id` INT DEFAULT 0 COMMENT '关联销售订单明细ID',
  `product_id` INT DEFAULT 0 COMMENT '成品ID',
  `style_no` VARCHAR(60) DEFAULT '' COMMENT '款号/货号',
  `name` VARCHAR(120) NOT NULL COMMENT '商品名称',
  `spec` VARCHAR(100) DEFAULT '' COMMENT '规格',
  `color_code` VARCHAR(30) DEFAULT '' COMMENT '色号',
  `size_detail` TEXT COMMENT '尺码明细 JSON',
  `carton_no` VARCHAR(40) DEFAULT '' COMMENT '箱号',
  `unit` VARCHAR(20) DEFAULT '件' COMMENT '单位',
  `qty` INT DEFAULT 0 COMMENT '数量',
  `price` DECIMAL(10,2) DEFAULT 0 COMMENT '单价',
  `amount` DECIMAL(12,2) DEFAULT 0 COMMENT '金额',
  `unit_weight` DECIMAL(10,2) DEFAULT 0 COMMENT '单件重量 g/KG',
  INDEX `idx_obi_ob_id` (`ob_id`),
  INDEX `idx_obi_product_id` (`product_id`),
  INDEX `idx_obi_so_item_id` (`so_item_id`),
  INDEX `idx_obi_style_no` (`style_no`),
  FOREIGN KEY (`ob_id`) REFERENCES `psi_outbounds`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='出库单明细';

-- -------------------------------------------
-- 7. 修复 psi_purchases —— 补齐 PurchaseOrdersController::receive() 所需的列
-- -------------------------------------------
-- 使用 INFORMATION_SCHEMA 动态检测是否存在列，兼容 MySQL 5.7+ / MariaDB 10.2+
DROP PROCEDURE IF EXISTS tmp_psi_purchases_alter;
DELIMITER $$
CREATE PROCEDURE tmp_psi_purchases_alter()
BEGIN
  IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'psi_purchases' AND COLUMN_NAME = 'product_id') THEN
    ALTER TABLE `psi_purchases` ADD COLUMN `product_id` INT DEFAULT 0 COMMENT '成品ID（采购订单收货时使用）' AFTER `item_id`;
  END IF;
  IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'psi_purchases' AND COLUMN_NAME = 'supplier') THEN
    ALTER TABLE `psi_purchases` ADD COLUMN `supplier` VARCHAR(100) DEFAULT '' COMMENT '供应商名称' AFTER `supplier_id`;
  END IF;
  IF NOT EXISTS (SELECT 1 FROM information_schema.COLUMNS
                 WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'psi_purchases' AND COLUMN_NAME = 'brand') THEN
    ALTER TABLE `psi_purchases` ADD COLUMN `brand` VARCHAR(100) DEFAULT '' COMMENT '品牌' AFTER `supplier`;
  END IF;
END$$
DELIMITER ;
CALL tmp_psi_purchases_alter();
DROP PROCEDURE IF EXISTS tmp_psi_purchases_alter;
