-- Drop biz_tenant since it was already created
-- Now run the rest of tables

-- 给 sys_user 增加 tenant_id 字段（用于SaaS隔离）
DROP PROCEDURE IF EXISTS add_tenant_col;
DELIMITER //
CREATE PROCEDURE add_tenant_col()
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = DATABASE() AND table_name = 'sys_user' AND column_name = 'tenant_id'
  ) THEN
    ALTER TABLE sys_user ADD COLUMN tenant_id BIGINT DEFAULT 1 COMMENT '所属租户';
  END IF;
END //
DELIMITER ;
CALL add_tenant_col();
DROP PROCEDURE IF EXISTS add_tenant_col;

-- 物料分类
CREATE TABLE IF NOT EXISTS biz_material_category (
  category_id   BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  category_name VARCHAR(100) NOT NULL,
  parent_id     BIGINT DEFAULT 0,
  ancestors     VARCHAR(500) DEFAULT '',
  sort          INT DEFAULT 0,
  status        CHAR(1) DEFAULT '0',
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  PRIMARY KEY (category_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='物料分类';

CREATE TABLE IF NOT EXISTS biz_material (
  material_id   BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  category_id   BIGINT DEFAULT 0,
  material_code VARCHAR(50) NOT NULL COMMENT '物料编码',
  material_name VARCHAR(200) NOT NULL COMMENT '物料名称',
  spec          VARCHAR(500) DEFAULT '' COMMENT '规格型号',
  unit          VARCHAR(50) DEFAULT '' COMMENT '单位',
  brand         VARCHAR(100) DEFAULT '' COMMENT '品牌',
  description   TEXT COMMENT '描述',
  status        CHAR(1) DEFAULT '0',
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  update_by     VARCHAR(64) DEFAULT '',
  update_time   DATETIME,
  remark        VARCHAR(500) DEFAULT NULL,
  PRIMARY KEY (material_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='物料';

CREATE TABLE IF NOT EXISTS biz_supplier (
  supplier_id   BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  supplier_name VARCHAR(200) NOT NULL,
  contact       VARCHAR(50) DEFAULT '',
  phone         VARCHAR(20) DEFAULT '',
  email         VARCHAR(100) DEFAULT '',
  address       VARCHAR(500) DEFAULT '',
  user_id       BIGINT DEFAULT NULL,
  status        CHAR(1) DEFAULT '0',
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  update_by     VARCHAR(64) DEFAULT '',
  update_time   DATETIME,
  remark        VARCHAR(500) DEFAULT NULL,
  PRIMARY KEY (supplier_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商';

CREATE TABLE IF NOT EXISTS biz_rfq (
  rfq_id        BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  rfq_no        VARCHAR(50) NOT NULL,
  rfq_title     VARCHAR(200) NOT NULL,
  deadline      DATETIME DEFAULT NULL,
  delivery_addr VARCHAR(500) DEFAULT '',
  status        VARCHAR(20) DEFAULT 'draft',
  remark        TEXT,
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  update_by     VARCHAR(64) DEFAULT '',
  update_time   DATETIME,
  PRIMARY KEY (rfq_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='报价请求';

CREATE TABLE IF NOT EXISTS biz_rfq_item (
  item_id       BIGINT NOT NULL AUTO_INCREMENT,
  rfq_id        BIGINT NOT NULL,
  material_id   BIGINT DEFAULT 0,
  material_name VARCHAR(200) NOT NULL,
  spec          VARCHAR(500) DEFAULT '',
  unit          VARCHAR(50) DEFAULT '',
  quantity      DECIMAL(15,4) NOT NULL,
  expected_price DECIMAL(15,4) DEFAULT NULL,
  remark        VARCHAR(500) DEFAULT '',
  PRIMARY KEY (item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='RFQ物料明细';

CREATE TABLE IF NOT EXISTS biz_rfq_supplier (
  id            BIGINT NOT NULL AUTO_INCREMENT,
  rfq_id        BIGINT NOT NULL,
  supplier_id   BIGINT NOT NULL,
  invited_time  DATETIME DEFAULT NULL,
  quoted_time   DATETIME DEFAULT NULL,
  status        VARCHAR(20) DEFAULT 'pending',
  PRIMARY KEY (id),
  UNIQUE KEY uk_rfq_supplier (rfq_id, supplier_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS biz_quotation (
  quotation_id  BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  rfq_id        BIGINT NOT NULL,
  supplier_id   BIGINT NOT NULL,
  quote_no      VARCHAR(50) DEFAULT '',
  valid_days    INT DEFAULT 30,
  delivery_days INT DEFAULT 0,
  total_amount  DECIMAL(15,4) DEFAULT 0,
  currency      VARCHAR(10) DEFAULT 'CNY',
  status        VARCHAR(20) DEFAULT 'draft',
  note          TEXT,
  submit_time   DATETIME DEFAULT NULL,
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  update_time   DATETIME,
  PRIMARY KEY (quotation_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商报价单';

CREATE TABLE IF NOT EXISTS biz_quotation_item (
  item_id       BIGINT NOT NULL AUTO_INCREMENT,
  quotation_id  BIGINT NOT NULL,
  rfq_item_id   BIGINT NOT NULL,
  material_name VARCHAR(200) DEFAULT '',
  spec          VARCHAR(500) DEFAULT '',
  unit          VARCHAR(50) DEFAULT '',
  quantity      DECIMAL(15,4) DEFAULT 0,
  unit_price    DECIMAL(15,4) NOT NULL,
  total_price   DECIMAL(15,4) DEFAULT 0,
  delivery_days INT DEFAULT 0,
  remark        VARCHAR(500) DEFAULT '',
  PRIMARY KEY (item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='报价明细';

CREATE TABLE IF NOT EXISTS biz_purchase_order (
  po_id         BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  po_no         VARCHAR(50) NOT NULL,
  rfq_id        BIGINT DEFAULT NULL,
  supplier_id   BIGINT NOT NULL,
  total_amount  DECIMAL(15,4) DEFAULT 0,
  currency      VARCHAR(10) DEFAULT 'CNY',
  delivery_addr VARCHAR(500) DEFAULT '',
  delivery_date DATE DEFAULT NULL,
  status        VARCHAR(20) DEFAULT 'draft',
  remark        TEXT,
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  update_by     VARCHAR(64) DEFAULT '',
  update_time   DATETIME,
  PRIMARY KEY (po_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购单';

CREATE TABLE IF NOT EXISTS biz_purchase_order_item (
  item_id       BIGINT NOT NULL AUTO_INCREMENT,
  po_id         BIGINT NOT NULL,
  material_id   BIGINT DEFAULT 0,
  material_name VARCHAR(200) NOT NULL,
  spec          VARCHAR(500) DEFAULT '',
  unit          VARCHAR(50) DEFAULT '',
  quantity      DECIMAL(15,4) NOT NULL,
  unit_price    DECIMAL(15,4) NOT NULL,
  total_price   DECIMAL(15,4) DEFAULT 0,
  remark        VARCHAR(500) DEFAULT '',
  PRIMARY KEY (item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='采购单明细';

CREATE TABLE IF NOT EXISTS biz_supplier_evaluation (
  eval_id       BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  po_id         BIGINT NOT NULL,
  supplier_id   BIGINT NOT NULL,
  quality_score INT DEFAULT 5,
  delivery_score INT DEFAULT 5,
  service_score INT DEFAULT 5,
  price_score   INT DEFAULT 5,
  total_score   DECIMAL(3,1) DEFAULT 5.0,
  comment       TEXT,
  evaluator     VARCHAR(64) DEFAULT '',
  eval_time     DATETIME,
  PRIMARY KEY (eval_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='供应商评价';

CREATE TABLE IF NOT EXISTS biz_order_objection (
  objection_id  BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  po_id         BIGINT NOT NULL,
  supplier_id   BIGINT NOT NULL,
  reason        TEXT NOT NULL,
  attachment    VARCHAR(500) DEFAULT '',
  status        VARCHAR(20) DEFAULT 'pending',
  resolution    TEXT,
  create_by     VARCHAR(64) DEFAULT '',
  create_time   DATETIME,
  resolve_time  DATETIME DEFAULT NULL,
  PRIMARY KEY (objection_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单异议';

CREATE TABLE IF NOT EXISTS biz_transaction (
  tx_id         BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id     BIGINT NOT NULL DEFAULT 1,
  po_id         BIGINT DEFAULT NULL,
  supplier_id   BIGINT DEFAULT NULL,
  tx_type       VARCHAR(50) DEFAULT '',
  tx_no         VARCHAR(50) DEFAULT '',
  amount        DECIMAL(15,4) DEFAULT NULL,
  currency      VARCHAR(10) DEFAULT 'CNY',
  description   TEXT,
  operator      VARCHAR(64) DEFAULT '',
  tx_time       DATETIME,
  create_time   DATETIME,
  PRIMARY KEY (tx_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='交易记录';

-- ═══════════════════════════════════════════════════════════════
-- 发货单（注：该表需手动创建，此前未包含在 DDL 中）
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE IF NOT EXISTS biz_delivery_order (
  do_id             BIGINT NOT NULL AUTO_INCREMENT,
  tenant_id         BIGINT NOT NULL DEFAULT 1,
  do_no             VARCHAR(50) NOT NULL COMMENT '发货单号',
  type              VARCHAR(20) DEFAULT NULL COMMENT '类型(supplier/client)',
  rfq_id            BIGINT DEFAULT NULL COMMENT '关联RFQ ID(client类型可为空)',
  quotation_id      BIGINT DEFAULT NULL COMMENT '关联报价单ID',
  client_quote_id   BIGINT DEFAULT NULL COMMENT '关联甲方报价单ID',
  supplier_id       BIGINT DEFAULT NULL COMMENT '供应商ID(client类型可为空)',
  total_amount      DECIMAL(15,4) DEFAULT 0 COMMENT '总金额',
  currency          VARCHAR(10) DEFAULT 'CNY',
  delivery_date     DATE DEFAULT NULL COMMENT '交货日期',
  delay_date        DATE DEFAULT NULL COMMENT '延期日期',
  actual_close_date DATE DEFAULT NULL COMMENT '实际结单日期',
  close_date_set_by VARCHAR(64) DEFAULT '' COMMENT '结单设置人',
  delivery_status   VARCHAR(20) DEFAULT 'pending' COMMENT '状态(pending/transit/history/confirmed/rejected)',
  remark            VARCHAR(500) DEFAULT NULL,
  create_by         VARCHAR(64) DEFAULT '',
  create_time       DATETIME,
  update_by         VARCHAR(64) DEFAULT '',
  update_time       DATETIME,
  PRIMARY KEY (do_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发货单';

CREATE TABLE IF NOT EXISTS biz_delivery_order_item (
  item_id       BIGINT NOT NULL AUTO_INCREMENT,
  do_id         BIGINT NOT NULL COMMENT '发货单ID',
  material_id   BIGINT DEFAULT 0,
  material_name VARCHAR(200) DEFAULT '',
  spec          VARCHAR(500) DEFAULT '',
  unit          VARCHAR(50) DEFAULT '',
  quantity      DECIMAL(15,4) DEFAULT 0,
  unit_price    DECIMAL(15,4) DEFAULT 0,
  total_price   DECIMAL(15,4) DEFAULT 0,
  remark        VARCHAR(500) DEFAULT '',
  PRIMARY KEY (item_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='发货单明细';

INSERT IGNORE INTO sys_menu(menu_id,menu_name,parent_id,order_num,path,component,query,is_frame,is_cache,menu_type,visible,status,perms,icon,create_by,create_time,update_by,update_time,remark)
VALUES
(2000,'智慧报价',0,5,'bid',NULL,NULL,1,0,'M','0','0','','#','admin',NOW(),'','',''),
(2001,'物料管理',2000,1,'material','bid/material/index',NULL,1,0,'C','0','0','bid:material:list','component','admin',NOW(),'','',''),
(2002,'供应商管理',2000,2,'supplier','bid/supplier/index',NULL,1,0,'C','0','0','bid:supplier:list','user','admin',NOW(),'','',''),
(2003,'报价请求',2000,3,'rfq','bid/rfq/index',NULL,1,0,'C','0','0','bid:rfq:list','form','admin',NOW(),'','',''),
(2004,'供应商报价',2000,4,'quotation','bid/quotation/index',NULL,1,0,'C','0','0','bid:quotation:list','money','admin',NOW(),'','',''),
(2005,'智慧比价',2000,5,'comparison','bid/comparison/index',NULL,1,0,'C','0','0','bid:comparison:list','chart','admin',NOW(),'','',''),
(2051,'比价详情',2005,1,'detail','bid/comparison/detail',NULL,1,0,'C','1','0','bid:comparison:detail','#','admin',NOW(),'','',''),
(2006,'采购单',2000,6,'purchaseorder','bid/purchaseorder/index',NULL,1,0,'C','0','0','bid:purchaseorder:list','shopping','admin',NOW(),'','',''),
(2007,'供应商评价',2000,7,'evaluation','bid/evaluation/index',NULL,1,0,'C','0','0','bid:evaluation:list','star','admin',NOW(),'','',''),
(2008,'订单异议',2000,8,'objection','bid/objection/index',NULL,1,0,'C','0','0','bid:objection:list','warning','admin',NOW(),'','',''),
(2009,'交易记录',2000,9,'transaction','bid/transaction/index',NULL,1,0,'C','0','0','bid:transaction:list','list','admin',NOW(),'','',''),
(2010,'租户管理',2000,10,'tenant','bid/tenant/index',NULL,1,0,'C','0','0','bid:tenant:list','peoples','admin',NOW(),'','','');
