/**
 * Order Management View
 * Based on official Xboard order modules
 */

const OrderManagement = {
  setup() {
    const { ref, onMounted } = Vue;
    const list = ref([]);
    const loading = ref(true);
    const filters = ref({
      keyword: '',
      status: ''
    });
    const pagination = ref({
      current: 1,
      total: 0,
      per_page: 20
    });

    const fetchOrders = async (page = 1) => {
      loading.value = true;
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const response = await fetch(`/api/v2/${adminPath}/order/fetch`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            page: page,
            per_page: pagination.value.per_page,
            ...filters.value
          })
        });
        const result = await response.json();
        if (result.data) {
          list.value = result.data.list;
          pagination.value = result.data.pagination;
        }
      } catch (err) {
        console.error('Fetch orders failed', err);
      } finally {
        loading.value = false;
      }
    };

    const getStatusType = (status) => {
      switch (status) {
        case 0: return 'status-pending'; // 待支付
        case 1: return 'status-pending'; // 开通中
        case 2: return 'status-disabled'; // 已取消
        case 3: return 'status-active'; // 已完成
        case 4: return 'status-disabled'; // 已退款
        default: return '';
      }
    };

    const getStatusText = (status) => {
      const map = { 0: '待支付', 1: '开通中', 2: '已取消', 3: '已完成', 4: '已退款' };
      return map[status] || '未知';
    };

    const handleAction = async (tradeNo, action) => {
      if (!confirm(`确定执行 ${action} 操作吗?`)) return;
      
      try {
        const adminPath = window.settings?.secure_path || 'admin';
        const response = await fetch(`/api/v2/${adminPath}/order/${action}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ trade_no: tradeNo })
        });
        const result = await response.json();
        if (result.data) {
          fetchOrders(pagination.value.current);
        } else {
          alert('操作失败: ' + result.message);
        }
      } catch (err) {
        alert('请求错误');
      }
    };

    onMounted(() => fetchOrders());

    return {
      list, loading, filters, pagination,
      fetchOrders, getStatusType, getStatusText, handleAction
    };
  },
  template: `
    <div class="order-management animate-in">
      <div class="page-header">
        <div class="filter-bar">
          <input 
            type="text" 
            v-model="filters.keyword" 
            placeholder="订单号 / 用户ID" 
            @keyup.enter="fetchOrders(1)"
          >
          <select v-model="filters.status" @change="fetchOrders(1)" class="form-input" style="width: 150px; margin-left: 10px;">
            <option value="">全部状态</option>
            <option value="0">待支付</option>
            <option value="2">已取消</option>
            <option value="3">已完成</option>
          </select>
        </div>
      </div>

      <div class="card">
        <table class="admin-table">
          <thead>
            <tr>
              <th>订单号</th>
              <th>用户</th>
              <th>套餐</th>
              <th>金额</th>
              <th>状态</th>
              <th>创建时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody v-if="!loading">
            <tr v-for="order in list" :key="order.trade_no">
              <td><code>{{ order.trade_no }}</code></td>
              <td>
                <div class="email-cell">
                  <span>{{ order.user_email }}</span>
                  <small class="text-secondary">UID: {{ order.user_id }}</small>
                </div>
              </td>
              <td>{{ order.plan_name || '佣金提现' }}</td>
              <td><span style="font-weight: 500;">{{ (order.total_amount / 100).toFixed(2) }}</span> <small>CNY</small></td>
              <td>
                <span :class="['status-tag', getStatusType(order.status)]">
                  {{ getStatusText(order.status) }}
                </span>
              </td>
              <td>{{ order.created_at_text }}</td>
              <td class="row-actions">
                <a href="#" @click.prevent="handleAction(order.trade_no, 'paid')" v-if="order.status === 0">手动到账</a>
                <span class="sep" v-if="order.status === 0">|</span>
                <a href="#" @click.prevent="handleAction(order.trade_no, 'cancel')" v-if="order.status === 0" class="text-danger">取消</a>
                <a href="#" v-else>详情</a>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div v-if="loading" class="loading">加载中...</div>
        
        <div class="pagination" v-if="pagination.last_page > 1">
           <!-- Simple pagination placeholder -->
           <button @click="fetchOrders(pagination.current - 1)" :disabled="pagination.current <= 1">上一页</button>
           <span>{{ pagination.current }} / {{ pagination.last_page }}</span>
           <button @click="fetchOrders(pagination.current + 1)" :disabled="pagination.current >= pagination.last_page">下一页</button>
        </div>
      </div>
    </div>
  `
};

export default OrderManagement;
