import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
import { z } from '@hono/zod-openapi';
import { AppDataSource, ErrorSchema, parseWithAwait } from '@d8d/shared-utils';
import { authMiddleware } from '@d8d/auth-module';
import { AuthContext } from '@d8d/shared-types';
import { OrderService } from '../services/order.service';
import {
  EmploymentOrderSchema,
  CreateOrderSchema,
  UpdateOrderSchema,
  QueryOrderSchema,
  BatchAddPersonsSchema,
  CreateOrderPersonAssetSchema,
  QueryOrderPersonAssetSchema,
  UpdatePersonWorkStatusSchema
} from '../schemas/order.schema';
import { OrderStatus, WorkStatus } from '@d8d/allin-enums';
// FileSchema导入已不再需要，使用简化的SimpleFileSchema

// 简化的文件schema，用于订单资产查询
const SimpleFileSchema = z.object({
  id: z.number().int().positive().openapi({
    description: '文件ID',
    example: 1
  }),
  name: z.string().max(255).openapi({
    description: '文件名称',
    example: '项目计划书.pdf'
  }),
  type: z.string().max(50).nullable().openapi({
    description: '文件类型',
    example: 'application/pdf'
  }),
  size: z.number().int().positive().nullable().openapi({
    description: '文件大小，单位字节',
    example: 102400
  }),
  path: z.string().max(512).openapi({
    description: '文件存储路径',
    example: '/uploads/documents/2023/project-plan.pdf'
  }),
  fullUrl: z.string().optional().openapi({
    description: '完整文件访问URL',
    example: 'https://minio.example.com/d8dai/uploads/documents/2023/project-plan.pdf'
  }),
  description: z.string().nullable().openapi({
    description: '文件描述',
    example: '2023年度项目计划书'
  }),
  uploadTime: z.coerce.date().openapi({
    description: '上传时间',
    example: '2023-01-15T10:30:00Z'
  })
});

// 创建订单路由
const createOrderRoute = createRoute({
  method: 'post',
  path: '/create',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateOrderSchema }
      }
    }
  },
  responses: {
    200: {
      description: '订单创建成功',
      content: {
        'application/json': { schema: EmploymentOrderSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建订单失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新订单路由
const updateOrderRoute = createRoute({
  method: 'put',
  path: '/update/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: UpdateOrderSchema }
      }
    }
  },
  responses: {
    200: {
      description: '订单更新成功',
      content: {
        'application/json': { schema: EmploymentOrderSchema }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '更新订单失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除订单路由
const deleteOrderRoute = createRoute({
  method: 'delete',
  path: '/delete/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '订单删除成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除订单失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 分页查询订单路由
const getAllOrdersRoute = createRoute({
  method: 'get',
  path: '/list',
  middleware: [authMiddleware],
  request: {
    query: QueryOrderSchema
  },
  responses: {
    200: {
      description: '获取订单列表成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(EmploymentOrderSchema).openapi({ description: '订单列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取订单列表失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 获取单个订单详情路由
const getOrderByIdRoute = createRoute({
  method: 'get',
  path: '/detail/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '获取订单详情成功',
      content: {
        'application/json': { schema: EmploymentOrderSchema.nullable() }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '获取订单详情失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 激活订单路由
const activateOrderRoute = createRoute({
  method: 'post',
  path: '/activate/{orderId}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      orderId: z.coerce.number().int().positive().openapi({
        param: { name: 'orderId', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '订单激活成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误或订单状态不符合要求',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '激活订单失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 关闭订单路由
const closeOrderRoute = createRoute({
  method: 'post',
  path: '/close/{orderId}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      orderId: z.coerce.number().int().positive().openapi({
        param: { name: 'orderId', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    })
  },
  responses: {
    200: {
      description: '订单关闭成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' })
          })
        }
      }
    },
    400: {
      description: '参数错误或订单状态不符合要求',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '关闭订单失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 批量添加人员到订单路由
const batchAddPersonsRoute = createRoute({
  method: 'post',
  path: '/{orderId}/persons/batch',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      orderId: z.coerce.number().int().positive().openapi({
        param: { name: 'orderId', in: 'path' },
        example: 1,
        description: '订单ID'
      })
    }),
    body: {
      content: {
        'application/json': { schema: BatchAddPersonsSchema }
      }
    }
  },
  responses: {
    200: {
      description: '批量添加人员成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' }),
            message: z.string().openapi({ description: '操作结果消息' }),
            addedCount: z.number().int().openapi({ description: '实际添加的人员数量' })
          })
        }
      }
    },
    400: {
      description: '参数错误或订单状态不符合要求',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '批量添加人员失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 创建订单人员资产路由
const createOrderPersonAssetRoute = createRoute({
  method: 'post',
  path: '/assets/create',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: CreateOrderPersonAssetSchema }
      }
    }
  },
  responses: {
    200: {
      description: '订单人员资产创建成功',
      content: {
        'application/json': { schema: z.object({
          id: z.number().int().openapi({ description: '资产ID' }),
          orderId: z.number().int().openapi({ description: '订单ID' }),
          personId: z.number().int().openapi({ description: '人员ID' }),
          assetType: z.string().openapi({ description: '资产类型' }),
          assetFileType: z.string().openapi({ description: '资产文件类型' }),
          fileId: z.number().int().openapi({ description: '文件ID' }),
          relatedTime: z.coerce.date().openapi({ description: '关联时间' }),
          createTime: z.coerce.date().openapi({ description: '创建时间' }),
          updateTime: z.coerce.date().openapi({ description: '更新时间' })
        }) }
      }
    },
    400: {
      description: '参数错误或文件不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单或人员不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '创建订单人员资产失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 查询订单人员资产路由
const queryOrderPersonAssetRoute = createRoute({
  method: 'get',
  path: '/assets/query',
  middleware: [authMiddleware],
  request: {
    query: QueryOrderPersonAssetSchema
  },
  responses: {
    200: {
      description: '查询订单人员资产成功',
      content: {
        'application/json': {
          schema: z.object({
            data: z.array(z.object({
              id: z.number().int().openapi({ description: '资产ID' }),
              orderId: z.number().int().openapi({ description: '订单ID' }),
              personId: z.number().int().openapi({ description: '人员ID' }),
              assetType: z.string().openapi({ description: '资产类型' }),
              assetFileType: z.string().openapi({ description: '资产文件类型' }),
              fileId: z.number().int().openapi({ description: '文件ID' }),
              file: SimpleFileSchema.optional().openapi({ description: '文件信息' }),
              relatedTime: z.coerce.date().openapi({ description: '关联时间' }),
              createTime: z.coerce.date().openapi({ description: '创建时间' }),
              updateTime: z.coerce.date().openapi({ description: '更新时间' })
            })).openapi({ description: '资产列表' }),
            total: z.number().int().openapi({ description: '总记录数' })
          })
        }
      }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '查询订单人员资产失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 删除订单人员资产路由
const deleteOrderPersonAssetRoute = createRoute({
  method: 'delete',
  path: '/assets/delete/{id}',
  middleware: [authMiddleware],
  request: {
    params: z.object({
      id: z.coerce.number().int().positive().openapi({
        param: { name: 'id', in: 'path' },
        example: 1,
        description: '资产ID'
      })
    })
  },
  responses: {
    200: {
      description: '删除订单人员资产成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' }),
            message: z.string().openapi({ description: '操作结果消息' })
          })
        }
      }
    },
    400: {
      description: '参数错误',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '资产不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '删除订单人员资产失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

// 更新订单人员工作状态路由
const updatePersonWorkStatusRoute = createRoute({
  method: 'put',
  path: '/persons/work-status',
  middleware: [authMiddleware],
  request: {
    body: {
      content: {
        'application/json': { schema: UpdatePersonWorkStatusSchema }
      }
    }
  },
  responses: {
    200: {
      description: '更新工作状态成功',
      content: {
        'application/json': {
          schema: z.object({
            success: z.boolean().openapi({ description: '是否成功' }),
            message: z.string().openapi({ description: '操作结果消息' })
          })
        }
      }
    },
    400: {
      description: '参数错误或订单状态不符合要求',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    401: {
      description: '认证失败',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    404: {
      description: '订单或人员不存在',
      content: { 'application/json': { schema: ErrorSchema } }
    },
    500: {
      description: '更新工作状态失败',
      content: { 'application/json': { schema: ErrorSchema } }
    }
  }
});

const app = new OpenAPIHono<AuthContext>()
  // 创建订单
  .openapi(createOrderRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const user = c.get('user');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.create(data, user?.id);

      return c.json(await parseWithAwait(EmploymentOrderSchema, result), 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      // 处理枚举验证错误
      if (error instanceof Error && (
        error.message.includes('订单状态无效') ||
        error.message.includes('工作状态无效')
      )) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建订单失败'
      }, 500);
    }
  })
  // 更新订单
  .openapi(updateOrderRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const data = c.req.valid('json');
      const user = c.get('user');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.update(id, data, user?.id);

      if (!result) {
        return c.json({ code: 404, message: '订单不存在' }, 404);
      }

      const validatedResult = await parseWithAwait(EmploymentOrderSchema, result);
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      // 处理枚举验证错误
      if (error instanceof Error && (
        error.message.includes('订单状态无效') ||
        error.message.includes('工作状态无效')
      )) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      // 处理订单不存在错误
      if (error instanceof Error && error.message.includes('订单不存在')) {
        return c.json({
          code: 404,
          message: '订单不存在'
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新订单失败'
      }, 500);
    }
  })
  // 删除订单
  .openapi(deleteOrderRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const user = c.get('user');
      const orderService = new OrderService(AppDataSource);

      const success = await orderService.delete(id, user?.id);

      if (!success) {
        return c.json({ code: 404, message: '订单不存在' }, 404);
      }

      return c.json({ success }, 200);
    } catch (error) {
      if (error instanceof z.ZodError) {
        return c.json({
          code: 400,
          message: '参数错误',
          errors: error.issues
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除订单失败'
      }, 500);
    }
  })
  // 获取所有订单
  .openapi(getAllOrdersRoute, async (c) => {
    try {
      const query = c.req.valid('query');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.findAll(query);

      // 使用 parseWithAwait 验证和转换数据
      const validatedData = await parseWithAwait(
        z.object({
          data: z.array(EmploymentOrderSchema),
          total: z.number().int()
        }),
        result
      );
      return c.json(validatedData, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取订单列表失败'
      }, 500);
    }
  })
  // 获取单个订单详情
  .openapi(getOrderByIdRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.findOne(id);

      if (!result) {
        return c.json({ code: 404, message: '订单不存在' }, 404);
      }

      const validatedResult = await parseWithAwait(EmploymentOrderSchema, result);
      return c.json(validatedResult, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '获取订单详情失败'
      }, 500);
    }
  })
  // 激活订单
  .openapi(activateOrderRoute, async (c) => {
    try {
      const { orderId } = c.req.valid('param');
      const orderService = new OrderService(AppDataSource);

      const success = await orderService.activateOrder(orderId);

      return c.json({ success }, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('订单ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      if (error instanceof Error && error.message.includes('只有草稿状态的订单才能激活')) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '激活订单失败'
      }, 500);
    }
  })
  // 关闭订单
  .openapi(closeOrderRoute, async (c) => {
    try {
      const { orderId } = c.req.valid('param');
      const orderService = new OrderService(AppDataSource);

      const success = await orderService.closeOrder(orderId);

      return c.json({ success }, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('订单ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      if (error instanceof Error && error.message.includes('只有已确认或进行中的订单才能关闭')) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '关闭订单失败'
      }, 500);
    }
  })
  // 批量添加人员到订单
  .openapi(batchAddPersonsRoute, async (c) => {
    try {
      const { orderId } = c.req.valid('param');
      const { persons } = c.req.valid('json');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.batchAddPersons(orderId, persons);

      // 使用 parseWithAwait 验证和转换数据
      const validatedResult = await parseWithAwait(
        z.object({
          success: z.boolean(),
          message: z.string(),
          addedCount: z.number().int()
        }),
        result
      );
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('已结束或已取消')) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      if (error instanceof Error && error.message.includes('订单ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '批量添加人员失败'
      }, 500);
    }
  })
  // 创建订单人员资产
  .openapi(createOrderPersonAssetRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.createOrderPersonAsset(data);

      // 使用 parseWithAwait 验证和转换数据
      const validatedResult = await parseWithAwait(
        z.object({
          id: z.number().int(),
          orderId: z.number().int(),
          personId: z.number().int(),
          assetType: z.string(),
          assetFileType: z.string(),
          fileId: z.number().int(),
          relatedTime: z.coerce.date(),
          createTime: z.coerce.date(),
          updateTime: z.coerce.date()
        }),
        result
      );
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('文件不存在')) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      if (error instanceof Error && error.message.includes('人员ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '创建订单人员资产失败'
      }, 500);
    }
  })
  // 查询订单人员资产
  .openapi(queryOrderPersonAssetRoute, async (c) => {
    try {
      const query = c.req.valid('query');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.queryOrderPersonAsset(query);

      // 使用 parseWithAwait 验证和转换数据
      const validatedResult = await parseWithAwait(
        z.object({
          data: z.array(z.object({
            id: z.number().int(),
            orderId: z.number().int(),
            personId: z.number().int(),
            assetType: z.string(),
            assetFileType: z.string(),
            fileId: z.number().int(),
            file: SimpleFileSchema.optional(),
            relatedTime: z.coerce.date(),
            createTime: z.coerce.date(),
            updateTime: z.coerce.date()
          })),
          total: z.number().int()
        }),
        result
      );
      return c.json(validatedResult, 200);
    } catch (error) {
      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '查询订单人员资产失败'
      }, 500);
    }
  })
  // 删除订单人员资产
  .openapi(deleteOrderPersonAssetRoute, async (c) => {
    try {
      const { id } = c.req.valid('param');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.deleteOrderPersonAsset(id);

      // 使用 parseWithAwait 验证和转换数据
      const validatedResult = await parseWithAwait(
        z.object({
          success: z.boolean(),
          message: z.string()
        }),
        result
      );
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('资产ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '删除订单人员资产失败'
      }, 500);
    }
  })
  // 更新订单人员工作状态
  .openapi(updatePersonWorkStatusRoute, async (c) => {
    try {
      const data = c.req.valid('json');
      const orderService = new OrderService(AppDataSource);

      const result = await orderService.updatePersonWorkStatus(
        data.orderId,
        data.personId,
        data.workStatus
      );

      // 使用 parseWithAwait 验证和转换数据
      const validatedResult = await parseWithAwait(
        z.object({
          success: z.boolean(),
          message: z.string()
        }),
        result
      );
      return c.json(validatedResult, 200);
    } catch (error) {
      if (error instanceof Error && error.message.includes('订单ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      if (error instanceof Error && error.message.includes('人员ID')) {
        return c.json({
          code: 404,
          message: error.message
        }, 404);
      }

      if (error instanceof Error && error.message.includes('工作状态无效')) {
        return c.json({
          code: 400,
          message: error.message
        }, 400);
      }

      return c.json({
        code: 500,
        message: error instanceof Error ? error.message : '更新工作状态失败'
      }, 500);
    }
  });

export default app;