USE [YL_MESDB]
GO

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

    DECLARE @today date = CONVERT(date, GETDATE());
    DECLARE @currentStart date = DATEFROMPARTS(YEAR(@today), MONTH(@today), 1);
    DECLARE @currentEnd date = DATEADD(month, 1, @currentStart);
    DECLARE @previousStart date = DATEADD(month, -1, @currentStart);
    DECLARE @previousEnd date = @currentStart;

    DECLARE @rates TABLE (
        [module] varchar(20) NOT NULL,
        [currentNumerator] decimal(18, 2) NULL,
        [currentDenominator] decimal(18, 2) NULL,
        [previousNumerator] decimal(18, 2) NULL,
        [previousDenominator] decimal(18, 2) NULL
    );

    -- Sales and purchase source views contain the exception set and total set.
    INSERT INTO @rates
    SELECT
        'sales',
        CASE WHEN currentTotal.total > currentException.total THEN currentTotal.total - currentException.total ELSE 0 END,
        currentTotal.total,
        CASE WHEN previousTotal.total > previousException.total THEN previousTotal.total - previousException.total ELSE 0 END,
        previousTotal.total
    FROM (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_m]
        WHERE [DocDate] >= @currentStart AND [DocDate] < @currentEnd
    ) currentTotal
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_z]
        WHERE [DocDate] >= @currentStart AND [DocDate] < @currentEnd
    ) currentException
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_m]
        WHERE [DocDate] >= @previousStart AND [DocDate] < @previousEnd
    ) previousTotal
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_SaleOTRate_z]
        WHERE [DocDate] >= @previousStart AND [DocDate] < @previousEnd
    ) previousException;

    INSERT INTO @rates
    SELECT
        'research',
        SUM(CASE WHEN [预计结束时间] >= @currentStart AND [预计结束时间] < @currentEnd AND [单据状态] = N'已完成' THEN 1 ELSE 0 END),
        SUM(CASE WHEN [预计结束时间] >= @currentStart AND [预计结束时间] < @currentEnd THEN 1 ELSE 0 END),
        SUM(CASE WHEN [预计结束时间] >= @previousStart AND [预计结束时间] < @previousEnd AND [单据状态] = N'已完成' THEN 1 ELSE 0 END),
        SUM(CASE WHEN [预计结束时间] >= @previousStart AND [预计结束时间] < @previousEnd THEN 1 ELSE 0 END)
    FROM [dbo].[MES_设计报工_任务]
    WHERE [预计结束时间] >= @previousStart AND [预计结束时间] < @currentEnd;

    INSERT INTO @rates
    SELECT
        'plan',
        SUM(CASE WHEN [计划开始时间] >= @currentStart AND [计划开始时间] < @currentEnd AND ISNULL([齐套], 0) = 1 THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @currentStart AND [计划开始时间] < @currentEnd THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @previousStart AND [计划开始时间] < @previousEnd AND ISNULL([齐套], 0) = 1 THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @previousStart AND [计划开始时间] < @previousEnd THEN 1 ELSE 0 END)
    FROM [dbo].[View_生产订单_MES]
    WHERE [计划开始时间] >= @previousStart AND [计划开始时间] < @currentEnd
        AND [自制件属性] LIKE N'%装配%'
        AND [物料编码] NOT LIKE N'%3420-HT2%'
        AND [物料编码] NOT LIKE N'%3420-YT2%'
        AND [物料编码] NOT LIKE N'%3420-YF2%'
        AND [物料编码] NOT LIKE N'%3420-YP2%';

    INSERT INTO @rates
    SELECT
        'purchase',
        CASE WHEN currentTotal.total > currentException.total THEN currentTotal.total - currentException.total ELSE 0 END,
        currentTotal.total,
        CASE WHEN previousTotal.total > previousException.total THEN previousTotal.total - previousException.total ELSE 0 END,
        previousTotal.total
    FROM (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate_M]
        WHERE [DocDate] >= @currentStart AND [DocDate] < @currentEnd
    ) currentTotal
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate]
        WHERE [DocDate] >= @currentStart AND [DocDate] < @currentEnd
    ) currentException
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate_M]
        WHERE [DocDate] >= @previousStart AND [DocDate] < @previousEnd
    ) previousTotal
    CROSS JOIN (
        SELECT COUNT_BIG(1) AS total
        FROM [SAP].[SBO_YL].[dbo].[SAP_MES_POOnTimeRate]
        WHERE [DocDate] >= @previousStart AND [DocDate] < @previousEnd
    ) previousException;

    INSERT INTO @rates
    SELECT
        'machining',
        SUM(CASE WHEN [计划开始时间] >= @currentStart AND [计划开始时间] < @currentEnd
            AND [开工时间] IS NOT NULL AND [开工时间] <= DATEADD(day, 1, [计划开始时间]) THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @currentStart AND [计划开始时间] < @currentEnd THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @previousStart AND [计划开始时间] < @previousEnd
            AND [开工时间] IS NOT NULL AND [开工时间] <= DATEADD(day, 1, [计划开始时间]) THEN 1 ELSE 0 END),
        SUM(CASE WHEN [计划开始时间] >= @previousStart AND [计划开始时间] < @previousEnd THEN 1 ELSE 0 END)
    FROM [dbo].[View_生产订单_MES]
    WHERE [计划开始时间] >= @previousStart AND [计划开始时间] < @currentEnd
        AND [指派对象] <> N'走手续'
        AND [指派对象] NOT LIKE N'%装配%'
        AND [指派对象] NOT IN (N'期初物料', N'打磨', N'钻床', N'电火花', N'压力测试', N'酸洗/喷漆', N'抛光', N'外协')
        AND [排产状态] = 1
        AND [订单编号] > 5000;

    ;WITH assemblyBase AS (
        SELECT
            ISNULL([预计送检日期], CASE
                WHEN [物料描述] LIKE N'%系统%' THEN DATEADD(day, 3, [钣金预达时间])
                ELSE DATEADD(day, 3, [齐套时间])
            END) AS expectedInspection,
            CASE
                WHEN ISNULL([任务状态], 0) >= 4
                    OR (ISNULL([指派数量], 0) > 0 AND ISNULL([完成数量], 0) >= ISNULL([指派数量], 0))
                THEN [修改时间]
                ELSE NULL
            END AS completionTime,
            CASE
                WHEN [物料描述] LIKE N'%系统%' AND [派工时间] IS NOT NULL THEN 1
                WHEN [物料描述] NOT LIKE N'%系统%' AND ISNULL([发料状态], 0) = 1 THEN 1
                ELSE 0
            END AS executable
        FROM [dbo].[View_生产订单_MES]
        WHERE [物料类型] = N'pit_Resource'
            AND [自制件属性] LIKE N'%装配%'
            AND [物料描述] NOT LIKE N'%软管总成%'
            AND [物料描述] NOT LIKE N'%发货部件%'
            AND ISNULL([不装配], N'') <> N'否'
    )
    INSERT INTO @rates
    SELECT
        'assembly',
        SUM(CASE WHEN expectedInspection >= @currentStart AND expectedInspection < @currentEnd AND executable = 1
            AND NOT (completionTime > expectedInspection OR (completionTime IS NULL AND expectedInspection < @today)) THEN 1 ELSE 0 END),
        SUM(CASE WHEN expectedInspection >= @currentStart AND expectedInspection < @currentEnd AND executable = 1 THEN 1 ELSE 0 END),
        SUM(CASE WHEN expectedInspection >= @previousStart AND expectedInspection < @previousEnd AND executable = 1
            AND NOT (completionTime > expectedInspection OR completionTime IS NULL) THEN 1 ELSE 0 END),
        SUM(CASE WHEN expectedInspection >= @previousStart AND expectedInspection < @previousEnd AND executable = 1 THEN 1 ELSE 0 END)
    FROM assemblyBase
    WHERE expectedInspection >= @previousStart AND expectedInspection < @currentEnd;

    ;WITH qualitySummary AS (
        SELECT
            [TaskAID],
            SUM(ISNULL([检验数量], 0)) AS inspectedQuantity,
            MAX([检测时间]) AS lastInspectionTime
        FROM [dbo].[YL_质量检验_质检记录]
        WHERE [检测类型编号] = 6 AND [TaskAID] IS NOT NULL
        GROUP BY [TaskAID]
    ), operationSummary AS (
        SELECT
            [TaskAID],
            SUM(ISNULL([操作数值], 0)) AS completedQuantity,
            MAX(CASE WHEN ISNULL([操作数值], 0) <> 0 THEN COALESCE([报工日期], [结束时间]) END) AS lastReportTime
        FROM [dbo].[YL_加工中心_操作记录表]
        WHERE ISNULL([操作类别编号], 0) IN (3, 6) AND [TaskAID] IS NOT NULL
        GROUP BY [TaskAID]
    ), qualityBase AS (
        SELECT
            o.lastReportTime,
            DATEADD(day, 2, o.lastReportTime) AS inspectionDeadline,
            o.completedQuantity,
            ISNULL(q.inspectedQuantity, 0) AS inspectedQuantity,
            q.lastInspectionTime
        FROM operationSummary o
        LEFT JOIN qualitySummary q ON q.[TaskAID] = o.[TaskAID]
        WHERE o.lastReportTime >= @previousStart AND o.lastReportTime < @currentEnd
            AND o.completedQuantity > 0
    )
    INSERT INTO @rates
    SELECT
        'quality',
        SUM(CASE WHEN lastReportTime >= @currentStart AND lastReportTime < @currentEnd
            AND ((inspectedQuantity >= completedQuantity AND lastInspectionTime <= inspectionDeadline)
                OR (inspectedQuantity < completedQuantity AND inspectionDeadline >= @today)) THEN 1 ELSE 0 END),
        SUM(CASE WHEN lastReportTime >= @currentStart AND lastReportTime < @currentEnd THEN 1 ELSE 0 END),
        SUM(CASE WHEN lastReportTime >= @previousStart AND lastReportTime < @previousEnd
            AND inspectedQuantity >= completedQuantity AND lastInspectionTime <= inspectionDeadline THEN 1 ELSE 0 END),
        SUM(CASE WHEN lastReportTime >= @previousStart AND lastReportTime < @previousEnd THEN 1 ELSE 0 END)
    FROM qualityBase;

    -- Temporary placeholder until the warehouse timely-rate formula is confirmed.
    INSERT INTO @rates
    VALUES ('warehouse', 95, 100, 95, 100);

    SELECT
        [module],
        CAST(CASE WHEN ISNULL([currentDenominator], 0) = 0 THEN 0 ELSE ISNULL([currentNumerator], 0) * 100.0 / [currentDenominator] END AS decimal(18, 2)) AS [currentRate],
        CAST(CASE WHEN ISNULL([previousDenominator], 0) = 0 THEN 0 ELSE ISNULL([previousNumerator], 0) * 100.0 / [previousDenominator] END AS decimal(18, 2)) AS [previousRate],
        ISNULL([currentNumerator], 0) AS [currentNumerator],
        ISNULL([currentDenominator], 0) AS [currentDenominator],
        ISNULL([previousNumerator], 0) AS [previousNumerator],
        ISNULL([previousDenominator], 0) AS [previousDenominator]
    FROM @rates
    ORDER BY CASE [module]
        WHEN 'sales' THEN 1
        WHEN 'research' THEN 2
        WHEN 'plan' THEN 3
        WHEN 'purchase' THEN 4
        WHEN 'machining' THEN 5
        WHEN 'assembly' THEN 6
        WHEN 'quality' THEN 7
        WHEN 'warehouse' THEN 8
        ELSE 99
    END;
END
GO
