-- 招投标信息维护：供应商明细子表、历史数据回填与菜单改名

CREATE TABLE IF NOT EXISTS `ccdi_purchase_transaction_supplier` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `purchase_id` VARCHAR(32) NOT NULL COMMENT '采购事项ID',
  `supplier_name` VARCHAR(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '供应商名称',
  `supplier_uscc` VARCHAR(18) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '供应商统一信用代码',
  `contact_person` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '供应商联系人',
  `contact_phone` VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '供应商联系电话',
  `supplier_bank_account` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '供应商银行账户',
  `is_bid_winner` TINYINT NOT NULL DEFAULT 0 COMMENT '是否中标：1-是，0-否',
  `sort_order` INT NOT NULL DEFAULT 1 COMMENT '排序',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `created_by` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '创建人',
  `updated_by` VARCHAR(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '更新人',
  PRIMARY KEY (`id`),
  KEY `idx_purchase_id` (`purchase_id`),
  KEY `idx_purchase_bid_winner` (`purchase_id`, `is_bid_winner`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='招投标供应商明细表';

INSERT INTO ccdi_purchase_transaction_supplier (
  purchase_id,
  supplier_name,
  supplier_uscc,
  contact_person,
  contact_phone,
  supplier_bank_account,
  is_bid_winner,
  sort_order,
  create_time,
  update_time,
  created_by,
  updated_by
)
SELECT
  t.purchase_id,
  t.supplier_name,
  t.supplier_uscc,
  t.contact_person,
  t.contact_phone,
  t.supplier_bank_account,
  1,
  1,
  IFNULL(t.create_time, NOW()),
  IFNULL(t.update_time, NOW()),
  t.created_by,
  t.updated_by
FROM ccdi_purchase_transaction t
LEFT JOIN ccdi_purchase_transaction_supplier s
  ON s.purchase_id = t.purchase_id
 AND s.is_bid_winner = 1
WHERE IFNULL(t.supplier_name, '') <> ''
  AND s.id IS NULL;

UPDATE sys_menu
SET menu_name = '招投标信息维护',
    remark = '招投标信息维护菜单',
    update_by = 'admin',
    update_time = NOW()
WHERE perms = 'ccdi:purchaseTransaction:list'
   OR path = 'purchaseTransaction';

UPDATE sys_menu
SET menu_name = CASE perms
    WHEN 'ccdi:purchaseTransaction:query' THEN '招投标信息查询'
    WHEN 'ccdi:purchaseTransaction:add' THEN '招投标信息新增'
    WHEN 'ccdi:purchaseTransaction:edit' THEN '招投标信息修改'
    WHEN 'ccdi:purchaseTransaction:remove' THEN '招投标信息删除'
    WHEN 'ccdi:purchaseTransaction:import' THEN '招投标信息导入'
    ELSE menu_name
END,
update_by = 'admin',
update_time = NOW()
WHERE perms IN (
  'ccdi:purchaseTransaction:query',
  'ccdi:purchaseTransaction:add',
  'ccdi:purchaseTransaction:edit',
  'ccdi:purchaseTransaction:remove',
  'ccdi:purchaseTransaction:import'
);
