<template>
  <div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
      <h1>订单管理</h1>
      <a-space>
        <a-button @click="exportOrders" :loading="exportLoading">
          <template #icon><ExportOutlined /></template>
          导出数据
        </a-button>
        <a-button type="primary" @click="showAddModal">
          <template #icon><PlusOutlined /></template>
          添加订单
        </a-button>
      </a-space>
    </div>
    
    <!-- 搜索区域 -->
    <div style="margin-bottom: 16px; display: flex; gap: 8px; align-items: center;">
      <a-auto-complete
        v-model:value="searchUsername"
        :options="usernameOptions"
        placeholder="请选择或输入用户名进行搜索"
        style="width: 300px;"
        :filter-option="false"
        @search="handleSearchInput"
        @press-enter="searchOrdersByUsername"
      />
      <a-button type="primary" @click="searchOrdersByUsername" :loading="searchLoading">
        <template #icon><SearchOutlined /></template>
        查询
      </a-button>
      <a-button @click="resetSearch" :disabled="!isSearching">
        重置
      </a-button>
    </div>
    
    <a-table 
      :columns="columns" 
      :data-source="orders" 
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'total_amount'">
          ¥{{ record.total_amount }}
        </template>
        <template v-else-if="column.dataIndex === 'status'">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template v-else-if="column.dataIndex === 'created_at'">
          {{ formatDate(record.created_at) }}
        </template>
        <template v-else-if="column.dataIndex === 'action'">
          <a-button type="link" @click="viewOrder(record)">查看</a-button>
          <a-button type="link" @click="editOrder(record)">编辑</a-button>
          <a-popconfirm
            title="确定要删除这个订单吗？"
            @confirm="deleteOrder(record.id)"
            ok-text="确定"
            cancel-text="取消"
          >
            <a-button type="link" danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑订单模态框 -->
    <a-modal
      v-model:open="modalVisible"
      :title="isEdit ? '编辑订单' : '添加订单'"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
      width="800px"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="用户" name="user_id">
              <a-select v-model:value="formData.user_id" placeholder="请选择用户" :loading="usersLoading">
                <a-select-option v-for="user in users" :key="user.id" :value="user.id">
                  {{ user.username }} ({{ user.email }})
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="订单状态" name="status">
              <a-select v-model:value="formData.status" placeholder="请选择状态">
                <a-select-option value="pending">待处理</a-select-option>
                <a-select-option value="paid">已支付</a-select-option>
                <a-select-option value="shipped">已发货</a-select-option>
                <a-select-option value="delivered">已送达</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="订单项目">
          <div v-for="(item, index) in formData.items" :key="index" style="border: 1px solid #d9d9d9; padding: 16px; margin-bottom: 8px; border-radius: 6px;">
            <a-row :gutter="16" align="middle">
              <a-col :span="8">
                <a-form-item :name="['items', index, 'product_id']" label="产品" :rules="[{ required: true, message: '请选择产品' }]">
                  <a-select v-model:value="item.product_id" placeholder="请选择产品" :loading="productsLoading">
                    <a-select-option v-for="product in products" :key="product.id" :value="product.id">
                      {{ product.name }} (¥{{ product.price }})
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :name="['items', index, 'quantity']" label="数量" :rules="[{ required: true, message: '请输入数量' }]">
                  <a-input-number v-model:value="item.quantity" :min="1" style="width: 100%" @change="calculateItemTotal(index)" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item :name="['items', index, 'price']" label="单价" :rules="[{ required: true, message: '请输入单价' }]">
                  <a-input-number v-model:value="item.price" :min="0" :precision="2" style="width: 100%" @change="calculateItemTotal(index)" />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <div style="margin-top: 30px;">小计: ¥{{ (item.quantity * item.price || 0).toFixed(2) }}</div>
              </a-col>
              <a-col :span="1">
                <a-button type="text" danger @click="removeItem(index)" style="margin-top: 30px;">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-col>
            </a-row>
          </div>
          <a-button type="dashed" @click="addItem" style="width: 100%; margin-top: 8px;">
            <template #icon><PlusOutlined /></template>
            添加订单项
          </a-button>
        </a-form-item>
        
        <a-form-item>
          <div style="text-align: right; font-size: 16px; font-weight: bold;">
            总金额: ¥{{ calculateTotalAmount() }}
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看订单详情模态框 -->
    <a-modal
      v-model:open="viewModalVisible"
      title="订单详情"
      :footer="null"
      width="800px"
    >
      <div v-if="viewOrderData">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="订单ID">{{ viewOrderData.id }}</a-descriptions-item>
          <a-descriptions-item label="用户">{{ viewOrderData.user?.username || `用户ID: ${viewOrderData.user_id}` }}</a-descriptions-item>
          <a-descriptions-item label="总金额">¥{{ viewOrderData.total_amount }}</a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(viewOrderData.status)">
              {{ getStatusText(viewOrderData.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">{{ formatDate(viewOrderData.created_at) }}</a-descriptions-item>
          <a-descriptions-item label="更新时间">{{ formatDate(viewOrderData.updated_at) }}</a-descriptions-item>
        </a-descriptions>
        
        <a-divider>订单项目</a-divider>
        <a-table 
          :columns="orderItemColumns" 
          :data-source="viewOrderData.items || []" 
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'product_name'">
              {{ getProductName(record.product_id) }}
            </template>
            <template v-else-if="column.dataIndex === 'price'">
              ¥{{ record.price }}
            </template>
            <template v-else-if="column.dataIndex === 'total'">
              ¥{{ (record.quantity * record.price).toFixed(2) }}
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined, DeleteOutlined, SearchOutlined, ExportOutlined } from '@ant-design/icons-vue'
// 移除axios导入，使用统一的api工具
import { api } from '../utils/api'
import { ExportUtils } from '../utils/exportUtils'

export default {
  components: {
    PlusOutlined,
    DeleteOutlined,
    SearchOutlined,
    ExportOutlined
  },
  setup() {
    const orders = ref([])
    const users = ref([])
    const products = ref([])
    const loading = ref(false)
    const usersLoading = ref(false)
    const productsLoading = ref(false)
    const modalVisible = ref(false)
    const viewModalVisible = ref(false)
    const submitLoading = ref(false)
    const isEdit = ref(false)
    const formRef = ref()
    const viewOrderData = ref(null)
    
    // 搜索相关的响应式数据
const searchUsername = ref('')
const searchLoading = ref(false)
const isSearching = ref(false)
const usernameOptions = ref([])

    // 导出相关
    const exportLoading = ref(false)

    const formData = reactive({
      user_id: undefined,
      status: 'pending',
      items: [{
        product_id: undefined,
        quantity: 1,
        price: 0
      }]
    })

    const rules = {
      user_id: [{ required: true, message: '请选择用户' }],
      status: [{ required: true, message: '请选择状态' }]
    }

    const columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 80
      },
      {
        title: '用户',
        dataIndex: 'username',
        key: 'username',
        customRender: ({ record }) => record.user?.username || `用户ID: ${record.user_id}`
      },
      {
        title: '总金额',
        dataIndex: 'total_amount',
        key: 'total_amount'
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status'
      },
      {
        title: '创建时间',
        dataIndex: 'created_at',
        key: 'created_at'
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 200
      }
    ]

    const orderItemColumns = [
      {
        title: '产品',
        dataIndex: 'product_name',
        key: 'product_name'
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity'
      },
      {
        title: '单价',
        dataIndex: 'price',
        key: 'price'
      },
      {
        title: '小计',
        dataIndex: 'total',
        key: 'total'
      }
    ]

    // 获取所有订单
    const fetchOrders = async () => {
      try {
        loading.value = true
        const response = await api.get('/orders')
        if (response.success) {
          orders.value = response.data || []
        } else {
          message.error('获取订单失败')
        }
      } catch (error) {
        console.error('获取订单失败:', error)
        message.error('获取订单失败')
      } finally {
        loading.value = false
      }
    }

    // 获取所有用户
    const fetchUsers = async () => {
      try {
        usersLoading.value = true
        const response = await api.get('/users')
        if (response.success) {
          users.value = response.data || []
        }
      } catch (error) {
        console.error('获取用户失败:', error)
      } finally {
        usersLoading.value = false
      }
    }

    // 获取所有产品
    const fetchProducts = async () => {
      try {
        productsLoading.value = true
        const response = await api.get('/products')
        if (response.success) {
          products.value = response.data || []
        }
      } catch (error) {
        console.error('获取产品失败:', error)
      } finally {
        productsLoading.value = false
      }
    }

    // 显示添加模态框
    const showAddModal = () => {
      isEdit.value = false
      resetForm()
      modalVisible.value = true
      fetchUsers()
      fetchProducts()
    }

    // 查看订单
    const viewOrder = (record) => {
      viewOrderData.value = record
      viewModalVisible.value = true
    }

    // 编辑订单
    const editOrder = (record) => {
      isEdit.value = true
      formData.user_id = record.user_id
      formData.status = record.status
      formData.items = record.items || [{
        product_id: undefined,
        quantity: 1,
        price: 0
      }]
      formData.id = record.id
      modalVisible.value = true
      fetchUsers()
      fetchProducts()
    }

    // 删除订单
    const deleteOrder = async (id) => {
      try {
        await api.delete(`/orders/${id}`)
        message.success('删除成功')
        fetchOrders()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    }

    // 提交表单
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        submitLoading.value = true
        
        const orderData = {
          user_id: formData.user_id,
          status: formData.status,
          items: formData.items.filter(item => item.product_id && item.quantity && item.price),
          total_amount: calculateTotalAmount()
        }

        if (isEdit.value) {
          await api.put(`/orders/${formData.id}`, orderData)
          message.success('更新成功')
        } else {
          await api.post('/orders', orderData)
          message.success('创建成功')
        }
        
        modalVisible.value = false
        fetchOrders()
      } catch (error) {
        console.error('提交失败:', error)
        message.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }

    // 取消
    const handleCancel = () => {
      modalVisible.value = false
      resetForm()
    }

    // 重置表单
    const resetForm = () => {
      formData.user_id = undefined
      formData.status = 'pending'
      formData.items = [{
        product_id: undefined,
        quantity: 1,
        price: 0
      }]
      delete formData.id
      formRef.value?.resetFields()
    }

    // 添加订单项
    const addItem = () => {
      formData.items.push({
        product_id: undefined,
        quantity: 1,
        price: 0
      })
    }

    // 删除订单项
    const removeItem = (index) => {
      if (formData.items.length > 1) {
        formData.items.splice(index, 1)
      }
    }

    // 计算订单项小计
    const calculateItemTotal = (index) => {
      const item = formData.items[index]
      if (item.product_id) {
        const product = products.value.find(p => p.id === item.product_id)
        if (product && !item.price) {
          item.price = product.price
        }
      }
    }

    // 计算总金额
    const calculateTotalAmount = () => {
      return formData.items.reduce((total, item) => {
        return total + (item.quantity * item.price || 0)
      }, 0).toFixed(2)
    }

    // 获取状态颜色
    const getStatusColor = (status) => {
      const colors = {
        pending: 'orange',
        paid: 'blue',
        shipped: 'cyan',
        delivered: 'green',
        cancelled: 'red'
      }
      return colors[status] || 'default'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const texts = {
        pending: '待处理',
        paid: '已支付',
        shipped: '已发货',
        delivered: '已送达',
        cancelled: '已取消'
      }
      return texts[status] || status
    }

    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }

    // 获取用户名
    const getUserName = (userId) => {
      const user = users.value.find(u => u.id === userId)
      return user ? `${user.username} (${user.email})` : `用户ID: ${userId}`
    }

    // 获取产品名
    const getProductName = (productId) => {
      const product = products.value.find(p => p.id === productId)
      return product ? product.name : `产品ID: ${productId}`
    }

    // 搜索订单
    const searchOrdersByUsername = async () => {
      if (!searchUsername.value.trim()) {
        message.warning('请输入用户名进行搜索')
        return
      }
      
      try {
        searchLoading.value = true
        const response = await api.get('/orders/search', {
          params: { username: searchUsername.value.trim() }
        })
        
        if (response.success) {
          orders.value = response.data || []
          isSearching.value = true
          message.success(response.message || `找到 ${orders.value.length} 个匹配的订单`)
        } else {
          orders.value = []
          message.info('未找到匹配的订单')
        }
      } catch (error) {
        console.error('搜索订单失败:', error)
        message.error('搜索订单失败')
        orders.value = []
      } finally {
        searchLoading.value = false
      }
    }

    // 处理搜索输入（为自动完成提供选项）
const handleSearchInput = (value) => {
  if (!value) {
    usernameOptions.value = []
    return
  }
  
  // 从现有用户列表中筛选匹配的用户名
  const matchingUsers = users.value.filter(user => 
    user.username && user.username.toLowerCase().includes(value.toLowerCase())
  )
  
  usernameOptions.value = matchingUsers.map(user => ({
    value: user.username,
    label: user.username
  }))
}

// 更新用户名选项（在数据加载后）
const updateUsernameOptions = () => {
  const uniqueUsernames = [...new Set(users.value.map(user => user.username).filter(Boolean))]
  usernameOptions.value = uniqueUsernames.map(username => ({
    value: username,
    label: username
  }))
}

// 重置搜索
const resetSearch = () => {
  searchUsername.value = ''
  isSearching.value = false
  usernameOptions.value = []
  fetchOrders() // 重新加载全部订单
}

    // 导出订单数据
    const exportOrders = async () => {
      try {
        if (!orders.value || orders.value.length === 0) {
          message.warning('没有数据可导出')
          return
        }
        
        exportLoading.value = true
        message.loading('正在导出数据...', 0)
        
        const result = ExportUtils.exportOrdersData(orders.value)
        
        if (result.success) {
          message.destroy()
          message.success(`导出成功！文件：${result.filename}`)
        } else {
          message.destroy()
          message.error(result.message)
        }
      } catch (error) {
        message.destroy()
        console.error('导出失败:', error)
        message.error('导出失败，请重试')
      } finally {
        exportLoading.value = false
      }
    }

    onMounted(() => {
      fetchOrders()
      fetchUsers().then(() => {
        updateUsernameOptions()
      })
    })

    return {
      orders,
      users,
      products,
      loading,
      usersLoading,
      productsLoading,
      modalVisible,
      viewModalVisible,
      submitLoading,
      isEdit,
      formRef,
      formData,
      rules,
      columns,
      orderItemColumns,
      viewOrderData,
      
      // 搜索相关
      searchUsername,
      searchLoading,
      isSearching,
      usernameOptions,
      handleSearchInput,
      updateUsernameOptions,
      searchOrdersByUsername,
      resetSearch,
      
      // 导出相关
      exportLoading,
      exportOrders,
      
      fetchOrders,
      fetchUsers,
      fetchProducts,
      showAddModal,
      viewOrder,
      editOrder,
      deleteOrder,
      handleSubmit,
      handleCancel,
      resetForm,
      addItem,
      removeItem,
      calculateItemTotal,
      calculateTotalAmount,
      getStatusColor,
      getStatusText,
      formatDate,
      getUserName,
      getProductName
    }
  }
}
</script>