import { describe, it, expect, beforeEach } from 'vitest';
import { testClient } from 'hono/testing';
import { IntegrationTestDatabase, setupIntegrationDatabaseHooksWithEntities } from '@d8d/shared-test-util';
import { JWTUtil } from '@d8d/shared-utils';
import { UserEntity, Role } from '@d8d/user-module';
import { File } from '@d8d/file-module';
import { Goods, GoodsCategory } from '@d8d/goods-module';
import { Supplier } from '@d8d/supplier-module';
import { Merchant } from '@d8d/merchant-module';
import { DeliveryAddress } from '@d8d/delivery-address-module';
import { AreaEntity } from '@d8d/geo-areas';
import userOrderItemsRoutes from '../../src/routes/user/order-items';
import { Order, OrderGoods } from '../../src/entities';

// 设置集成测试钩子
setupIntegrationDatabaseHooksWithEntities([
  UserEntity, Role, Order, OrderGoods, Goods, GoodsCategory, File, Supplier, Merchant, DeliveryAddress, AreaEntity
])

describe('用户订单商品管理API集成测试', () => {
  let client: ReturnType<typeof testClient<typeof userOrderItemsRoutes>>;
  let userToken: string;
  let otherUserToken: string;
  let testUser: UserEntity;
  let otherUser: UserEntity;
  let testOrder: Order;
  let otherUserOrder: Order;
  let testGoods: Goods;
  let testSupplier: Supplier;
  let testFile: File;
  let testGoodsCategory: GoodsCategory;
  let testMerchant: Merchant;
  let testDeliveryAddress: DeliveryAddress;
  let testProvince: AreaEntity;
  let testCity: AreaEntity;
  let testDistrict: AreaEntity;
  let testTown: AreaEntity;

  beforeEach(async () => {
    // 创建测试客户端
    client = testClient(userOrderItemsRoutes);

    // 获取数据源
    const dataSource = await IntegrationTestDatabase.getDataSource();

    // 创建测试用户
    const userRepository = dataSource.getRepository(UserEntity);
    testUser = userRepository.create({
      username: `test_user_${Math.floor(Math.random() * 100000)}`,
      password: 'test_password',
      nickname: '测试用户',
      registrationSource: 'web'
    });
    await userRepository.save(testUser);

    // 创建其他用户
    otherUser = userRepository.create({
      username: `other_user_${Math.floor(Math.random() * 100000)}`,
      password: 'other_password',
      nickname: '其他用户',
      registrationSource: 'web'
    });
    await userRepository.save(otherUser);

    // 生成测试用户的token
    userToken = JWTUtil.generateToken({
      id: testUser.id,
      username: testUser.username,
      roles: [{name:'user'}]
    });

    // 生成其他用户的token
    otherUserToken = JWTUtil.generateToken({
      id: otherUser.id,
      username: otherUser.username,
      roles: [{name:'user'}]
    });

    // 先创建商品分类
    const goodsCategoryRepository = dataSource.getRepository(GoodsCategory);
    testGoodsCategory = goodsCategoryRepository.create({
      name: '测试商品分类',
      level: 1,
      parentId: 0,
      sort: 1,
      state: 1,
      createdBy: testUser.id
    });
    await goodsCategoryRepository.save(testGoodsCategory);

    // 创建测试供应商
    const supplierRepository = dataSource.getRepository(Supplier);
    testSupplier = supplierRepository.create({
      name: '测试供应商',
      username: `test_supplier_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138000',
      realname: '测试供应商',
      state: 1,
      createdBy: testUser.id
    });
    await supplierRepository.save(testSupplier);

    // 创建测试商品
    const goodsRepository = dataSource.getRepository(Goods);
    testGoods = goodsRepository.create({
      name: '测试商品',
      price: 100.00,
      costPrice: 80.00,
      categoryId1: testGoodsCategory.id,
      categoryId2: testGoodsCategory.id,
      categoryId3: testGoodsCategory.id,
      goodsType: 1,
      supplierId: testSupplier.id,
      state: 1,
      stock: 100,
      lowestBuy: 1,
      createdBy: testUser.id
    });
    await goodsRepository.save(testGoods);

    // 创建测试文件
    const fileRepository = dataSource.getRepository(File);
    testFile = fileRepository.create({
      name: 'test_image.jpg',
      type: 'image/jpeg',
      size: 102400,
      path: 'images/test_image.jpg',
      uploadUserId: testUser.id,
      uploadTime: new Date(),
      createdAt: new Date(),
      updatedAt: new Date()
    });
    await fileRepository.save(testFile);

    // 创建测试商户
    const merchantRepository = dataSource.getRepository(Merchant);
    testMerchant = merchantRepository.create({
      name: '测试商户',
      username: `test_merchant_${Math.floor(Math.random() * 100000)}`,
      password: 'password123',
      phone: '13800138000',
      realname: '测试商户',
      state: 1,
      createdBy: testUser.id
    });
    await merchantRepository.save(testMerchant);

    // 创建测试地区数据
    const areaRepository = dataSource.getRepository(AreaEntity);
    testProvince = areaRepository.create({
      name: '测试省',
      code: 110000,
      level: 1,
      parentCode: 0,
      state: 1,
      createdBy: testUser.id
    });
    await areaRepository.save(testProvince);

    testCity = areaRepository.create({
      name: '测试市',
      code: 110100,
      level: 2,
      parentCode: testProvince.code,
      state: 1,
      createdBy: testUser.id
    });
    await areaRepository.save(testCity);

    testDistrict = areaRepository.create({
      name: '测试区',
      code: 110105,
      level: 3,
      parentCode: testCity.code,
      state: 1,
      createdBy: testUser.id
    });
    await areaRepository.save(testDistrict);

    testTown = areaRepository.create({
      name: '测试街道',
      code: 110105001,
      level: 4,
      parentCode: testDistrict.code,
      state: 1,
      createdBy: testUser.id
    });
    await areaRepository.save(testTown);

    // 创建测试配送地址
    const deliveryAddressRepository = dataSource.getRepository(DeliveryAddress);
    testDeliveryAddress = deliveryAddressRepository.create({
      name: '测试配送地址',
      phone: '13800138000',
      receiverProvince: testProvince.id,
      receiverCity: testCity.id,
      receiverDistrict: testDistrict.id,
      receiverTown: testTown.id,
      address: '测试地址详情',
      userId: testUser.id,
      state: 1,
      createdBy: testUser.id
    });
    await deliveryAddressRepository.save(testDeliveryAddress);

    // 创建测试用户的订单
    const orderRepository = dataSource.getRepository(Order);
    testOrder = orderRepository.create({
      orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
      userId: testUser.id,
      amount: 100.00,
      costAmount: 80.00,
      payAmount: 100.00,
      orderType: 1,
      payType: 1,
      payState: 2,
      state: 0,
      merchantId: testMerchant.id,
      supplierId: testSupplier.id,
      addressId: testDeliveryAddress.id,
      createdBy: testUser.id
    });
    await orderRepository.save(testOrder);

    // 创建其他用户的订单
    otherUserOrder = orderRepository.create({
      orderNo: `ORDER_${Math.floor(Math.random() * 100000)}`,
      userId: otherUser.id,
      amount: 200.00,
      costAmount: 160.00,
      payAmount: 200.00,
      orderType: 1,
      payType: 1,
      payState: 2,
      state: 0,
      merchantId: testMerchant.id,
      supplierId: testSupplier.id,
      addressId: testDeliveryAddress.id,
      createdBy: otherUser.id
    });
    await orderRepository.save(otherUserOrder);
  });

  describe('GET /order-items', () => {
    it('应该返回当前用户订单的商品列表', async () => {
      // 为测试用户的订单创建一些商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);

      const userOrderGoods1 = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试商品1',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(userOrderGoods1);

      const userOrderGoods2 = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试商品2',
        price: 25.00,
        num: 4,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(userOrderGoods2);

      // 为其他用户的订单创建一个商品，确保不会返回
      const otherUserOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '其他用户商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: otherUser.id
      });
      await orderGoodsRepository.save(otherUserOrderGoods);

      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户订单商品列表响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户订单商品列表错误响应:', errorData);
      }
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data).toHaveProperty('data');
        expect(Array.isArray(data.data)).toBe(true);

        // 验证只返回当前用户订单的商品
        data.data.forEach((orderGoods: any) => {
          expect(orderGoods.order.userId).toBe(testUser.id);
        });

        // 验证不包含其他用户订单的商品
        const otherUserOrderGoodsInResponse = data.data.find((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === otherUser.id
        );
        expect(otherUserOrderGoodsInResponse).toBeUndefined();
      }
    });

    it('应该拒绝未认证用户的访问', async () => {
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      });
      expect(response.status).toBe(401);
    });
  });

  describe('POST /order-items', () => {
    it('应该成功创建订单商品并自动设置当前用户权限', async () => {
      const createData = {
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '用户创建商品',
        price: 75.00,
        num: 3,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id
      };

      const response = await client.index.$post({
        json: createData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户创建订单商品响应状态:', response.status);
      if (response.status !== 201) {
        const errorData = await response.json();
        console.debug('用户创建订单商品错误响应:', errorData);
      }
      expect(response.status).toBe(201);

      if (response.status === 201) {
        const data = await response.json();
        expect(data).toHaveProperty('id');
        expect(data.goodsName).toBe(createData.goodsName);
        expect(parseFloat(data.price)).toBe(createData.price);
        expect(data.num).toBe(createData.num);
        expect(data.createdBy).toBe(testUser.id); // 验证自动设置创建用户
      }
    });

    it('应该验证创建订单商品的必填字段', async () => {
      const invalidData = {
        // 缺少必填字段
        price: -1,
        num: -1
      };

      const response = await client.index.$post({
        json: invalidData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(400);
    });

    it('应该拒绝为其他用户的订单创建商品', async () => {
      const createData = {
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '尝试为其他用户订单创建商品',
        price: 75.00,
        num: 3,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id
      };

      const response = await client.index.$post({
        json: createData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('GET /order-items/:id', () => {
    it('应该返回当前用户订单的商品详情', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试订单商品详情',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

      const response = await client[':id'].$get({
        param: { id: testOrderGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户订单商品详情响应状态:', response.status);
      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('用户订单商品详情错误响应:', errorData);
      }
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.id).toBe(testOrderGoods.id);
        expect(data.goodsName).toBe(testOrderGoods.goodsName);
        expect(data.order.userId).toBe(testUser.id); // 验证订单属于当前用户
      }
    });

    it('应该拒绝访问其他用户订单的商品', async () => {
      // 为其他用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const otherUserOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '其他用户订单商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: otherUser.id
      });
      await orderGoodsRepository.save(otherUserOrderGoods);

      const response = await client[':id'].$get({
        param: { id: otherUserOrderGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403（权限不足）
    });

    it('应该处理不存在的订单商品', async () => {
      const response = await client[':id'].$get({
        param: { id: 999999 }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(404);
    });
  });

  describe('PUT /order-items/:id', () => {
    it('应该成功更新当前用户订单的商品', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试更新订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

      const updateData = {
        num: 5,
        state: 1
      };

      const response = await client[':id'].$put({
        param: { id: testOrderGoods.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户更新订单商品响应状态:', response.status);
      expect(response.status).toBe(200);

      if (response.status === 200) {
        const data = await response.json();
        expect(data.num).toBe(updateData.num);
        expect(data.state).toBe(updateData.state);
        expect(data.updatedBy).toBe(testUser.id); // 验证自动设置更新用户
      }
    });

    it('应该拒绝更新其他用户订单的商品', async () => {
      // 为其他用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const otherUserOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '其他用户订单商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: otherUser.id
      });
      await orderGoodsRepository.save(otherUserOrderGoods);

      const updateData = {
        num: 2
      };

      const response = await client[':id'].$put({
        param: { id: otherUserOrderGoods.id },
        json: updateData
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('DELETE /order-items/:id', () => {
    it('应该成功删除当前用户订单的商品', async () => {
      // 先为测试用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const testOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '测试删除订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(testOrderGoods);

      const response = await client[':id'].$delete({
        param: { id: testOrderGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      console.debug('用户删除订单商品响应状态:', response.status);
      expect(response.status).toBe(204);
    });

    it('应该拒绝删除其他用户订单的商品', async () => {
      // 为其他用户的订单创建一个商品
      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);
      const otherUserOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '其他用户订单商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: otherUser.id
      });
      await orderGoodsRepository.save(otherUserOrderGoods);

      const response = await client[':id'].$delete({
        param: { id: otherUserOrderGoods.id }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      expect(response.status).toBe(403); // 数据权限控制返回403
    });
  });

  describe('数据权限配置测试', () => {
    it('应该验证dataPermission配置正确工作', async () => {
      // 这个测试验证数据权限配置是否正常工作
      // 用户只能访问自己订单的商品

      const dataSource = await IntegrationTestDatabase.getDataSource();
      const orderGoodsRepository = dataSource.getRepository(OrderGoods);

      // 创建测试用户和其他用户订单的商品
      const userOrderGoods = orderGoodsRepository.create({
        orderId: testOrder.id,
        goodsId: testGoods.id,
        goodsName: '用户订单商品',
        price: 50.00,
        num: 2,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: testUser.id
      });
      await orderGoodsRepository.save(userOrderGoods);

      const otherUserOrderGoods = orderGoodsRepository.create({
        orderId: otherUserOrder.id,
        goodsId: testGoods.id,
        goodsName: '其他用户订单商品',
        price: 100.00,
        num: 1,
        state: 0,
        supplierId: testSupplier.id,
        imageFileId: testFile.id,
        createdBy: otherUser.id
      });
      await orderGoodsRepository.save(otherUserOrderGoods);

      // 使用测试用户token获取列表
      const response = await client.index.$get({
        query: {
          page: 1,
          pageSize: 10
        }
      }, {
        headers: {
          'Authorization': `Bearer ${userToken}`
        }
      });

      if (response.status !== 200) {
        const errorData = await response.json();
        console.debug('数据权限配置测试错误响应:', errorData);
      }
      expect(response.status).toBe(200);
      const data = await response.json();

      // 类型检查确保data属性存在
      if ('data' in data && Array.isArray(data.data)) {
        // 验证只返回测试用户订单的商品
        const userOrderGoodsInResponse = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === testUser.id
        );
        const otherUserOrderGoodsInResponse = data.data.filter((orderGoods: any) =>
          orderGoods.order && orderGoods.order.userId === otherUser.id
        );

        expect(userOrderGoodsInResponse.length).toBeGreaterThan(0);
        expect(otherUserOrderGoodsInResponse.length).toBe(0);
      } else {
        // 如果响应是错误格式，应该失败
        expect(data).toHaveProperty('data');
      }
    });
  });
});