USE [YL_MESDB];
GO

CREATE OR ALTER PROCEDURE [dbo].[设计报工_任务_删除]
    @DID int
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    DECLARE @单据状态 nvarchar(50);
    DECLARE @删除行数 int;

    BEGIN TRY
        BEGIN TRANSACTION;

        SELECT @单据状态 = [单据状态]
        FROM [dbo].[MES_设计报工_任务] WITH (UPDLOCK, HOLDLOCK)
        WHERE [DID] = @DID;

        IF @单据状态 IS NULL
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：任务不存在或已被删除' AS [message];
            RETURN;
        END

        IF EXISTS (SELECT 1 FROM [dbo].[MES_设计报工_记录] WITH (HOLDLOCK) WHERE [DID] = @DID)
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：该任务已有设计报工记录，不能删除' AS [message];
            RETURN;
        END

        IF EXISTS (SELECT 1 FROM [dbo].[MES_设计报工_校验记录] WITH (HOLDLOCK) WHERE [DID] = @DID)
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：该任务已有设计工时校验记录，不能删除' AS [message];
            RETURN;
        END

        IF @单据状态 = N'已完成'
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：任务已完成，不能删除' AS [message];
            RETURN;
        END

        IF @单据状态 <> N'待开始'
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：任务状态为' + @单据状态 + N'，不能删除' AS [message];
            RETURN;
        END

        DELETE FROM [dbo].[MES_设计报工_任务]
        WHERE [DID] = @DID;

        SET @删除行数 = @@ROWCOUNT;

        IF @删除行数 <> 1
        BEGIN
            ROLLBACK TRANSACTION;
            SELECT CAST(0 AS int) AS [result], N'删除失败：任务不存在或已被删除' AS [message];
            RETURN;
        END

        COMMIT TRANSACTION;
        SELECT CAST(1 AS int) AS [result], N'删除成功' AS [message];
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
        SELECT CAST(0 AS int) AS [result], N'删除失败：' + ERROR_MESSAGE() AS [message];
    END CATCH
END
GO
