<template>
  <div class="order-management">
    <a-page-header
      title="订单管理"
      sub-title="管理系统订单信息"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleRefresh">
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="今日订单"
            :value="statistics.today_orders"
            :precision="0"
            suffix="单"
          >
            <template #prefix>
              <ShoppingCartOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="今日销售额"
            :value="statistics.today_sales"
            :precision="2"
            suffix="元"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <MoneyCollectOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="本月订单"
            :value="statistics.month_orders"
            :precision="0"
            suffix="单"
          >
            <template #prefix>
              <CalendarOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card>
          <a-statistic
            title="本月销售额"
            :value="statistics.month_sales"
            :precision="2"
            suffix="元"
            :value-style="{ color: '#cf1322' }"
          >
            <template #prefix>
              <DollarOutlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <a-card>
      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm">
          <a-form-item label="订单号">
            <a-input
              v-model:value="searchForm.order_no"
              placeholder="请输入订单号"
              allow-clear
            />
          </a-form-item>
          
          <a-form-item label="状态">
            <a-select
              v-model:value="searchForm.status"
              placeholder="全部状态"
              style="width: 120px"
              allow-clear
            >
              <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="completed">已完成</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
              <a-select-option value="refunded">已退款</a-select-option>
            </a-select>
          </a-form-item>
          
          <a-form-item label="下单时间">
            <a-range-picker
              v-model:value="searchForm.orderTime"
              :placeholder="['开始时间', '结束时间']"
            />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              搜索
            </a-button>
            <a-button style="margin-left: 8px" @click="handleReset">
              重置
            </a-button>
          </a-form-item>
        </a-form>
      </div>

      <!-- 订单表格 -->
      <a-table
        :columns="columns"
        :data-source="orderList"
        :loading="loading"
        :pagination="pagination"
        :row-key="record => record.id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'amount'">
            <span class="amount-text">¥{{ record.amount }}</span>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'actions'">
            <a-space :size="8">
              <a-button size="small" @click="handleView(record)">
                <EyeOutlined />
                查看
              </a-button>
              
              <template v-if="record.status === 'pending' && hasPermission('order:write')">
                <a-button size="small" type="primary" @click="handlePay(record)">
                  <PayCircleOutlined />
                  支付
                </a-button>
              </template>
              
              <template v-else-if="record.status === 'paid' && hasPermission('order:write')">
                <a-button size="small" type="primary" @click="handleShip(record)">
                  <SendOutlined />
                  发货
                </a-button>
              </template>
              
              <template v-else-if="record.status === 'shipped' && hasPermission('order:write')">
                <a-button size="small" type="primary" @click="handleComplete(record)">
                  <CheckCircleOutlined />
                  完成
                </a-button>
              </template>
              
              <a-dropdown v-if="hasPermission('order:write')">
                <a-button size="small">
                  更多
                  <DownOutlined />
                </a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      v-if="['pending', 'paid'].includes(record.status)"
                      @click="handleCancel(record)"
                    >
                      <CloseCircleOutlined />
                      取消
                    </a-menu-item>
                    <a-menu-item
                      v-if="['paid', 'shipped', 'completed'].includes(record.status)"
                      @click="handleRefund(record)"
                    >
                      <RedoOutlined />
                      退款
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 编辑订单备注模态框 -->
    <a-modal
      v-model:open="remarkModalVisible"
      title="编辑订单备注"
      :confirm-loading="remarkModalLoading"
      @ok="handleRemarkModalOk"
      @cancel="handleRemarkModalCancel"
      width="500px"
    >
      <a-form
        ref="remarkFormRef"
        :model="currentOrder"
        layout="vertical"
      >
        <a-form-item label="订单号">
          <a-input v-model:value="currentOrder.order_no" disabled />
        </a-form-item>
        
        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="currentOrder.remark"
            placeholder="请输入订单备注"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue'
import { message, Modal, type FormInstance } from 'ant-design-vue'
import type { TableProps } from 'ant-design-vue'
import {
  ShoppingCartOutlined,
  MoneyCollectOutlined,
  CalendarOutlined,
  DollarOutlined,
  SearchOutlined,
  ReloadOutlined,
  EyeOutlined,
  PayCircleOutlined,
  SendOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  RedoOutlined,
  DownOutlined,
  EditOutlined
} from '@ant-design/icons-vue'
import { useAppStore } from '@/stores/app'
import { 
  getOrders, 
  getOrder, 
  getOrderStatistics,
  updateOrderStatus,
  shipOrder,
  completeOrder,
  cancelOrder,
  refundOrder,
  updateOrder
} from '@/api/order'
import type { Order, OrderStatistics, OrderUpdateData } from '@/api/order'

interface SearchForm {
  order_no: string
  status: string
  orderTime: any[]
}

const appStore = useAppStore()

// 权限检查方法
const hasPermission = (permission: string) => {
  return appStore.hasPermission(permission)
}

const loading = ref(false)
const statistics = ref<OrderStatistics>({
  today_orders: 0,
  today_sales: 0,
  month_orders: 0,
  month_sales: 0
})

const searchForm = reactive<SearchForm>({
  order_no: '',
  status: '',
  orderTime: []
})

const orderList = ref<Order[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const columns = [
  {
    title: '订单号',
    dataIndex: 'order_no',
    key: 'order_no',
    width: 150
  },
  {
    title: '用户',
    dataIndex: 'user_name',
    key: 'user_name',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'user_phone',
    key: 'user_phone',
    width: 120
  },
  {
    title: '金额',
    key: 'amount',
    width: 100,
    align: 'right'
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '支付方式',
    dataIndex: 'payment_method',
    key: 'payment_method',
    width: 100
  },
  {
    title: '下单时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 120
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center'
  }
]

// 状态映射
const getStatusColor = (status: string) => {
  const colors = {
    pending: 'orange',
    paid: 'blue',
    shipped: 'purple',
    completed: 'green',
    cancelled: 'red',
    refunded: 'red'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string) => {
  const texts = {
    pending: '待支付',
    paid: '已支付',
    shipped: '已发货',
    completed: '已完成',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status as keyof typeof texts] || '未知'
}

// 支付方式映射
const getPaymentMethodText = (method: string) => {
  const texts = {
    wechat: '微信支付',
    alipay: '支付宝',
    bank: '银行转账',
    balance: '余额支付'
  }
  return texts[method as keyof typeof texts] || '未知'
}

// 添加备注模态框相关状态
const remarkModalVisible = ref(false)
const remarkModalLoading = ref(false)
const remarkFormRef = ref<FormInstance>()

// 当前订单数据
const currentOrder = ref<Partial<Order>>({})

// 生命周期
onMounted(() => {
  loadOrders()
  loadStatistics()
})

// 方法
const loadOrders = async () => {
  loading.value = true
  try {
    const response = await getOrders({
      page: pagination.current,
      pageSize: pagination.pageSize,
      order_no: searchForm.order_no,
      status: searchForm.status
    })
    
    orderList.value = response.data
    pagination.total = response.pagination?.total || 0
  } catch (error) {
    message.error('加载订单列表失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await getOrderStatistics()
    statistics.value = response.data
  } catch (error) {
    message.error('加载统计数据失败')
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadOrders()
}

const handleReset = () => {
  Object.assign(searchForm, {
    order_no: '',
    status: '',
    orderTime: []
  })
  pagination.current = 1
  loadOrders()
}

const handleRefresh = () => {
  loadOrders()
  loadStatistics()
  message.success('数据已刷新')
}

const handleTableChange: TableProps['onChange'] = (pag) => {
  pagination.current = pag.current!
  pagination.pageSize = pag.pageSize!
  loadOrders()
}

const handleView = async (record: Order) => {
  try {
    const response = await getOrder(record.id)
    Modal.info({
      title: '订单详情',
      width: 600,
      content: h('div', { class: 'order-detail-modal' }, [
        h('a-descriptions', {
          column: 1,
          bordered: true
        }, [
          h('a-descriptions-item', { label: '订单号' }, response.data.order_no),
          h('a-descriptions-item', { label: '用户' }, response.data.user_name),
          h('a-descriptions-item', { label: '联系电话' }, response.data.user_phone),
          h('a-descriptions-item', { label: '订单金额' }, `¥${response.data.amount}`),
          h('a-descriptions-item', { label: '状态' }, [
            h('a-tag', { color: getStatusColor(response.data.status) }, getStatusText(response.data.status))
          ]),
          h('a-descriptions-item', { label: '支付方式' }, getPaymentMethodText(response.data.payment_method)),
          h('a-descriptions-item', { label: '下单时间' }, response.data.created_at),
          h('a-descriptions-item', { label: '支付时间' }, response.data.paid_at || '-'),
          h('a-descriptions-item', { label: '发货时间' }, response.data.shipped_at || '-'),
          h('a-descriptions-item', { label: '完成时间' }, response.data.completed_at || '-'),
          h('a-descriptions-item', { label: '备注' }, response.data.remark || '-')
        ])
      ]),
      okText: '关闭',
      footer: (_, { OkBtn }) => hasPermission('order:write') ? h('div', { style: 'text-align: right;' }, [
        h('a-button', {
          onClick: () => {
            Modal.destroyAll()
            handleEditRemark(response.data)
          }
        }, '编辑备注'),
        h(OkBtn)
      ]) : h(OkBtn)
    })
  } catch (error) {
    message.error('获取订单详情失败')
  }
}

// 添加编辑备注的方法
const handleEditRemark = async (record: Order) => {
  try {
    const response = await getOrder(record.id)
    currentOrder.value = response.data
    remarkModalVisible.value = true
  } catch (error) {
    message.error('获取订单详情失败')
  }
}

const handleRemarkModalOk = () => {
  remarkFormRef.value
    ?.validate()
    .then(async () => {
      try {
        remarkModalLoading.value = true
        const updateData: OrderUpdateData = {
          remark: currentOrder.value.remark
        }
        await updateOrder(currentOrder.value.id!, updateData)
        message.success('更新订单备注成功')
        remarkModalVisible.value = false
        loadOrders()
      } catch (error) {
        message.error('更新订单备注失败')
      } finally {
        remarkModalLoading.value = false
      }
    })
    .catch((error: any) => {
      console.error('表单验证失败:', error)
    })
}

const handleRemarkModalCancel = () => {
  remarkModalVisible.value = false
  remarkFormRef.value?.resetFields()
}

const handlePay = async (record: Order) => {
  Modal.confirm({
    title: '确认支付',
    content: `确定要标记订单 "${record.order_no}" 为已支付状态吗？`,
    onOk: async () => {
      try {
        await updateOrderStatus(record.id, 'paid')
        message.success('订单状态已更新')
        loadOrders()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleShip = async (record: Order) => {
  Modal.confirm({
    title: '确认发货',
    content: `确定要标记订单 "${record.order_no}" 为已发货状态吗？`,
    onOk: async () => {
      try {
        await shipOrder(record.id)
        message.success('订单已发货')
        loadOrders()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleComplete = async (record: Order) => {
  Modal.confirm({
    title: '确认完成',
    content: `确定要标记订单 "${record.order_no}" 为已完成状态吗？`,
    onOk: async () => {
      try {
        await completeOrder(record.id)
        message.success('订单已完成')
        loadOrders()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleCancel = async (record: Order) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消订单 "${record.order_no}" 吗？`,
    onOk: async () => {
      try {
        await cancelOrder(record.id)
        message.success('订单已取消')
        loadOrders()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}

const handleRefund = async (record: Order) => {
  Modal.confirm({
    title: '确认退款',
    content: `确定要为订单 "${record.order_no}" 办理退款吗？`,
    onOk: async () => {
      try {
        await refundOrder(record.id)
        message.success('订单已退款')
        loadOrders()
      } catch (error) {
        message.error('操作失败')
      }
    }
  })
}
</script>

<style scoped lang="less">
.order-management {
  .stats-row {
    margin-bottom: 24px;
  }
  
  .search-container {
    margin-bottom: 16px;
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
    
    :deep(.ant-form-item) {
      margin-bottom: 16px;
    }
  }
  
  .amount-text {
    font-weight: 500;
    color: #cf1322;
  }
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}
</style>