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

// 数据源切换
const dataSource = ref<'erp' | 'crm'>('erp');

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

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

// CRM筛选
const crmFilters = ref({
  lifecycle: '',
  level: '',
  keyword: '',
});

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

// 分页
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);

// ERP客户列表
const erpDealerList = ref<CustomerVO[]>([]);
// CRM经销商列表
const crmDealerList = ref<CrmDealerVo[]>([]);
const loading = ref(false);
const syncLoading = ref(false);

// 同步预警对话框
const showAlertsDialog = ref(false);
const currentAlerts = ref<CrmSyncAlertVo[]>([]);
const currentAlertDealer = ref<CrmDealerVo | null>(null);

// 切换数据源
async function handleDataSourceChange(val: string | number | boolean | undefined) {
  const source = val as 'erp' | 'crm';
  dataSource.value = source;
  currentPage.value = 1;
  if (source === 'erp') {
    await loadErpDealerList();
  } else {
    await loadCrmDealerList();
  }
}

// 加载ERP客户列表
async function loadErpDealerList() {
  loading.value = true;
  try {
    const res = await getCustomerList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: erpFilters.value.keyword || undefined,
      salesAreaCode: erpFilters.value.salesAreaCode || undefined,
      brand: erpFilters.value.brand || undefined,
    });
    const data = res.data || res;
    let rows = data.rows || [];
    if (erpFilters.value.isStop !== '') {
      const stopFlag = Number(erpFilters.value.isStop);
      rows = rows.filter((d: CustomerVO) => d.isStop === stopFlag);
    }
    erpDealerList.value = rows;
    total.value = data.total || 0;
    totalDealers.value = data.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || '加载客户列表失败');
  } finally {
    loading.value = false;
  }
}

// 加载CRM经销商列表
async function loadCrmDealerList() {
  loading.value = true;
  try {
    const res = await getDealerList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      dealerName: crmFilters.value.keyword || undefined,
      lifecycle: crmFilters.value.lifecycle || undefined,
      level: crmFilters.value.level || undefined,
    });
    const data = res.rows ? res : { rows: [], total: 0 };
    crmDealerList.value = data.rows || [];
    total.value = data.total || 0;
    totalDealers.value = data.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || '加载经销商列表失败');
  } finally {
    loading.value = false;
  }
}

// 手动同步经销商
async function handleSync(dealer: CrmDealerVo) {
  syncLoading.value = true;
  try {
    const res = await manualSyncDealer(dealer.dealerId);
    const result = res.data;
    if (result?.success) {
      if (result.updated) {
        ElMessage.success('同步成功，已更新ERP最新信息');
      } else {
        ElMessage.info('数据已是最新，无需更新');
      }
      if (result.alerts && result.alerts.length > 0) {
        showSyncAlertsDialog(dealer, result.alerts);
      }
      await loadCrmDealerList();
    } else {
      ElMessage.error(result?.message || '同步失败');
    }
  } catch {
    ElMessage.error('同步失败');
  } finally {
    syncLoading.value = false;
  }
}

// 显示同步预警对话框
function showSyncAlertsDialog(dealer: CrmDealerVo, alerts: CrmSyncAlertVo[]) {
  currentAlertDealer.value = dealer;
  currentAlerts.value = alerts;
  showAlertsDialog.value = true;
}

// 处理预警
async function handleResolveAlert(alertId: number, action: 'acknowledge' | 'ignore') {
  try {
    await resolveAlert(alertId, action);
    ElMessage.success('预警已处理');
    showAlertsDialog.value = false;
    await loadCrmDealerList();
  } catch {
    ElMessage.error('处理失败');
  }
}

async function loadSalesAreas() {
  try {
    const res = await getSalesAreas();
    salesAreas.value = res?.data || [];
  } catch { /* ignore */ }
}

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

function handleSearch() {
  currentPage.value = 1;
  if (dataSource.value === 'erp') {
    loadErpDealerList();
  } else {
    loadCrmDealerList();
  }
}

function handlePageChange(page: number) {
  currentPage.value = page;
  if (dataSource.value === 'erp') {
    loadErpDealerList();
  } else {
    loadCrmDealerList();
  }
}

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

// CRM生命周期标签
function getLifecycleInfo(item: CrmDealerVo) {
  switch (item.lifecycle) {
    case 'active':
      return { type: 'success' as const, text: '活跃' };
    case 'churn':
      return { type: 'danger' as const, text: '流失' };
    default:
      return { type: 'info' 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(code: string) {
  const idx = code.charCodeAt(code.length - 1) % logoGradients.length;
  return logoGradients[idx];
}

onMounted(() => {
  loadErpDealerList();
  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">{{ dataSource === 'erp' ? '合作客户' : '经销商' }}</span>
        </div>
      </div>
      <!-- 数据源切换 -->
      <el-radio-group v-model="dataSource" @change="handleDataSourceChange">
        <el-radio-button value="erp">ERP客户档案</el-radio-button>
        <el-radio-button value="crm">CRM经销商</el-radio-button>
      </el-radio-group>
    </div>

    <!-- ERP筛选 -->
    <div v-if="dataSource === 'erp'" class="filter-bar">
      <el-select
        v-model="erpFilters.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="erpFilters.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="erpFilters.isStop"
        placeholder="状态"
        clearable
        style="width: 120px"
        @change="handleSearch"
      >
        <el-option label="合作中" value="0" />
        <el-option label="已停用" value="1" />
      </el-select>
      <el-input
        v-model="erpFilters.keyword"
        placeholder="搜索客户名称、编码..."
        clearable
        style="width: 240px"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <span v-if="total > 0" class="total-info">共 {{ total }} 家</span>
    </div>

    <!-- CRM筛选 -->
    <div v-else class="filter-bar">
      <el-select
        v-model="crmFilters.lifecycle"
        placeholder="生命周期"
        clearable
        style="width: 120px"
        @change="handleSearch"
      >
        <el-option label="活跃" value="active" />
        <el-option label="流失" value="churn" />
      </el-select>
      <el-select
        v-model="crmFilters.level"
        placeholder="等级"
        clearable
        style="width: 120px"
        @change="handleSearch"
      >
        <el-option label="A级" value="A" />
        <el-option label="B级" value="B" />
        <el-option label="C级" value="C" />
      </el-select>
      <el-input
        v-model="crmFilters.keyword"
        placeholder="搜索经销商名称、编码..."
        clearable
        style="width: 240px"
        @clear="handleSearch"
        @keyup.enter="handleSearch"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <span v-if="total > 0" class="total-info">共 {{ total }} 家</span>
    </div>

    <!-- ERP客户卡片 -->
    <div v-if="dataSource === 'erp'" v-loading="loading" class="dealer-grid">
      <div
        v-for="dealer in erpDealerList"
        :key="dealer.customerCode"
        class="dealer-card"
      >
        <div class="card-header">
          <div class="dealer-logo" :style="{ background: getLogoBg(dealer.customerCode) }">
            {{ 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>

    <!-- CRM经销商卡片 -->
    <div v-else v-loading="loading" class="dealer-grid">
      <div
        v-for="dealer in crmDealerList"
        :key="dealer.dealerId"
        class="dealer-card"
      >
        <div class="card-header">
          <div class="dealer-logo" :style="{ background: getLogoBg(dealer.dealerCode) }">
            {{ dealer.dealerName.charAt(0) }}
          </div>
          <div class="dealer-identity">
            <span class="dealer-name">{{ dealer.dealerName }}</span>
            <span class="dealer-code">{{ dealer.dealerCode }}</span>
          </div>
          <el-tag :type="getLifecycleInfo(dealer).type" size="small" effect="light" round>
            {{ getLifecycleInfo(dealer).text }}
          </el-tag>
        </div>
        <div class="card-body">
          <div class="detail-row">
            <span class="detail-label">ERP编码</span>
            <span class="detail-value">{{ dealer.customerCode || '--' }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">等级</span>
            <span class="detail-value">{{ dealer.levelName || dealer.level || '--' }}</span>
          </div>
          <div class="detail-row">
            <span class="detail-label">联系人</span>
            <span class="detail-value">{{ dealer.contactName || '--' }} · {{ maskPhone(dealer.mobile || '') }}</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.totalOrderAmount?.toFixed(0) || '--' }}</span>
              <span class="kpi-label">累计订单</span>
            </div>
            <div class="kpi-item">
              <span class="kpi-value">{{ dealer.activityScore?.toFixed(1) || '--' }}</span>
              <span class="kpi-label">活跃评分</span>
            </div>
          </div>
          <!-- 同步状态 -->
          <div class="sync-actions">
            <el-tag v-if="dealer.hasPendingAlerts" type="warning" size="small" effect="plain">
              存在差异
            </el-tag>
            <el-button
              type="primary"
              size="small"
              :loading="syncLoading"
              @click="handleSync(dealer)"
            >
              同步
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- Empty state -->
    <div v-if="!loading && (dataSource === 'erp' ? erpDealerList.length === 0 : crmDealerList.length === 0)" class="empty-state">
      <el-empty description="暂无数据" />
    </div>

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

    <!-- 同步预警对话框 -->
    <el-dialog v-model="showAlertsDialog" title="同步差异预警" width="600px">
      <el-alert type="warning" :closable="false">
        CRM维护的字段与ERP存在差异，请确认是否需要更新
      </el-alert>
      <el-table :data="currentAlerts" style="margin-top: 16px">
        <el-table-column prop="alertType" label="差异类型" />
        <el-table-column prop="alertMessage" label="差异说明" />
        <el-table-column prop="crmValue" label="CRM值" />
        <el-table-column prop="erpValue" label="ERP值" />
        <el-table-column label="操作" width="150">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleResolveAlert(row.id, 'acknowledge')">
              确认
            </el-button>
            <el-button type="info" link size="small" @click="handleResolveAlert(row.id, 'ignore')">
              忽略
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

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

.page-header {
  display: flex;
  align-items: center;
  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);
}

.sync-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.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>