-- 将 生成出库任务 菜单挂载到：作业流程
-- 说明：执行本脚本后，请在“角色授权”里给对应角色勾选新菜单和“查看”权限。

SET @wrk_batch_out_parent_id := (
  SELECT id
  FROM sys_resource
  WHERE code = 'workFlow' AND level = 1
  ORDER BY id
  LIMIT 1
);

SET @wrk_batch_out_sort := COALESCE(
  (
    SELECT MAX(COALESCE(sort, 0)) + 1
    FROM sys_resource
    WHERE resource_id = @wrk_batch_out_parent_id
      AND level = 2
  ),
  1
);

INSERT INTO sys_resource(code, name, resource_id, level, sort, status)
SELECT 'wrkBatchOut/wrkBatchOut.html', '生成出库任务', @wrk_batch_out_parent_id, 2, @wrk_batch_out_sort, 1
FROM dual
WHERE @wrk_batch_out_parent_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1
    FROM sys_resource
    WHERE code = 'wrkBatchOut/wrkBatchOut.html' AND level = 2
  );

UPDATE sys_resource
SET name = '生成出库任务',
    resource_id = @wrk_batch_out_parent_id,
    level = 2,
    sort = @wrk_batch_out_sort,
    status = 1
WHERE code = 'wrkBatchOut/wrkBatchOut.html' AND level = 2;

SET @wrk_batch_out_id := (
  SELECT id
  FROM sys_resource
  WHERE code = 'wrkBatchOut/wrkBatchOut.html' AND level = 2
  ORDER BY id
  LIMIT 1
);

INSERT INTO sys_resource(code, name, resource_id, level, sort, status)
SELECT 'wrkBatchOut/wrkBatchOut.html#view', '查看', @wrk_batch_out_id, 3, 1, 1
FROM dual
WHERE @wrk_batch_out_id IS NOT NULL
  AND NOT EXISTS (
    SELECT 1
    FROM sys_resource
    WHERE code = 'wrkBatchOut/wrkBatchOut.html#view' AND level = 3
  );

UPDATE sys_resource
SET name = '查看',
    resource_id = @wrk_batch_out_id,
    level = 3,
    sort = 1,
    status = 1
WHERE code = 'wrkBatchOut/wrkBatchOut.html#view' AND level = 3;

SELECT id, code, name, resource_id, level, sort, status
FROM sys_resource
WHERE code IN (
  'wrkBatchOut/wrkBatchOut.html',
  'wrkBatchOut/wrkBatchOut.html#view'
)
ORDER BY level, sort, id;
