/*
    SQL Server 2012 兼容脚本（数据库兼容级别 110）。
    不使用 DROP IF EXISTS、STRING_AGG、STRING_SPLIT、CREATE OR ALTER 等 SQL Server 2012 之后新增的语法；
    错误重抛统一使用 RAISERROR。
*/
SET XACT_ABORT ON;

BEGIN TRY
BEGIN TRANSACTION;

DECLARE @Sql NVARCHAR(1000);

/* 焊接任务单增加班组。 */
IF COL_LENGTH('dbo.HJGL_WeldTask', 'TeamGroupId') IS NULL
    ALTER TABLE dbo.HJGL_WeldTask ADD TeamGroupId NVARCHAR(50) NULL;

/* 防腐委托改为关联任务单或热处理报告来源。 */
IF COL_LENGTH('dbo.Tw_AntiCorrosionTrust', 'WeldTaskCode') IS NULL
    ALTER TABLE dbo.Tw_AntiCorrosionTrust ADD WeldTaskCode NVARCHAR(200) NULL;

IF COL_LENGTH('dbo.Tw_AntiCorrosionTrust', 'HotProessTrustId') IS NULL
    ALTER TABLE dbo.Tw_AntiCorrosionTrust ADD HotProessTrustId NVARCHAR(50) NULL;

/*
    新防腐委托仅使用焊接任务单或热处理委托作为来源。
    旧来源列不再写入；该表尚无业务数据，无需迁移或回填旧来源。
*/
IF COL_LENGTH('dbo.Tw_AntiCorrosionTrust', 'OutputMasterId') IS NOT NULL
   AND EXISTS
   (
       SELECT 1
       FROM sys.columns
       WHERE object_id = OBJECT_ID('dbo.Tw_AntiCorrosionTrust')
         AND name = 'OutputMasterId'
         AND is_nullable = 0
   )

DROP INDEX UX_Tw_AntiCorrosionTrust_OutputMasterId ON SGGLDB_SHJ.dbo.Tw_AntiCorrosionTrust;


BEGIN
    ALTER TABLE dbo.Tw_AntiCorrosionTrust
        ALTER COLUMN OutputMasterId NVARCHAR(50) NULL;
END;

IF COL_LENGTH('dbo.Tw_AntiCorrosionTrustDetail', 'IsPostWeld') IS NULL
BEGIN
    ALTER TABLE dbo.Tw_AntiCorrosionTrustDetail
        ADD IsPostWeld BIT NOT NULL
            CONSTRAINT DF_Tw_AntiCorrosionTrustDetail_IsPostWeld DEFAULT (0);
END; 

/* 下料检测增加坡口加工类型。 */
IF COL_LENGTH('dbo.HJGL_PreWeldCuttingCheck', 'GrooveProcessType') IS NULL
    ALTER TABLE dbo.HJGL_PreWeldCuttingCheck ADD GrooveProcessType NVARCHAR(100) NULL;

/* 焊缝外观检测承接原组对记录中不属于组对工序的字段。 */
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'WeldReinforcement') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD WeldReinforcement DECIMAL(18,2) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'WeldHeight') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD WeldHeight DECIMAL(18,2) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'WeldWidth') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD WeldWidth DECIMAL(18,2) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'SurfaceDefect') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD SurfaceDefect NVARCHAR(500) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'PreheatTemperature') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD PreheatTemperature DECIMAL(18,2) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'InterpassTemperature') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD InterpassTemperature DECIMAL(18,2) NULL;
IF COL_LENGTH('dbo.HJGL_WeldAppearanceCheck', 'CheckCode') IS NULL
    ALTER TABLE dbo.HJGL_WeldAppearanceCheck ADD CheckCode NVARCHAR(200) NULL;

/* 焊接日报增加班组、专工两级审核留痕。 */
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'TeamAuditMan') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD TeamAuditMan NVARCHAR(50) NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'TeamAuditDate') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD TeamAuditDate DATETIME NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'ProfessionalAuditMan') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD ProfessionalAuditMan NVARCHAR(50) NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'ProfessionalAuditDate') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD ProfessionalAuditDate DATETIME NULL;

/* 焊接日报待审核阶段保存实际工艺快照，专工审核后再回写焊口。 */
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'WeldingMethodId') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD WeldingMethodId NVARCHAR(50) NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'WeldTypeId') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD WeldTypeId NVARCHAR(50) NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'WeldingWire') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD WeldingWire NVARCHAR(50) NULL;
IF COL_LENGTH('dbo.HJGL_WeldingDailyTempDetail', 'WeldingRod') IS NULL
    ALTER TABLE dbo.HJGL_WeldingDailyTempDetail ADD WeldingRod NVARCHAR(50) NULL;

/* 历史待审核记录按焊口当前工艺值补齐，保证升级后查询和审核行为一致。 */
SET @Sql = N'
UPDATE temp
   SET WeldingMethodId = COALESCE(temp.WeldingMethodId, joint.WeldingMethodId),
       WeldTypeId = COALESCE(temp.WeldTypeId, joint.WeldTypeId),
       WeldingWire = COALESCE(temp.WeldingWire, joint.WeldingWire),
       WeldingRod = COALESCE(temp.WeldingRod, joint.WeldingRod)
  FROM dbo.HJGL_WeldingDailyTempDetail temp
  INNER JOIN dbo.HJGL_WeldJoint joint ON joint.WeldJointId = temp.WeldJointId
 WHERE temp.WeldingMethodId IS NULL
    OR temp.WeldTypeId IS NULL
    OR temp.WeldingWire IS NULL
    OR temp.WeldingRod IS NULL;';
EXEC sys.sp_executesql @Sql;

/*
    为本次新增字段补充数据库注释。
    字段已存在时更新 MS_Description，不存在注释时新增，确保升级脚本可重复执行。
*/
DECLARE @ColumnComments TABLE
(
    TableName SYSNAME NOT NULL,
    ColumnName SYSNAME NOT NULL,
    ColumnDescription NVARCHAR(500) NOT NULL,
    SortIndex INT NOT NULL
);

INSERT INTO @ColumnComments (TableName, ColumnName, ColumnDescription, SortIndex)
SELECT N'HJGL_WeldTask', N'TeamGroupId', N'班组ID', 1 UNION ALL
SELECT N'Tw_AntiCorrosionTrust', N'WeldTaskCode', N'来源焊接任务单编码', 2 UNION ALL
SELECT N'Tw_AntiCorrosionTrust', N'HotProessTrustId', N'来源热处理委托ID', 3 UNION ALL
SELECT N'Tw_AntiCorrosionTrustDetail', N'IsPostWeld', N'是否焊后防腐：0-否，1-是', 4 UNION ALL
SELECT N'HJGL_PreWeldCuttingCheck', N'GrooveProcessType', N'坡口加工类型', 5 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'WeldReinforcement', N'焊缝余高', 6 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'WeldHeight', N'焊缝高度', 7 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'WeldWidth', N'焊缝宽度', 8 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'SurfaceDefect', N'表面缺陷', 9 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'PreheatTemperature', N'预热温度', 10 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'InterpassTemperature', N'层间温度', 11 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'TeamAuditMan', N'班组审核人ID', 12 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'TeamAuditDate', N'班组审核时间', 13 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'ProfessionalAuditMan', N'专工审核人ID', 14 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'ProfessionalAuditDate', N'专工审核时间', 15 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'WeldingMethodId', N'待审核焊接方法ID，专工审核后回写焊口', 16 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'WeldTypeId', N'待审核焊缝类型ID，专工审核后回写焊口', 17 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'WeldingWire', N'待审核焊丝ID，专工审核后回写焊口', 18 UNION ALL
SELECT N'HJGL_WeldingDailyTempDetail', N'WeldingRod', N'待审核焊条ID，专工审核后回写焊口', 19 UNION ALL
SELECT N'HJGL_WeldAppearanceCheck', N'CheckCode', N'焊缝外观检测编号，格式：FCC-单位工程名称-yyyyMMdd', 20;

DECLARE @CommentTableName SYSNAME;
DECLARE @CommentColumnName SYSNAME;
DECLARE @ColumnDescription NVARCHAR(500);

DECLARE ColumnComments CURSOR LOCAL FAST_FORWARD FOR
    SELECT TableName, ColumnName, ColumnDescription
    FROM @ColumnComments
    ORDER BY SortIndex;
OPEN ColumnComments;
FETCH NEXT FROM ColumnComments INTO @CommentTableName, @CommentColumnName, @ColumnDescription;
WHILE @@FETCH_STATUS = 0
BEGIN
    IF COL_LENGTH(N'dbo.' + @CommentTableName, @CommentColumnName) IS NOT NULL
    BEGIN
        IF EXISTS
        (
            SELECT 1
            FROM sys.extended_properties ep
            INNER JOIN sys.columns c
                ON c.object_id = ep.major_id
               AND c.column_id = ep.minor_id
            WHERE ep.class = 1
              AND ep.name = N'MS_Description'
              AND ep.major_id = OBJECT_ID(N'dbo.' + @CommentTableName)
              AND c.name = @CommentColumnName
        )
        BEGIN
            EXEC sys.sp_updateextendedproperty
                @name = N'MS_Description',
                @value = @ColumnDescription,
                @level0type = N'SCHEMA', @level0name = N'dbo',
                @level1type = N'TABLE', @level1name = @CommentTableName,
                @level2type = N'COLUMN', @level2name = @CommentColumnName;
        END
        ELSE
        BEGIN
            EXEC sys.sp_addextendedproperty
                @name = N'MS_Description',
                @value = @ColumnDescription,
                @level0type = N'SCHEMA', @level0name = N'dbo',
                @level1type = N'TABLE', @level1name = @CommentTableName,
                @level2type = N'COLUMN', @level2name = @CommentColumnName;
        END;
    END;

    FETCH NEXT FROM ColumnComments INTO @CommentTableName, @CommentColumnName, @ColumnDescription;
END;
CLOSE ColumnComments;
DEALLOCATE ColumnComments;

/* 原有已审核记录直接视为两级审核完成，旧审核信息回填到专工审核。 */
UPDATE dbo.HJGL_WeldingDailyTempDetail
   SET AuditState = 2,
       ProfessionalAuditMan = COALESCE(ProfessionalAuditMan, AuditMan),
       ProfessionalAuditDate = COALESCE(ProfessionalAuditDate, AuditDate)
 WHERE AuditState = 1;

/* 组对记录只保留组对工序字段。 */
IF EXISTS (SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID('dbo.HJGL_PreWeldFitupCheck') AND name = 'FK_PreWeldFitupCheck_GrooveType')
    ALTER TABLE dbo.HJGL_PreWeldFitupCheck DROP CONSTRAINT FK_PreWeldFitupCheck_GrooveType;

DECLARE @FitupColumn SYSNAME;
DECLARE @FitupIndex SYSNAME;
DECLARE @DefaultConstraint SYSNAME;
DECLARE @FitupColumns TABLE
(
    ColumnName SYSNAME NOT NULL,
    SortIndex INT NOT NULL
);

/* 使用 SQL Server 2012 支持的 UNION ALL 初始化待删除字段，避免依赖高版本语法。 */
INSERT INTO @FitupColumns (ColumnName, SortIndex)
SELECT N'GrooveTypeId', 1 UNION ALL
SELECT N'GrooveProcessType', 2 UNION ALL
SELECT N'GrooveAngle', 3 UNION ALL
SELECT N'WeldReinforcement', 4 UNION ALL
SELECT N'WeldHeight', 5 UNION ALL
SELECT N'WeldWidth', 6 UNION ALL
SELECT N'SurfaceDefect', 7;

DECLARE FitupColumns CURSOR LOCAL FAST_FORWARD FOR
    SELECT ColumnName
    FROM @FitupColumns
    ORDER BY SortIndex;
OPEN FitupColumns;
FETCH NEXT FROM FitupColumns INTO @FitupColumn;
WHILE @@FETCH_STATUS = 0
BEGIN
    IF COL_LENGTH('dbo.HJGL_PreWeldFitupCheck', @FitupColumn) IS NOT NULL
    BEGIN
        WHILE 1 = 1
        BEGIN
            SET @FitupIndex = NULL;
            SELECT TOP (1) @FitupIndex = i.name
            FROM sys.indexes i
            INNER JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id
            INNER JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id
            WHERE i.object_id = OBJECT_ID('dbo.HJGL_PreWeldFitupCheck') AND c.name = @FitupColumn
              AND i.is_primary_key = 0 AND i.is_unique_constraint = 0;
            IF @FitupIndex IS NULL BREAK;
            SET @Sql = N'DROP INDEX ' + QUOTENAME(@FitupIndex) + N' ON dbo.HJGL_PreWeldFitupCheck';
            EXEC sys.sp_executesql @Sql;
        END;

        SET @DefaultConstraint = NULL;
        SELECT @DefaultConstraint = dc.name
        FROM sys.default_constraints dc
        INNER JOIN sys.columns c ON c.object_id = dc.parent_object_id AND c.column_id = dc.parent_column_id
        WHERE dc.parent_object_id = OBJECT_ID('dbo.HJGL_PreWeldFitupCheck') AND c.name = @FitupColumn;
        IF @DefaultConstraint IS NOT NULL
        BEGIN
            SET @Sql = N'ALTER TABLE dbo.HJGL_PreWeldFitupCheck DROP CONSTRAINT ' + QUOTENAME(@DefaultConstraint);
            EXEC sys.sp_executesql @Sql;
        END;
        SET @Sql = N'ALTER TABLE dbo.HJGL_PreWeldFitupCheck DROP COLUMN ' + QUOTENAME(@FitupColumn);
        EXEC sys.sp_executesql @Sql;
    END;
    FETCH NEXT FROM FitupColumns INTO @FitupColumn;
END;
CLOSE FitupColumns;
DEALLOCATE FitupColumns;

COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0
        ROLLBACK TRANSACTION;

    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT @ErrorMessage = ERROR_MESSAGE(),
           @ErrorSeverity = ERROR_SEVERITY(),
           @ErrorState = ERROR_STATE();

    /* SQL Server 2012 使用 RAISERROR 重新抛出原始错误。 */
    RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
END CATCH;
