-- v4.0.18：门店多收款银行账户（列表 + 默认账户）

CREATE TABLE IF NOT EXISTS `store_bank_account` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `store_id` BIGINT UNSIGNED NOT NULL,
  `bank_account_name` VARCHAR(64) NOT NULL,
  `bank_account_no` VARCHAR(32) NOT NULL,
  `bank_branch` VARCHAR(128) NULL,
  `is_default` TINYINT NOT NULL DEFAULT 0,
  `status` ENUM('ACTIVE','DISABLED') NOT NULL DEFAULT 'ACTIVE',
  `sort_order` INT NOT NULL DEFAULT 0,
  `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  `updated_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
  PRIMARY KEY (`id`),
  KEY `idx_store_bank_account_store_status` (`store_id`, `status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='门店收款银行账户';

-- 回填：按门店主账号（is_primary=1，缺失则取最早绑定账号）的收款字段，为每店生成一条默认账户
INSERT INTO `store_bank_account`
  (`store_id`, `bank_account_name`, `bank_account_no`, `bank_branch`, `is_default`, `status`, `sort_order`)
SELECT
  b.`store_id`,
  a.`bank_account_name`,
  a.`bank_account_no`,
  a.`bank_branch`,
  1,
  'ACTIVE',
  0
FROM `store_account_store` b
JOIN `store_account` a ON a.`id` = b.`store_account_id`
WHERE a.`bank_account_name` IS NOT NULL
  AND TRIM(a.`bank_account_name`) <> ''
  AND a.`bank_account_no` IS NOT NULL
  AND TRIM(a.`bank_account_no`) <> ''
  AND b.`store_account_id` = (
    SELECT b2.`store_account_id`
    FROM `store_account_store` b2
    JOIN `store_account` a2 ON a2.`id` = b2.`store_account_id`
    WHERE b2.`store_id` = b.`store_id`
    ORDER BY (a2.`is_primary` = 1) DESC, a2.`id` ASC
    LIMIT 1
  )
ON DUPLICATE KEY UPDATE `updated_at` = `updated_at`;
