/**
 * Plan Management View
 */

import { adminApi } from '../api/admin.js';

const { ref, onMounted } = Vue;

export default {
  name: 'PlanManagement',
  template: `
    <div class="plan-management">
      <div class="page-header">
        <h2>套餐管理</h2>
        <div class="actions">
          <button class="btn btn-primary" @click="addPlan">创建套餐</button>
        </div>
      </div>

      <div class="stats-grid">
         <div class="stats-card" v-for="plan in plans" :key="plan.id">
            <div class="plan-header">
               <span class="plan-name">{{ plan.name }}</span>
               <span :class="'status-tag ' + (plan.show ? 'status-active' : 'status-disabled')">
                  {{ plan.show ? '上架中' : '已下架' }}
               </span>
            </div>
            <div class="plan-price">¥{{ plan.month_price / 100 }} <small>/月</small></div>
            <ul class="plan-features">
               <li>流量: {{ formatTraffic(plan.transfer_enable) }}</li>
               <li>设备限制: {{ plan.device_limit || '无限制' }}</li>
               <li>速度限制: {{ plan.speed_limit || '无限制' }} Mbps</li>
            </ul>
            <div class="row-actions">
               <a href="javascript:;" @click="editPlan(plan)">编辑</a>
               <span class="sep">|</span>
               <a href="javascript:;" @click="copyPlan(plan)">克隆</a>
            </div>
         </div>
      </div>

      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="plans.length === 0" class="placeholder">暂无套餐数据</div>
    </div>
  `,
  setup() {
    const plans = ref([]);
    const loading = ref(true);

    const loadPlans = async () => {
      loading.value = true;
      try {
        const res = await adminApi.getPlans();
        plans.value = res.data || [];
      } catch (e) {
        console.error('Failed to load plans', e);
      } finally {
        loading.value = false;
      }
    };

    const formatTraffic = (gb) => gb + ' GB'; // Backend usually stores GB for plans

    const addPlan = () => alert('创建套餐功能开发中...');
    const editPlan = (plan) => alert('编辑套餐: ' + plan.name);
    const copyPlan = (plan) => alert('克隆套餐: ' + plan.name);

    onMounted(loadPlans);

    return { plans, loading, formatTraffic, addPlan, editPlan, copyPlan };
  }
};
