SET NAMES utf8mb4;

SET @payment_manager_menu_id := (
  SELECT `id` FROM `sys_menu` WHERE `alias` = 'PaymentManager' LIMIT 1
);
SET @payment_manager_menu_id := IFNULL(@payment_manager_menu_id, 1700000600);

INSERT INTO `sys_menu` (
  `id`, `parent_id`, `menu_name`, `path`, `menu_type`, `icon`, `create_user`, `update_user`,
  `sort`, `status`, `router`, `alias`
)
SELECT
  @payment_manager_menu_id, 0, '支付管理', '/payment/manager', 1, 'lucide:credit-card',
  '0', '0', 193, 0, '/payment/manager', 'PaymentManager'
WHERE NOT EXISTS (
  SELECT 1 FROM `sys_menu` WHERE `alias` = 'PaymentManager'
);

UPDATE `sys_menu`
SET
  `parent_id` = 0,
  `menu_name` = '支付管理',
  `path` = '/payment/manager',
  `menu_type` = 1,
  `icon` = 'lucide:credit-card',
  `create_user` = '0',
  `update_user` = '0',
  `sort` = 193,
  `status` = 0,
  `router` = '/payment/manager'
WHERE `alias` = 'PaymentManager';

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `menu_name` = '订单列表',
  `path` = 'operate/order-details',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = 1,
  `status` = 0,
  `router` = 'payment/manager/order/list'
WHERE `alias` = 'OrderDetails';

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `path` = 'operate/pay-country',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = CASE `alias` WHEN 'PayCountry' THEN 2 ELSE 7 END,
  `status` = 0,
  `router` = 'payment/manager/country'
WHERE `alias` IN ('PayCountry', 'openPayCountry');

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `path` = 'operate/region-relation',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = 3,
  `status` = 0,
  `router` = 'payment/manager/region/relation'
WHERE `alias` = 'RegionRelation';

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `path` = 'operate/pay-application',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = 4,
  `status` = 0,
  `router` = 'payment/manager/application'
WHERE `alias` = 'PayApplication';

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `path` = 'operate/pay-factory',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = 5,
  `status` = 0,
  `router` = 'payment/manager/factory'
WHERE `alias` = 'PayFactory';

UPDATE `sys_menu`
SET
  `parent_id` = @payment_manager_menu_id,
  `path` = 'operate/pay-channel',
  `menu_type` = 2,
  `icon` = 'form',
  `sort` = 6,
  `status` = 0,
  `router` = 'payment/manager/channel'
WHERE `alias` = 'PayChannel';

INSERT INTO `sys_role_menu` (`role_id`, `menu_id`)
SELECT DISTINCT source.`role_id`, @payment_manager_menu_id
FROM `sys_role_menu` source
JOIN `sys_menu` child_menu ON child_menu.`id` = source.`menu_id`
WHERE child_menu.`alias` IN (
  'OrderDetails',
  'PayCountry',
  'openPayCountry',
  'RegionRelation',
  'PayApplication',
  'PayFactory',
  'PayChannel'
)
  AND NOT EXISTS (
    SELECT 1 FROM `sys_role_menu` target
    WHERE target.`role_id` = source.`role_id`
      AND target.`menu_id` = @payment_manager_menu_id
  );
