<template>
  <div class="waybill-accounts-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>电子面单账户总览</span>
          <el-button type="primary" size="small" @click="syncAll">同步所有平台</el-button>
        </div>
      </template>

      <!-- 平台选项卡 -->
      <el-tabs v-model="activePlatform" @tab-click="handleTabClick">
        <el-tab-pane
          v-for="platform in platforms"
          :key="platform.code"
          :label="platform.name"
          :name="platform.code"
        >
          <!-- 每个平台的账户表格 -->
          <el-table
            :data="accountsByPlatform[platform.code] || []"
            border
            v-loading="loading[platform.code]"
            style="width:100%"
          >
            <el-table-column prop="expressName" label="快递公司" min-width="120" />
            <el-table-column prop="branchName" label="网点名称" min-width="150" />
            <el-table-column prop="address" label="发货地址" show-overflow-tooltip />
            <el-table-column prop="balance" label="面单余额" width="100">
              <template #default="{row}">
                <span :class="{'warning': row.balance < 10}">{{ row.balance }} 张</span>
              </template>
            </el-table-column>
            <el-table-column prop="used" label="已使用" width="80" />
            <el-table-column prop="canceled" label="已取消" width="80" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{row}">
                <el-button type="primary" size="small" @click="openTakeNo(platform.code, row)">取号</el-button>
                <el-button type="warning" size="small" @click="openCancel(platform.code, row)">取消</el-button>
                <el-button type="info" size="small" @click="viewDetail(platform.code, row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="tab-footer">
            <el-button type="primary" plain @click="syncPlatform(platform.code)">同步本平台</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 取号对话框（可复用之前的） -->
    <el-dialog v-model="takeNoVisible" title="取号" width="600px">
      <el-form :model="takeNoForm" label-width="100px">
        <el-form-item label="平台">
          <span>{{ currentPlatformName }}</span>
        </el-form-item>
        <el-form-item label="快递公司">
          <span>{{ currentAccount?.expressName }}</span>
        </el-form-item>
        <el-form-item label="订单号">
          <el-select v-model="takeNoForm.orderSn" multiple filterable placeholder="请选择订单">
            <el-option v-for="item in pendingOrders" :key="item.id" :label="item.platformOrderSn" :value="item.platformOrderSn" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="takeNoVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTakeNo">确认取号</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getWaybillAccounts, syncWaybillAccounts } from '@/api/platform'

// 平台列表
const platforms = [
  { code: 'pdd', name: '拼多多' },
  { code: 'taobao', name: '淘宝' },
  { code: 'jd', name: '京东' },
  { code: 'douyin', name: '抖音' },
  { code: 'kuaishou', name: '快手' }
]

const activePlatform = ref('pdd')
const accountsByPlatform = reactive<Record<string, any[]>>({})
const loading = reactive<Record<string, boolean>>({})
platforms.forEach(p => {
  accountsByPlatform[p.code] = []
  loading[p.code] = false
})

// 取号相关
const takeNoVisible = ref(false)
const currentPlatform = ref('')
const currentAccount = ref<any>(null)
const takeNoForm = ref({ orderSn: [] })
const pendingOrders = ref<any[]>([]) // 待打印订单

const currentPlatformName = computed(() => {
  return platforms.find(p => p.code === currentPlatform.value)?.name || ''
})

// 加载指定平台账户
const loadPlatformAccounts = async (platform: string) => {
  loading[platform] = true
  try {
    const res = await getWaybillAccounts(platform)
    if (res.code === 200) {
      accountsByPlatform[platform] = res.data
    }
  } finally {
    loading[platform] = false
  }
}

// 同步单个平台
const syncPlatform = async (platform: string) => {
  loading[platform] = true
  try {
    const res = await syncWaybillAccounts(platform)
    if (res.code === 200) {
      accountsByPlatform[platform] = res.data
      ElMessage.success(`${platforms.find(p => p.code === platform)?.name}同步成功`)
    }
  } finally {
    loading[platform] = false
  }
}

// 同步所有平台
const syncAll = async () => {
  for (const platform of platforms) {
    await syncPlatform(platform.code)
  }
  ElMessage.success('所有平台同步完成')
}

// 切换选项卡
const handleTabClick = () => {
  if (accountsByPlatform[activePlatform.value]?.length === 0) {
    loadPlatformAccounts(activePlatform.value)
  }
}

// 打开取号对话框
const openTakeNo = (platform: string, account: any) => {
  currentPlatform.value = platform
  currentAccount.value = account
  takeNoVisible.value = true
  // TODO: 加载待打印订单列表
}

const handleTakeNo = () => {
  ElMessage.info('取号功能待实现')
  takeNoVisible.value = false
}

const openCancel = (platform: string, account: any) => {
  ElMessage.info('取消功能待实现')
}

const viewDetail = (platform: string, account: any) => {
  ElMessage.info('详情功能待实现')
}

onMounted(() => {
  // 默认加载第一个平台的账户
  loadPlatformAccounts(activePlatform.value)
})
</script>

<style scoped>
.waybill-accounts-container {
  padding: 24px;
  background: #f8f9fa;
  min-height: calc(100vh - 64px);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a2e;
}
.tab-footer {
  margin-top: 20px;
  text-align: right;
}
.warning {
  color: #d4af37;
  font-weight: bold;
}
</style>