
CREATE PROCEDURE [dbo].[工时统计_任务工时_查询_导出]
    @合同号 NVARCHAR(50) = NULL,
    @操作人 NVARCHAR(50) = NULL,
    @产品编码 NVARCHAR(100) = NULL,
    @工序名称 NVARCHAR(50) = NULL,
    @订单号 NVARCHAR(50) = NULL,
    @开始日期 DATE = NULL,
    @结束日期 DATE = NULL
AS
BEGIN
    SET NOCOUNT ON;

    -- 导出文件名和类型
    SELECT '任务工时统计_' + REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(19), GETDATE(), 21), ':', ''), '-', ''), ' ', '-') AS tablename, '15' AS tabletype
    
    -- 字段宽度
    SELECT 256*20 AS 合同号, 256*12 AS 订单号, 256*40 AS 产品编码, 256*25 AS 产品名称, 256*15 AS 工序名称, 
           256*12 AS 操作人, 256*12 AS 计划数量, 256*12 AS 完成数量, 256*10 AS 报工数量, 256*20 AS 开始时间, 256*20 AS 结束时间, 256*12 AS '工时(h)'
    
    -- 是否计算列
    SELECT 0 AS 合同号, 0 AS 订单号, 0 AS 产品编码, 0 AS 产品名称, 0 AS 工序名称, 
           0 AS 操作人, 0 AS 计划数量, 0 AS 完成数量, 0 AS 报工数量, 0 AS 开始时间, 0 AS 结束时间, 0 AS '工时(h)'

    -- 导出数据：每行都填满完整信息
    SELECT 
        ISNULL(订单合同号, '') AS 合同号,
        ISNULL(订单号, '') AS 订单号,
        ISNULL(产品编码, '') AS 产品编码,
        ISNULL(产品名称, '') AS 产品名称,
        ISNULL(工序名称, '') AS 工序名称,
        ISNULL(操作人, '') AS 操作人,
        CASE WHEN 计划数量 IS NULL THEN '' WHEN 计划数量 = FLOOR(计划数量) THEN CAST(CAST(计划数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(计划数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 计划数量,
        CASE WHEN 完成数量 IS NULL THEN '' WHEN 完成数量 = FLOOR(完成数量) THEN CAST(CAST(完成数量 AS INT) AS VARCHAR(20)) ELSE CAST(CAST(完成数量 AS DECIMAL(10,1)) AS VARCHAR(20)) END AS 完成数量,
        CASE WHEN 操作类别 IN ('报工', '辅助结束') THEN CAST(操作数值 AS VARCHAR(20)) ELSE '0' END AS 报工数量,
        CONVERT(VARCHAR(19), 开始时间, 120) AS 开始时间,
        CONVERT(VARCHAR(19), 结束时间, 120) AS 结束时间,
        CAST(CAST(加工工时 / 60.0 / 60.0 AS DECIMAL(10,2)) AS VARCHAR(20)) AS '工时(h)'
    FROM View_生产工时视图
    WHERE (@开始日期 IS NULL OR @开始日期 = '' OR 结束时间 >= @开始日期)
          AND (@结束日期 IS NULL OR @结束日期 = '' OR 开始时间 <= @结束日期)
      AND (@合同号 IS NULL OR @合同号 = '' OR 订单合同号 LIKE '%' + @合同号 + '%')
      AND (@操作人 IS NULL OR @操作人 = '' OR 操作人 LIKE '%' + @操作人 + '%')
      AND (@产品编码 IS NULL OR @产品编码 = '' OR 产品编码 LIKE '%' + @产品编码 + '%')
      AND (@工序名称 IS NULL OR @工序名称 = '' OR 工序名称 LIKE '%' + @工序名称 + '%')
      AND (@订单号 IS NULL OR @订单号 = '' OR 订单号 LIKE '%' + @订单号 + '%')
    ORDER BY 订单合同号, 订单号, 产品编码, 工序名称, 开始时间
END

