import { ref } from 'vue'

// 模拟数据存储
const mockOrders = ref([
  {
    id: '1',
    orderNo: 'OUT-20231227-001',
    status: 'EXECUTING',
    operatorId: 'OP001',
    operatorName: '张三',
    totalAmount: 12500.50,
    remarks: '紧急出库，生产线急需',
    createdAt: '2023-12-27 09:30:00',
    warehouseName: '成品仓A'
  },
  {
    id: '2',
    orderNo: 'OUT-20231226-005',
    status: 'COMPLETED',
    operatorId: 'OP002',
    operatorName: '李四',
    totalAmount: 8500.00,
    remarks: '正常销售出库',
    createdAt: '2023-12-26 14:20:00',
    confirmedAt: '2023-12-26 16:45:00',
    warehouseName: '成品仓B'
  }
])

const mockOrderDetails = ref([
  {
    id: '101',
    orderId: '1',
    materialId: 'MAT001',
    materialCode: 'P-1001',
    materialName: '不锈钢螺丝',
    specification: 'M8*25',
    unit: '个',
    plannedQuantity: 1000,
    actualQuantity: 750,
    unitPrice: 2.5,
    plannedAmount: 2500,
    actualAmount: 1875,
    batchCount: 3
  },
  {
    id: '102',
    orderId: '1',
    materialId: 'MAT002',
    materialCode: 'P-1002',
    materialName: '轴承',
    specification: '6202ZZ',
    unit: '个',
    plannedQuantity: 500,
    actualQuantity: 500,
    unitPrice: 15.0,
    plannedAmount: 7500,
    actualAmount: 7500,
    batchCount: 2
  }
])

const mockInventoryBatches = ref([
  {
    id: 'B001',
    batchNo: 'BATCH-202312-001',
    materialId: 'MAT001',
    materialCode: 'P-1001',
    materialName: '不锈钢螺丝',
    specification: 'M8*25',
    unit: '个',
    quantity: 300,
    unitCost: 2.3,
    location: 'A-01-02',
    warehouseName: '成品仓A',
    productionDate: '2023-11-15',
    expiryDate: '2026-11-15',
    supplierName: '上海五金',
    status: 'NORMAL'
  }
])

// 模拟操作日志数据
const mockOperationLogs = ref([
  {
    id: 'LOG001',
    orderId: '1',
    orderNo: 'OUT-20231227-001',
    operatorId: 'OP001',
    operatorName: '张三',
    operationType: 'CREATE',
    operationDesc: '创建出库单',
    success: true,
    createdAt: '2023-12-27 09:30:00',
    duration: 120
  },
  {
    id: 'LOG002',
    orderId: '1',
    orderNo: 'OUT-20231227-001',
    operatorId: 'OP001',
    operatorName: '张三',
    operationType: 'SCAN',
    operationDesc: '扫描批次 BATCH-202312-001，出库数量 50',
    success: true,
    createdAt: '2023-12-27 10:30:15',
    duration: 850
  }
])

// API函数
export const fetchOrders = async () => {
  // 模拟API调用
  return new Promise(resolve => {
    setTimeout(() => {
      resolve([...mockOrders.value])
    }, 500)
  })
}

export const deleteOrder = async (orderId) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const index = mockOrders.value.findIndex(o => o.id === orderId)
      if (index === -1) {
        reject(new Error('订单不存在'))
        return
      }
      
      // 检查订单状态，只有草稿状态的订单可以删除
      const order = mockOrders.value[index]
      if (order.status !== 'DRAFT') {
        reject(new Error('只有草稿状态的订单可以删除'))
        return
      }
      
      // 删除订单
      mockOrders.value.splice(index, 1)
      
      // 删除相关订单详情
      mockOrderDetails.value = mockOrderDetails.value.filter(d => d.orderId !== orderId)
      
      resolve()
    }, 800)
  })
}

export const createOrder = async (orderData) => {
  return new Promise(resolve => {
    setTimeout(() => {
      // 创建新订单
      const newOrder = {
        id: Date.now().toString(),
        orderNo: `OUT-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${Math.floor(Math.random() * 1000).toString().padStart(3, '0')}`,
        status: 'DRAFT',
        operatorId: orderData.operatorId || 'OP001',
        operatorName: orderData.operatorName || '张三',
        totalAmount: orderData.totalAmount || 0,
        remarks: orderData.remarks || '',
        createdAt: new Date().toISOString(),
        warehouseName: orderData.warehouseName || '成品仓A',
        ...orderData
      }
      
      // 添加到模拟数据
      mockOrders.value.unshift(newOrder)
      
      // 创建订单详情
      if (orderData.details && Array.isArray(orderData.details)) {
        const newDetails = orderData.details.map(detail => ({
          id: `${newOrder.id}-${Date.now().toString()}`,
          orderId: newOrder.id,
          ...detail
        }))
        
        mockOrderDetails.value.push(...newDetails)
      }
      
      resolve(newOrder)
    }, 1000)
  })
}

export const fetchOperationLogs = async (filters = {}) => {
  return new Promise(resolve => {
    setTimeout(() => {
      let logs = [...mockOperationLogs.value]
      
      // 按操作类型过滤
      if (filters.operationType) {
        logs = logs.filter(log => log.operationType === filters.operationType)
      }
      
      // 按操作员过滤
      if (filters.operatorName) {
        logs = logs.filter(log => 
          log.operatorName.toLowerCase().includes(filters.operatorName.toLowerCase())
        )
      }
      
      // 按订单号过滤
      if (filters.orderNo) {
        logs = logs.filter(log => 
          log.orderNo.toLowerCase().includes(filters.orderNo.toLowerCase())
        )
      }
      
      // 按日期范围过滤
      if (filters.dateRange && filters.dateRange.length === 2) {
        const [start, end] = filters.dateRange
        const startDate = new Date(start)
        const endDate = new Date(end)
        endDate.setHours(23, 59, 59, 999)
        
        logs = logs.filter(log => {
          const logDate = new Date(log.createdAt)
          return logDate >= startDate && logDate <= endDate
        })
      }
      
      // 按订单ID过滤
      if (filters.orderId) {
        logs = logs.filter(log => log.orderId === filters.orderId)
      }
      
      // 按成功状态过滤
      if (filters.success !== undefined) {
        logs = logs.filter(log => log.success === filters.success)
      }
      
      // 排序（默认按创建时间倒序）
      logs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
      
      resolve(logs)
    }, 600)
  })
}

export const fetchOrderDetails = async (orderId) => {
  return new Promise(resolve => {
    setTimeout(() => {
      const details = mockOrderDetails.value.filter(d => d.orderId === orderId)
      resolve([...details])
    }, 300)
  })
}

export const scanBatch = async (
  batchNo, 
  orderId, 
  quantity
) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const batch = mockInventoryBatches.value.find(b => b.batchNo === batchNo)
      
      if (!batch) {
        reject(new Error('批次不存在或已失效'))
        return
      }
      
      if (batch.quantity <= 0) {
        reject(new Error('库存不足'))
        return
      }
      
      if (quantity !== undefined) {
        // 模拟出库操作
        if (quantity > batch.quantity) {
          reject(new Error('出库数量超过库存数量'))
          return
        }
        
        // 更新库存数量
        batch.quantity -= quantity
        
        // 更新订单明细
        const detail = mockOrderDetails.value.find(
          d => d.orderId === orderId && d.materialId === batch.materialId
        )
        
        if (detail) {
          detail.actualQuantity += quantity
          detail.actualAmount += quantity * batch.unitCost
        }
      }
      
      resolve({ ...batch })
    }, 800)
  })
}

export const confirmOutbound = async (orderId) => {
  return new Promise(resolve => {
    setTimeout(() => {
      const order = mockOrders.value.find(o => o.id === orderId)
      if (order) {
        order.status = 'COMPLETED'
        order.confirmedAt = new Date().toISOString()
      }
      resolve()
    }, 1000)
  })
}

export const fetchRecentTransactions = async (orderId) => {
  // 模拟数据
  return new Promise(resolve => {
    setTimeout(() => {
      resolve([
        {
          id: 'T001',
          orderId,
          detailId: '101',
          batchId: 'B001',
          batchNo: 'BATCH-202312-001',
          materialName: '不锈钢螺丝',
          quantity: 50,
          unit: '个',
          unitCost: 2.3,
          amount: 115,
          location: 'A-01-02',
          operatorName: '张三',
          scannedAt: '2023-12-27 10:30:15',
          status: 'NORMAL'
        }
      ])
    }, 300)
  })
}

export const undoTransaction = async (transactionId) => {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log(`撤销交易 ${transactionId}`)
      resolve()
    }, 800)
  })
}

export const getBatchRecommendation = async (
  materialId
) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve([
        {
          batchId: 'B001',
          batchNo: 'BATCH-202312-001',
          materialId,
          materialName: '不锈钢螺丝',
          recommendedQuantity: 250,
          currentStock: 300,
          location: 'A-01-02',
          expiryDate: '2026-11-15',
          productionDate: '2023-11-15',
          supplierName: '上海五金',
          priorityScore: 95,
          reason: ['先进先出', '库位最近']
        }
      ])
    }, 500)
  })
}

export const pauseOutbound = async (orderId) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const order = mockOrders.value.find(o => o.id === orderId)
      if (!order) {
        reject(new Error('订单不存在'))
        return
      }
      
      if (order.status !== 'EXECUTING') {
        reject(new Error('订单当前状态无法暂停'))
        return
      }
      
      order.status = 'PAUSED'
      order.pausedAt = new Date().toISOString()
      
      resolve(order)
    }, 800)
  })
}

export const resumeOutbound = async (orderId) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const order = mockOrders.value.find(o => o.id === orderId)
      if (!order) {
        reject(new Error('订单不存在'))
        return
      }
      
      if (order.status !== 'PAUSED') {
        reject(new Error('订单当前状态无法恢复'))
        return
      }
      
      order.status = 'EXECUTING'
      order.resumedAt = new Date().toISOString()
      
      resolve(order)
    }, 800)
  })
}