USE [YL_MESDB]
GO

CREATE OR ALTER PROCEDURE [dbo].[MES_Kanban_DepartmentOverview]
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @today date = CONVERT(date, GETDATE());
    DECLARE @tomorrow date = DATEADD(day, 1, @today);
    DECLARE @start date = DATEADD(day, -4, @today);
    DECLARE @monthStart date = DATEFROMPARTS(YEAR(@today), MONTH(@today), 1);

    CREATE TABLE #result (
        [module] varchar(20) NOT NULL,
        [chart] varchar(20) NOT NULL,
        [series] nvarchar(30) NOT NULL,
        [label] nvarchar(50) NOT NULL,
        [sort] int NOT NULL,
        [value] decimal(18, 2) NOT NULL,
        [extraValue] decimal(18, 2) NULL
    );

    INSERT INTO #result ([module], [chart], [series], [label], [sort], [value], [extraValue])
    SELECT 'sales', 'bar', N'任务数', category, sort, COUNT_BIG(1), NULL
    FROM (
        SELECT
            CASE
                WHEN [销售产品名称] = N'同轴阀' THEN N'同轴阀'
                WHEN [销售产品名称] = N'同轴阀组' THEN N'同轴阀组'
                WHEN [销售产品名称] LIKE N'%系统%' THEN N'系统'
                ELSE N'其他'
            END AS category,
            CASE
                WHEN [销售产品名称] = N'同轴阀' THEN 1
                WHEN [销售产品名称] = N'同轴阀组' THEN 2
                WHEN [销售产品名称] LIKE N'%系统%' THEN 3
                ELSE 4
            END AS sort
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_TransitTaskClass]
    ) source
    GROUP BY category, sort;

    INSERT INTO #result
    SELECT 'sales', 'summary', N'滞留', N'销售滞留', 1, COUNT_BIG(1), NULL
    FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleBlgDet];

    INSERT INTO #result
    SELECT
        'sales', 'rate', N'准交率', N'准交率', 1,
        CAST(CASE WHEN denominator.total = 0 THEN 0 ELSE numerator.total * 100.0 / denominator.total END AS decimal(18, 2)),
        denominator.total
    FROM (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_z]) numerator
    CROSS JOIN (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_m]) denominator;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [DocDate]) AS dt, COUNT(DISTINCT [单据编号]) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_TransitTaskClass]
        WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
        GROUP BY CONVERT(date, [DocDate])
    ), reduced AS (
        SELECT CONVERT(date, [DocDate]) AS dt, COUNT(DISTINCT [单据号]) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_BizIncDec]
        WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
        GROUP BY CONVERT(date, [DocDate])
    )
    INSERT INTO #result
    SELECT 'sales', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    ;WITH categories AS (
        SELECT
            CASE WHEN [类别] IN (N'分类一', N'分类二', N'分类三', N'分类四') THEN [类别] ELSE N'其他' END AS category,
            CASE [类别] WHEN N'分类一' THEN 1 WHEN N'分类二' THEN 2 WHEN N'分类三' THEN 3 WHEN N'分类四' THEN 4 ELSE 5 END AS sort
        FROM [dbo].[MES_设计报工_任务]
        WHERE ISNULL([单据状态], N'') <> N'已完成'
    )
    INSERT INTO #result
    SELECT 'research', 'bar', N'任务数', category, sort, COUNT_BIG(1), NULL
    FROM categories
    GROUP BY category, sort;

    INSERT INTO #result
    SELECT 'research', 'summary', N'滞留', N'研发滞留', 1, COUNT_BIG(1), NULL
    FROM [dbo].[MES_设计报工_任务]
    WHERE ISNULL([单据状态], N'') <> N'已完成'
        AND [预计结束时间] < GETDATE();

    INSERT INTO #result
    SELECT
        'research', 'rate', N'完成率', N'按期完成率', 1,
        CAST(CASE WHEN COUNT_BIG(1) = 0 THEN 0 ELSE SUM(CASE WHEN [单据状态] = N'已完成' THEN 1 ELSE 0 END) * 100.0 / COUNT_BIG(1) END AS decimal(18, 2)),
        COUNT_BIG(1)
    FROM [dbo].[MES_设计报工_任务]
    WHERE [预计结束时间] >= @monthStart AND [预计结束时间] < @tomorrow;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [创建日期]) AS dt, COUNT_BIG(1) AS total
        FROM [dbo].[MES_设计报工_任务]
        WHERE [创建日期] >= @start AND [创建日期] < @tomorrow
        GROUP BY CONVERT(date, [创建日期])
    ), reduced AS (
        SELECT CONVERT(date, [最后编辑时间]) AS dt, COUNT_BIG(1) AS total
        FROM [dbo].[MES_设计报工_任务]
        WHERE [单据状态] = N'已完成' AND [最后编辑时间] >= @start AND [最后编辑时间] < @tomorrow
        GROUP BY CONVERT(date, [最后编辑时间])
    )
    INSERT INTO #result
    SELECT 'research', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    INSERT INTO #result
    SELECT 'purchase', 'bar', N'任务数', N'申请', 1, COUNT_BIG(1), NULL
    FROM [SAP].[SBO_YL].[dbo].[SAP_MES_InTransitTask]
    UNION ALL
    SELECT 'purchase', 'bar', N'任务数', N'订单', 2, COUNT_BIG(1), NULL
    FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POAddDet];

    INSERT INTO #result
    SELECT
        'purchase', 'rate', N'及时率', N'外购及时率', 1,
        CAST(CASE WHEN denominator.total = 0 THEN 0 ELSE numerator.total * 100.0 / denominator.total END AS decimal(18, 2)),
        denominator.total
    FROM (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate]) numerator
    CROSS JOIN (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate_M]) denominator;

    INSERT INTO #result
    SELECT
        'purchase', 'summary', N'滞留', N'采购滞留', 1,
        CASE WHEN denominator.total > numerator.total THEN denominator.total - numerator.total ELSE 0 END,
        NULL
    FROM (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate]) numerator
    CROSS JOIN (SELECT COUNT_BIG(1) AS total FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate_M]) denominator;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT dt, SUM(total) AS total
        FROM (
            SELECT CONVERT(date, [DocDate]) AS dt, COUNT_BIG(1) AS total
            FROM [SAP].[SBO_YL].[dbo].[SAP_MES_PRQAddList]
            WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
            GROUP BY CONVERT(date, [DocDate])
            UNION ALL
            SELECT CONVERT(date, [DocDate]), COUNT_BIG(1)
            FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POAddDet]
            WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
            GROUP BY CONVERT(date, [DocDate])
        ) source
        GROUP BY dt
    ), reduced AS (
        SELECT dt, SUM(total) AS total
        FROM (
            SELECT CONVERT(date, [DocDate]) AS dt, COUNT_BIG(1) AS total
            FROM [SAP].[SBO_YL].[dbo].[SAP_MES_PRQClearList]
            WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
            GROUP BY CONVERT(date, [DocDate])
            UNION ALL
            SELECT CONVERT(date, [DocDate]), COUNT_BIG(1)
            FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POClearList]
            WHERE [DocDate] >= @start AND [DocDate] < @tomorrow
            GROUP BY CONVERT(date, [DocDate])
        ) source
        GROUP BY dt
    )
    INSERT INTO #result
    SELECT 'purchase', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    INSERT INTO #result
    SELECT 'machining', 'summary', N'任务', N'未完成任务', 0, COUNT(DISTINCT [TaskAID]), NULL
    FROM [dbo].[View_生产订单_MES]
    WHERE ISNULL([任务状态], 0) < 4
        AND [指派对象] <> N'外协' AND [指派对象] NOT LIKE N'%装配%';

    INSERT INTO #result
    SELECT 'machining', 'summary', N'加急', N'加急任务', 1, COUNT(DISTINCT [订单编号]), NULL
    FROM [dbo].[View_生产订单_MES]
    WHERE ISNULL([加急总数], 0) > 0 AND [指派对象] NOT LIKE N'%装配%';

    INSERT INTO #result
    SELECT 'machining', 'summary', N'滞留', N'未及时开工', 2, COUNT_BIG(1), NULL
    FROM [dbo].[View_生产订单_MES]
    WHERE [计划开始时间] < GETDATE() AND [开工时间] IS NULL
        AND [排产状态] = 1
        AND [指派对象] <> N'外协' AND [指派对象] NOT LIKE N'%装配%';

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [派工时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[View_生产订单_MES]
        WHERE [派工时间] >= @start AND [派工时间] < @tomorrow
            AND [指派对象] <> N'外协' AND [指派对象] NOT LIKE N'%装配%'
        GROUP BY CONVERT(date, [派工时间])
    ), reduced AS (
        SELECT CONVERT(date, [修改时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[View_生产订单_MES]
        WHERE [修改时间] >= @start AND [修改时间] < @tomorrow
            AND ISNULL([任务状态], 0) = 4
            AND [指派对象] <> N'外协' AND [指派对象] NOT LIKE N'%装配%'
        GROUP BY CONVERT(date, [修改时间])
    )
    INSERT INTO #result
    SELECT 'machining', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [派工时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[View_生产订单_MES]
        WHERE [派工时间] >= @start AND [派工时间] < @tomorrow
            AND [自制件属性] LIKE N'%装配%'
        GROUP BY CONVERT(date, [派工时间])
    ), reduced AS (
        SELECT CONVERT(date, [修改时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[View_生产订单_MES]
        WHERE [修改时间] >= @start AND [修改时间] < @tomorrow
            AND [自制件属性] LIKE N'%装配%'
            AND ISNULL([指派数量], 0) > 0
            AND ISNULL([完成数量], 0) >= ISNULL([指派数量], 0)
        GROUP BY CONVERT(date, [修改时间])
    )
    INSERT INTO #result
    SELECT 'assembly', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [开始时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[YL_加工中心_操作记录表]
        WHERE [开始时间] >= @start AND [开始时间] < @tomorrow
            AND [操作类别] IN (N'报工', N'辅助结束')
        GROUP BY CONVERT(date, [开始时间])
    ), reduced AS (
        SELECT CONVERT(date, [检测时间]) AS dt, COUNT(DISTINCT [TaskAID]) AS total
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE [检测时间] >= @start AND [检测时间] < @tomorrow
        GROUP BY CONVERT(date, [检测时间])
    )
    INSERT INTO #result
    SELECT 'quality', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    ;WITH dates AS (
        SELECT DATEADD(day, number, @start) AS dt, number + 1 AS sort
        FROM (VALUES (0), (1), (2), (3), (4)) source(number)
    ), added AS (
        SELECT CONVERT(date, [doc_date]) AS dt, COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[UBT_MES_DP_receipttask_material_2Days]
        WHERE [doc_date] >= @start AND [doc_date] < @tomorrow
        GROUP BY CONVERT(date, [doc_date])
    ), reduced AS (
        SELECT dt, SUM(total) AS total
        FROM (
            SELECT TRY_CONVERT(date, [拣配日期]) AS dt, COUNT_BIG(1) AS total
            FROM [SAP].[SBO_YL].[dbo].[UBT_MES_DP_OpenOPKL_material_101]
            WHERE TRY_CONVERT(date, [拣配日期]) >= @start AND TRY_CONVERT(date, [拣配日期]) < @tomorrow
            GROUP BY TRY_CONVERT(date, [拣配日期])
            UNION ALL
            SELECT TRY_CONVERT(date, [拣配日期]), COUNT_BIG(1)
            FROM [SAP].[SBO_YL].[dbo].[UBT_MES_DP_OpenOPKL_material_103]
            WHERE TRY_CONVERT(date, [拣配日期]) >= @start AND TRY_CONVERT(date, [拣配日期]) < @tomorrow
            GROUP BY TRY_CONVERT(date, [拣配日期])
        ) source
        GROUP BY dt
    )
    INSERT INTO #result
    SELECT 'warehouse', 'trend', N'增减', CONVERT(char(10), dates.dt, 120), dates.sort,
        ISNULL(added.total, 0), ISNULL(reduced.total, 0)
    FROM dates
    LEFT JOIN added ON added.dt = dates.dt
    LEFT JOIN reduced ON reduced.dt = dates.dt;

    INSERT INTO #result
    VALUES ('warehouse', 'rate', N'及时率', N'及时率', 1, 95, NULL);

    SELECT [module], [chart], [series], [label], [sort], [value], [extraValue]
    FROM #result
    ORDER BY
        CASE [module]
            WHEN 'sales' THEN 1
            WHEN 'research' THEN 2
            WHEN 'purchase' THEN 3
            WHEN 'machining' THEN 4
            WHEN 'assembly' THEN 5
            WHEN 'quality' THEN 6
            WHEN 'warehouse' THEN 7
            ELSE 99
        END,
        [chart], [sort];
END
GO
