<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { getCustomerList, getSalesAreas, getBrands, type CustomerVO } from '@/api/erp';
import { ElMessage } from 'element-plus';

// 统计
const totalDealers = ref(0);

// 筛选
const filters = ref({
  salesAreaCode: '',
  brand: '',
  isStop: '' as '' | '0' | '1',
  keyword: '',
});

// 下拉选项
const salesAreas = ref<CustomerVO[]>([]);
const brands = ref<CustomerVO[]>([]);

// 分页
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
const dealerList = ref<CustomerVO[]>([]);
const loading = ref(false);

async function loadDealerList() {
  loading.value = true;
  console.log('=== 开始加载经销商列表 ===');
  console.log('当前页:', currentPage.value, '每页数量:', pageSize.value);
  console.log('筛选条件:', filters.value);

  try {
    const res = await getCustomerList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: filters.value.keyword || undefined,
      salesAreaCode: filters.value.salesAreaCode || undefined,
      brand: filters.value.brand || undefined,
    });
    console.log('API响应:', res);

    // 处理嵌套的响应结构
    const data = res.data || res; // 兼容两种响应格式
    console.log('数据对象:', data);
    console.log('数据行数:', data.rows?.length, '总数:', data.total);

    let rows = data.rows || [];
    // 状态筛选（后端不支持，前端过滤）
    if (filters.value.isStop !== '') {
      const stopFlag = Number(filters.value.isStop);
      rows = rows.filter((d: CustomerVO) => d.isStop === stopFlag);
    }
    dealerList.value = rows;
    total.value = data.total || 0;
    totalDealers.value = data.total || 0;
    console.log('最终显示经销商数量:', dealerList.value.length);
  } catch (error: any) {
    console.error('加载经销商列表失败:', error);
    ElMessage.error(error?.message || '加载经销商列表失败');
  } finally {
    loading.value = false;
  }
}

async function loadSalesAreas() {
  console.log('=== 开始加载销区列表 ===');
  try {
    const res = await getSalesAreas();
    console.log('销区API响应:', res);
    salesAreas.value = res?.data || [];
    console.log('销区数量:', salesAreas.value.length);
  } catch (error) {
    console.error('加载销区失败:', error);
  }
}

async function loadBrands() {
  try {
    const res = await getBrands();
    brands.value = res?.data || [];
  } catch { /* ignore */ }
}

function handleSearch() {
  currentPage.value = 1;
  loadDealerList();
}

function handlePageChange(page: number) {
  currentPage.value = page;
  loadDealerList();
}

// 状态标签
function getStatusInfo(item: CustomerVO) {
  if (item.isStop === 1) {
    return { type: 'danger' as const, text: '已停用' };
  }
  return { type: 'success' as const, text: '合作中' };
}

// 手机号脱敏
function maskPhone(phone: string) {
  if (!phone || phone.length < 7) return phone || '--';
  return phone.slice(0, 3) + '****' + phone.slice(-4);
}

// Logo 渐变色
const logoGradients = [
  'linear-gradient(135deg, #1d5af3, #3378fc)',
  'linear-gradient(135deg, #8b5cf6, #a78bfa)',
  'linear-gradient(135deg, #16a34a, #22c55e)',
  'linear-gradient(135deg, #d97706, #f59e0b)',
  'linear-gradient(135deg, #dc2626, #ef4444)',
  'linear-gradient(135deg, #0ea5e9, #38bdf8)',
  'linear-gradient(135deg, #e11d48, #f43f5e)',
  'linear-gradient(135deg, #64748b, #94a3b8)',
];

function getLogoBg(item: CustomerVO) {
  const idx = item.customerCode.charCodeAt(item.customerCode.length - 1) % logoGradients.length;
  return logoGradients[idx];
}

onMounted(() => {
  console.log('=== 经销商页面已挂载 ===');
  loadDealerList();
  loadSalesAreas();
  loadBrands();
});
</script>

<template>
  <div class="dealer-page">
    <!-- Header -->
    <div class="page-header">
      <div class="header-stats">
        <div class="h-stat">
          <span class="h-stat-value">{{ totalDealers }}</span>
          <span class="h-stat-label">合作经销商</span>
        </div>
      </div>
    </div>

    <!-- Filter -->
    <div class="filter-bar">
      <el-select
        v-model="filters.salesAreaCode"
        placeholder="选择销区"
        clearable
        style="width: 140px"
        @change="handleSearch"
      >
        <el-option
          v-for="area in salesAreas"
          :key="area.salesAreaCode"
          :label="area.salesAreaName"
          :value="area.salesAreaCode"
        />
      </el-select>
      <el-select
        v-model="filters.brand"
        placeholder="选择品牌"
        clearable
        filterable
        style="width: 150px"
        @change="handleSearch"
      >
        <el-option
          v-for="item in brands"
          :key="item.brand"
          :label="item.brandName"
          :value="item.brand"
        />
      </el-select>
      <el-select
        v-model="filters.isStop"
        placeholder="状态"
        clearable
        style="width: 120px"
        @change="handleSearch"
      >
        <el-option label="合作中" value="0" />
        <el-option label="已停用" value="1" />
      </el-select>
      <el-input
        v-model="filters.keyword"
        placeholder="搜索经销商名称、编码..."
        clearable
        style="width: 240px"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <span class="total-info" v-if="total > 0">共 {{ total }} 家</span>
    </div>

    <!-- Dealer Cards -->
    <div class="dealer-grid" v-loading="loading">
      <div
        v-for="dealer in dealerList"
        :key="dealer.customerCode"
        class="dealer-card"
      >
        <div class="card-header">
          <div class="dealer-logo" :style="{ background: getLogoBg(dealer) }">
            {{ dealer.customerName.charAt(0) }}
          </div>
          <div class="dealer-identity">
            <span class="dealer-name">{{ dealer.customerName }}</span>
            <span class="dealer-code">{{ dealer.customerCode }}</span>
          </div>
          <el-tag :type="getStatusInfo(dealer).type" size="small" effect="light" round>
            {{ getStatusInfo(dealer).text }}
          </el-tag>
        </div>
        <div class="card-body">
          <div class="detail-row">
            <span class="detail-label">销区</span>
            <span class="detail-value">{{ dealer.salesAreaName || '--' }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">品牌</span>
            <span class="detail-value">{{ dealer.brandName || '--' }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">联系人</span>
            <span class="detail-value">{{ dealer.contactName || '--' }} · {{ maskPhone(dealer.phone) }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">地址</span>
            <span class="detail-value">{{ [dealer.province, dealer.city].filter(Boolean).join(' ') || '--' }}</span>
          </div>
        </div>
        <div class="card-footer">
          <div class="dealer-kpi">
            <div class="kpi-item">
              <span class="kpi-value">{{ dealer.sdOrgName || '--' }}</span>
              <span class="kpi-label">经销组织</span>
            </div>
            <div class="kpi-item">
              <span class="kpi-value">{{ dealer.pricePlanName || '--' }}</span>
              <span class="kpi-label">价格方案</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty state -->
    <div v-if="!loading && dealerList.length === 0" class="empty-state">
      <el-empty description="暂无经销商数据" />
    </div>

    <!-- Pagination -->
    <div class="pagination-bar" v-if="total > 0">
      <span class="pagination-info">共 {{ total }} 家经销商</span>
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.dealer-page {
  padding: 20px;
}

.page-header {
  display: flex;
  align-items: left;
  justify-content: space-between;
  margin-bottom: 20px;
}

.header-stats {
  display: flex;
  gap: 32px;
}

.h-stat-value {
  display: block;
  font-size: 24px;
  font-weight: 700;
  color: var(--color-text-primary);
  letter-spacing: -0.02em;
}

.h-stat-label {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: center;

  .total-info {
    color: #909399;
    font-size: 14px;
  }
}

.dealer-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

@media (max-width: 1200px) {
  .dealer-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .dealer-grid {
    grid-template-columns: 1fr;
  }
}

.dealer-card {
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: all 0.25s ease;
  overflow: hidden;

  &:hover {
    box-shadow: var(--shadow-md);
    transform: translateY(-2px);
  }
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 20px 14px;
}

.dealer-logo {
  width: 42px;
  height: 42px;
  border-radius: 12px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 700;
  flex-shrink: 0;
}

.dealer-identity {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.dealer-name {
  font-size: 15px;
  font-weight: 650;
  color: var(--color-text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dealer-code {
  font-family: 'SF Mono', Menlo, monospace;
  font-size: 11.5px;
  color: var(--color-text-secondary);
  margin-top: 1px;
}

.card-body {
  padding: 0 20px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.detail-label {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.detail-value {
  font-size: 13px;
  color: var(--color-text-primary);
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 60%;
  text-align: right;
}

.card-footer {
  margin-top: 14px;
  padding: 14px 20px;
  border-top: 1px solid #f5f3f0;
}

.dealer-kpi {
  display: flex;
  justify-content: space-between;
}

.kpi-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.kpi-value {
  font-size: 14px;
  font-weight: 700;
  color: var(--color-text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 100%;
  text-align: center;
}

.kpi-label {
  font-size: 11px;
  color: var(--color-text-secondary);
}

.empty-state {
  padding: 60px 0;
}

.pagination-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;

  .pagination-info {
    font-size: 13px;
    color: var(--color-text-secondary);
  }
}
</style>
