<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">销售管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddOrderModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增订单
            </button>
            <button @click="exportSalesData" class="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700">
              导出数据
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 销售统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">本月销售额</div>
          <div class="mt-2 text-3xl font-bold text-blue-600 dark:text-blue-400">¥{{ formatNumber(currentMonthSales) }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            环比增长 <span :class="salesGrowth >= 0 ? 'text-green-600' : 'text-red-600'">{{ salesGrowth }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">订单数量</div>
          <div class="mt-2 text-3xl font-bold text-green-600 dark:text-green-400">{{ totalOrders }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            完成率 <span class="text-green-600">{{ completionRate }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">平均客单价</div>
          <div class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">¥{{ formatNumber(averageOrderValue) }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            同比增长 <span :class="avgOrderValueGrowth >= 0 ? 'text-green-600' : 'text-red-600'">{{ avgOrderValueGrowth }}%</span>
          </div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">销售预测</div>
          <div class="mt-2 text-3xl font-bold text-purple-600 dark:text-purple-400">¥{{ formatNumber(salesForecast) }}</div>
          <div class="mt-2 text-sm text-gray-500 dark:text-gray-400">
            预计完成率 <span class="text-green-600">{{ forecastCompletionRate }}%</span>
          </div>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="searchText" placeholder="订单号/客户名称" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">订单状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有状态</option>
              <option v-for="status in orderStatuses" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">时间范围</label>
            <select v-model="filters.timeRange" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有时间</option>
              <option v-for="range in timeRanges" :key="range.id" :value="range.id">{{ range.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">销售员</label>
            <select v-model="filters.salesperson" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有销售员</option>
              <option v-for="person in salespersons" :key="person.id" :value="person.id">{{ person.name }}</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 销售订单列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700">
          <h2 class="text-lg font-medium text-gray-900 dark:text-white">销售订单</h2>
        </div>
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">订单信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">客户信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">金额</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">销售员</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="order in filteredOrders" :key="order.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ order.orderNo }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ formatDate(order.date) }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ order.customerName }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ order.customerContact }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                ¥{{ formatNumber(order.amount) }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getOrderStatusClass(order.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getOrderStatusName(order.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white">
                {{ order.salesperson }}
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewOrder(order)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editOrder(order)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteOrder(order)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增订单模态框 -->
    <div v-if="showAddOrderModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">新增订单</h2>
        <form @submit.prevent="addOrder">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">客户名称</label>
            <select v-model="newOrder.customerId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="customer in customers" :key="customer.id" :value="customer.id">{{ customer.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">订单金额</label>
            <input type="number" v-model="newOrder.amount" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">订单日期</label>
            <input type="date" v-model="newOrder.date" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">订单状态</label>
            <select v-model="newOrder.status" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="status in orderStatuses" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">备注</label>
            <textarea v-model="newOrder.remark" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddOrderModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              添加
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 订单数据
const orders = ref([
  {
    id: 1,
    orderNo: 'SO20240315001',
    customerId: 1,
    customerName: 'ABC科技有限公司',
    customerContact: '张三',
    amount: 50000,
    date: '2024-03-15',
    status: 1,
    salesperson: '王五',
    remark: '新客户首单'
  },
  {
    id: 2,
    orderNo: 'SO20240316001',
    customerId: 2,
    customerName: 'XYZ贸易有限公司',
    customerContact: '李四',
    amount: 30000,
    date: '2024-03-16',
    status: 2,
    salesperson: '赵六',
    remark: '老客户续单'
  }
])

// 客户数据
const customers = ref([
  {
    id: 1,
    name: 'ABC科技有限公司',
    contact: '张三',
    phone: '13800138000'
  },
  {
    id: 2,
    name: 'XYZ贸易有限公司',
    contact: '李四',
    phone: '13900139000'
  }
])

// 订单状态
const orderStatuses = ref([
  { id: 1, name: '待处理' },
  { id: 2, name: '处理中' },
  { id: 3, name: '已完成' },
  { id: 4, name: '已取消' }
])

// 时间范围
const timeRanges = ref([
  { id: 1, name: '今天' },
  { id: 2, name: '本周' },
  { id: 3, name: '本月' },
  { id: 4, name: '本季度' },
  { id: 5, name: '本年' }
])

// 销售员
const salespersons = ref([
  { id: 1, name: '王五' },
  { id: 2, name: '赵六' },
  { id: 3, name: '钱七' }
])

// 筛选条件
const searchText = ref('')
const filters = ref({
  status: '',
  timeRange: '',
  salesperson: ''
})

// 模态框状态
const showAddOrderModal = ref(false)

// 新订单表单
const newOrder = ref({
  customerId: '',
  amount: '',
  date: '',
  status: '',
  remark: ''
})

// 计算属性
const filteredOrders = computed(() => {
  return orders.value.filter(item => {
    const matchesSearch = !searchText.value || 
      item.orderNo.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.customerName.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesStatus = !filters.value.status || item.status === filters.value.status
    const matchesSalesperson = !filters.value.salesperson || item.salesperson === filters.value.salesperson
    return matchesSearch && matchesStatus && matchesSalesperson
  })
})

const currentMonthSales = computed(() => {
  const currentMonth = new Date().getMonth() + 1
  return orders.value
    .filter(order => new Date(order.date).getMonth() + 1 === currentMonth)
    .reduce((sum, order) => sum + order.amount, 0)
})

const salesGrowth = computed(() => {
  // 这里假设有一个计算环比增长的逻辑
  return 15
})

const totalOrders = computed(() => orders.value.length)

const completionRate = computed(() => {
  const completedOrders = orders.value.filter(order => order.status === 3).length
  return Math.round((completedOrders / totalOrders.value) * 100)
})

const averageOrderValue = computed(() => {
  return orders.value.reduce((sum, order) => sum + order.amount, 0) / totalOrders.value
})

const avgOrderValueGrowth = computed(() => {
  // 这里假设有一个计算同比增长的逻辑
  return 8
})

const salesForecast = computed(() => {
  // 这里假设有一个销售预测的逻辑
  return currentMonthSales.value * 1.2
})

const forecastCompletionRate = computed(() => {
  // 这里假设有一个预测完成率的逻辑
  return 85
})

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取订单状态名称
const getOrderStatusName = (statusId) => {
  const status = orderStatuses.value.find(s => s.id === statusId)
  return status ? status.name : '未知状态'
}

// 获取订单状态样式
const getOrderStatusClass = (statusId) => {
  const classes = {
    1: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    2: 'bg-blue-100 text-blue-800 dark:bg-blue-700 dark:text-blue-300',
    3: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    4: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300'
  }
  return classes[statusId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 添加订单
const addOrder = () => {
  const customer = customers.value.find(c => c.id === newOrder.value.customerId)
  const item = {
    id: orders.value.length + 1,
    orderNo: `SO${new Date().getTime()}`,
    ...newOrder.value,
    customerName: customer.name,
    customerContact: customer.contact,
    salesperson: '当前用户' // 这里应该获取当前登录用户
  }
  orders.value.push(item)
  showAddOrderModal.value = false
  resetNewOrder()
}

// 重置新订单表单
const resetNewOrder = () => {
  newOrder.value = {
    customerId: '',
    amount: '',
    date: '',
    status: '',
    remark: ''
  }
}

// 导出销售数据
const exportSalesData = () => {
  // 实现导出销售数据的逻辑
  console.log('导出销售数据')
}

// 查看订单
const viewOrder = (item) => {
  // 实现查看订单逻辑
  console.log('查看订单:', item)
}

// 编辑订单
const editOrder = (item) => {
  // 实现编辑订单逻辑
  console.log('编辑订单:', item)
}

// 删除订单
const deleteOrder = (item) => {
  if (confirm(`确定要删除订单"${item.orderNo}"吗？`)) {
    const index = orders.value.findIndex(o => o.id === item.id)
    if (index !== -1) {
      orders.value.splice(index, 1)
    }
  }
}
</script> 