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

// 选中的销区
const selectedArea = ref<string>('');
const salesAreas = ref<CustomerVO[]>([]);
const loadingAreas = ref(false);

// 经销商列表
const dealers = ref<CustomerVO[]>([]);
const loadingDealers = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 加载销区列表
async function loadSalesAreas() {
  loadingAreas.value = true;
  try {
    const res = await getSalesAreas();
    // API 返回包装格式：{ code, msg, data }
    salesAreas.value = res?.data || [];
  } catch (error: any) {
    ElMessage.error(error?.message || '加载销区列表失败');
  } finally {
    loadingAreas.value = false;
  }
}

// 加载经销商列表
async function loadDealers() {
  if (!selectedArea.value) {
    dealers.value = [];
    return;
  }

  loadingDealers.value = true;
  try {
    const res = await getCustomerList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      salesAreaCode: selectedArea.value,
    });
    dealers.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || '加载经销商列表失败');
  } finally {
    loadingDealers.value = false;
  }
}

// 选择销区
function handleAreaChange() {
  currentPage.value = 1;
  loadDealers();
}

// 分页
function handlePageChange(page: number) {
  currentPage.value = page;
  loadDealers();
}

// 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];
}

// 状态标签
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);
}

onMounted(() => {
  loadSalesAreas();
});
</script>

<template>
  <div class="dealer-page">
    <!-- Header -->
    <div class="page-header">
      <h1 class="page-title">经销商管理</h1>
      <p class="page-desc">选择销区查看经销商信息</p>
    </div>

    <!-- Sales Area Selection -->
    <div class="area-selector">
      <div class="selector-label">选择销区：</div>
      <el-select
        v-model="selectedArea"
        placeholder="请选择销区"
        clearable
        filterable
        style="width: 300px"
        :loading="loadingAreas"
        @change="handleAreaChange"
      >
        <el-option
          v-for="area in salesAreas"
          :key="area.salesAreaCode"
          :label="`${area.salesAreaName} (${area.salesAreaCode})`"
          :value="area.salesAreaCode"
        />
      </el-select>
      <div v-if="selectedArea" class="area-info">
        <el-tag type="success" effect="plain" round>
          已选销区：{{ salesAreas.find(a => a.salesAreaCode === selectedArea)?.salesAreaName }}
        </el-tag>
      </div>
    </div>

    <!-- Dealer Cards -->
    <div v-if="selectedArea" class="dealer-section">
      <div class="section-header">
        <h3 class="section-title">经销商列表</h3>
        <span class="section-count">共 {{ total }} 家</span>
      </div>

      <div class="dealer-grid" v-loading="loadingDealers">
        <div
          v-for="dealer in dealers"
          :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="!loadingDealers && dealers.length === 0" class="empty-state">
        <el-empty description="该销区暂无经销商数据" />
      </div>

      <!-- Pagination -->
      <div class="pagination-bar" v-if="total > pageSize">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- Empty area hint -->
    <div v-if="!selectedArea" class="empty-area-hint">
      <el-empty description="请先选择销区查看经销商列表" />
    </div>
  </div>
</template>

<style scoped lang="scss">
.dealer-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 28px;
  font-weight: 700;
  color: var(--color-text-primary);
  margin: 0 0 8px;
}

.page-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin: 0;
}

.area-selector {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 32px;
  padding: 20px;
  background: #fff;
  border-radius: var(--radius-lg);
  box-shadow: var(--shadow-sm);
}

.selector-label {
  font-size: 14px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.area-info {
  margin-left: auto;
}

.dealer-section {
  margin-top: 24px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin: 0;
}

.section-count {
  font-size: 13px;
  color: var(--color-text-secondary);
}

.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: 40px 0;
}

.pagination-bar {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.empty-area-hint {
  padding: 60px 0;
}
</style>