-- 企业微信菜单：新增「问诊列表」H5 页面
-- 位置：企业微信 > 问诊列表，与「诊单」「业务订单」同级
-- 前端地址：/admin/wx/appointment?

SET @qywx_pid := (
    SELECT zhend.`pid`
    FROM `zyt_system_menu` zhend
    WHERE zhend.`name` = '诊单'
      AND zhend.`pid` > 0
      AND EXISTS (
          SELECT 1
          FROM `zyt_system_menu` orders
          WHERE orders.`pid` = zhend.`pid`
            AND orders.`name` = '业务订单'
      )
    ORDER BY id ASC
    LIMIT 1
);

SET @sort_no := (
    SELECT IFNULL(MAX(`sort`), 0) + 1
    FROM `zyt_system_menu`
    WHERE `pid` = @qywx_pid
);

-- 若之前执行过旧版 SQL（如 paths = wenzhen / patient），先修正为当前内部路由。
UPDATE `zyt_system_menu`
SET
    `name` = '问诊列表',
    `perms` = 'doctor.appointment/lists',
    `paths` = 'appointment',
    `component` = 'tcm/appointment/list_h5',
    `is_show` = 1,
    `is_disable` = 0,
    `update_time` = UNIX_TIMESTAMP()
WHERE @qywx_pid IS NOT NULL
  AND `pid` = @qywx_pid
  AND (
      `component` = 'tcm/appointment/list_h5'
      OR `paths` IN ('wenzhen', 'patient', 'appointment')
      OR `name` IN ('患者列表', '问诊列表')
  );

INSERT INTO `zyt_system_menu` (
    `pid`, `type`, `name`, `icon`, `sort`, `perms`, `paths`, `component`,
    `selected`, `params`, `is_cache`, `is_show`, `is_disable`, `create_time`, `update_time`
)
SELECT
    @qywx_pid,
    'C',
    '问诊列表',
    '',
    @sort_no,
    'doctor.appointment/lists',
    'appointment',
    'tcm/appointment/list_h5',
    '',
    '',
    0,
    1,
    0,
    UNIX_TIMESTAMP(),
    UNIX_TIMESTAMP()
FROM DUAL
WHERE @qywx_pid IS NOT NULL
  AND NOT EXISTS (
      SELECT 1
      FROM `zyt_system_menu`
      WHERE `pid` = @qywx_pid
        AND (`paths` = 'appointment' OR `component` = 'tcm/appointment/list_h5')
  );
