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

// Stats
const customerTotal = ref(0);

const crmStats = computed(() => [
  { label: '客户总数', value: customerTotal.value.toLocaleString(), icon: 'UserFilled' as const, change: '+5.2%', up: true, bg: '#eef5ff', color: '#1d5af3' },
  { label: '商机金额', value: '¥4,680万', icon: 'Money' as const, change: '+12.8%', up: true, bg: '#f0fdf4', color: '#16a34a' },
  { label: '本月赢单', value: '23', icon: 'Trophy' as const, change: '+15%', up: true, bg: '#fef3c7', color: '#d97706' },
  { label: '转化率', value: '32%', icon: 'DataLine' as const, change: '-2.1%', up: false, bg: '#fef2f2', color: '#dc2626' },
]);

// Pipeline
const activeStage = ref('all');

const pipeline = [
  { key: 'all', label: '全部', color: '#1d5af3', count: 42 },
  { key: 'lead', label: '线索', color: '#94a3b8', count: 15 },
  { key: 'negotiation', label: '谈判中', color: '#f59e0b', count: 12 },
  { key: 'proposal', label: '方案', color: '#8b5cf6', count: 8 },
  { key: 'closing', label: '赢单', color: '#22c55e', count: 7 },
];

const opportunities = [
  { id: 1, name: '智能制造系统升级', company: '创新科技有限公司', owner: '刘洋', closeDate: '2026-04-30', amount: '¥580万', progress: 75, priority: '高', priorityType: 'danger' as const, stage: 'negotiation', team: [{ name: '刘', color: '#1d5af3' }, { name: '李', color: '#8b5cf6' }] },
  { id: 2, name: '数据中心服务器采购', company: '盛通电子集团', owner: '李娜', closeDate: '2026-05-15', amount: '¥1,200万', progress: 40, priority: '高', priorityType: 'danger' as const, stage: 'proposal', team: [{ name: '李', color: '#8b5cf6' }, { name: '张', color: '#16a34a' }, { name: '赵', color: '#d97706' }] },
  { id: 3, name: 'ERP系统部署', company: '恒达科技', owner: '张磊', closeDate: '2026-04-20', amount: '¥320万', progress: 90, priority: '中', priorityType: 'warning' as const, stage: 'closing', team: [{ name: '张', color: '#16a34a' }] },
  { id: 4, name: 'IoT平台建设', company: '鑫盛电子', owner: '陈晨', closeDate: '2026-06-01', amount: '¥860万', progress: 20, priority: '高', priorityType: 'danger' as const, stage: 'lead', team: [{ name: '陈', color: '#0ea5e9' }, { name: '刘', color: '#1d5af3' }] },
  { id: 5, name: '安防监控系统', company: '博远通信', owner: '赵敏', closeDate: '2026-05-20', amount: '¥280万', progress: 55, priority: '中', priorityType: 'warning' as const, stage: 'negotiation', team: [{ name: '赵', color: '#d97706' }] },
  { id: 6, name: '云迁移服务', company: '瑞达精密', owner: '刘洋', closeDate: '2026-04-15', amount: '¥450万', progress: 95, priority: '低', priorityType: 'info' as const, stage: 'closing', team: [{ name: '刘', color: '#1d5af3' }, { name: '孙', color: '#dc2626' }] },
  { id: 7, name: 'AI质检系统', company: '华信达', owner: '李娜', closeDate: '2026-07-01', amount: '¥680万', progress: 10, priority: '中', priorityType: 'warning' as const, stage: 'lead', team: [{ name: '李', color: '#8b5cf6' }] },
];

function getCardsForStage(stage: string) {
  if (stage === 'all') return opportunities;
  return opportunities.filter(o => o.stage === stage);
}

// Customer table
const search = ref('');
const customers = ref<CustomerVO[]>([]);
const loading = ref(false);

const customerTableData = computed(() => {
  if (!search.value) return customers.value;
  const kw = search.value.toLowerCase();
  return customers.value.filter(c =>
    c.customerName.toLowerCase().includes(kw)
    || c.contactName.toLowerCase().includes(kw)
  );
});

function getLevelInfo(item: CustomerVO) {
  if (item.pricePlanName?.includes('VIP')) return { level: 'VIP', levelType: 'danger' as const };
  if (item.isStop === 1) return { level: '停用', levelType: 'info' as const };
  return { level: 'A', levelType: '' as const };
}

function getStatusInfo(item: CustomerVO) {
  if (item.isStop === 1) return { status: '已停用', statusColor: '#dc2626' };
  return { status: '活跃', statusColor: '#22c55e' };
}

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)',
];

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

async function loadCustomers() {
  loading.value = true;
  try {
    const res = await getCustomerList({ pageNum: 1, pageSize: 50, keyword: '' });
    customers.value = res.rows || [];
    customerTotal.value = res.total || 0;
  } catch (error: any) {
    ElMessage.error(error?.message || '加载客户列表失败');
  } finally {
    loading.value = false;
  }
}

// Add customer dialog
const showAddCustomer = ref(false);
const customerForm = ref({ name: '', industry: '', contact: '', phone: '', source: '', estimatedAmount: 0, remark: '' });

function handleAddCustomer() {
  ElMessage.success('客户创建成功');
  showAddCustomer.value = false;
  customerForm.value = { name: '', industry: '', contact: '', phone: '', source: '', estimatedAmount: 0, remark: '' };
}

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

<template>
  <div class="crm-page">
    <!-- Header Stats -->
    <div class="crm-stats">
      <div v-for="(s, i) in crmStats" :key="s.label" class="crm-stat-card">
        <div class="stat-icon-wrap" :style="{ background: s.bg }">
          <el-icon :size="22" :style="{ color: s.color }"><component :is="s.icon" /></el-icon>
        </div>
        <div class="stat-body">
          <span class="stat-num">{{ s.value }}</span>
          <span class="stat-lbl">{{ s.label }}</span>
        </div>
        <div class="stat-change" :class="s.up ? 'up' : 'down'">
          <el-icon :size="12"><component :is="s.up ? 'Top' : 'Bottom'" /></el-icon>
          {{ s.change }}
        </div>
      </div>
    </div>

    <!-- Tabs & Filters -->
    <div class="crm-toolbar">
      <div class="toolbar-left">
        <div class="pipeline-tabs">
          <div
            v-for="stage in pipeline"
            :key="stage.key"
            class="pipe-tab"
            :class="{ active: activeStage === stage.key }"
            @click="activeStage = stage.key"
          >
            <span class="pipe-dot" :style="{ background: stage.color }"></span>
            {{ stage.label }}
            <span class="pipe-count">{{ stage.count }}</span>
          </div>
        </div>
      </div>
      <div class="toolbar-right">
        <el-input v-model="search" placeholder="搜索客户、联系人..." clearable style="width: 220px" />
        <el-button type="primary" round @click="showAddCustomer = true">
          <el-icon><Plus /></el-icon> 新建客户
        </el-button>
      </div>
    </div>

    <!-- Pipeline View -->
    <div class="pipeline-view">
      <div v-for="stage in pipeline" :key="stage.key" class="pipeline-col">
        <div class="col-header">
          <span class="col-title">
            <span class="col-dot" :style="{ background: stage.color }"></span>
            {{ stage.label }}
          </span>
          <span class="col-count">{{ stage.count }}</span>
        </div>
        <div class="col-cards">
          <div v-for="card in getCardsForStage(stage.key)" :key="card.id" class="opportunity-card">
            <div class="opp-header">
              <span class="opp-name">{{ card.name }}</span>
              <el-tag :type="card.priorityType" size="small" effect="plain" round>{{ card.priority }}</el-tag>
            </div>
            <div class="opp-company">{{ card.company }}</div>
            <div class="opp-details">
              <div class="opp-detail">
                <el-icon :size="13"><User /></el-icon>
                <span>{{ card.owner }}</span>
              </div>
              <div class="opp-detail">
                <el-icon :size="13"><Calendar /></el-icon>
                <span>{{ card.closeDate }}</span>
              </div>
            </div>
            <div class="opp-footer">
              <span class="opp-amount">{{ card.amount }}</span>
              <div class="opp-progress">
                <el-progress :percentage="card.progress" :stroke-width="4" :show-text="false" :color="stage.color" />
              </div>
            </div>
            <div class="opp-avatars">
              <div v-for="(a, i) in card.team" :key="i" class="mini-avatar" :style="{ background: a.color, zIndex: card.team.length - i }">{{ a.name.charAt(0) }}</div>
            </div>
          </div>
          <div class="add-card-placeholder" @click="showAddCustomer = true">
            <el-icon :size="20"><Plus /></el-icon>
          </div>
        </div>
      </div>
    </div>

    <!-- Customer Table -->
    <div class="customer-section" v-loading="loading">
      <div class="section-header">
        <h3 class="section-title">客户列表</h3>
        <el-button text type="primary" size="small">管理客户</el-button>
      </div>
      <el-table :data="customerTableData" stripe style="width: 100%">
        <el-table-column prop="customerName" label="客户名称" min-width="180">
          <template #default="{ row }">
            <div class="cust-name-cell">
              <div class="cust-avatar" :style="{ background: getAvatarBg(row) }">{{ row.customerName.charAt(0) }}</div>
              <div>
                <span class="cust-name">{{ row.customerName }}</span>
                <span class="cust-industry">{{ row.brandName || '--' }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getLevelInfo(row).levelType" size="small" effect="light" round>{{ getLevelInfo(row).level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contactName" label="联系人" width="100" />
        <el-table-column prop="salesAreaName" label="销区" width="120" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="{ row }">
            <div class="status-dot-wrap">
              <span class="status-dot" :style="{ background: getStatusInfo(row).statusColor }"></span>
              {{ getStatusInfo(row).status }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default>
            <el-button type="primary" link size="small">详情</el-button>
            <el-button type="primary" link size="small">跟进</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- Add Customer Dialog -->
    <el-dialog v-model="showAddCustomer" title="新建客户" width="560px" :close-on-click-modal="false">
      <el-form :model="customerForm" label-position="top">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input v-model="customerForm.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属行业">
              <el-input v-model="customerForm.industry" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="联系人">
              <el-input v-model="customerForm.contact" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="customerForm.phone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="客户来源">
              <el-select v-model="customerForm.source" placeholder="请选择" style="width:100%">
                <el-option label="主动咨询" value="1" />
                <el-option label="展会获取" value="2" />
                <el-option label="老客推荐" value="3" />
                <el-option label="网络推广" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估金额">
              <el-input-number v-model="customerForm.estimatedAmount" :min="0" :step="10000" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="customerForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCustomer = false">取消</el-button>
        <el-button type="primary" @click="handleAddCustomer">创建客户</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

.crm-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 20px;
}

.crm-stat-card {
  background: #fff;
  border-radius: var(--radius-lg);
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 14px;
  box-shadow: var(--shadow-sm);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: all 0.25s ease;

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

.stat-icon-wrap {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.stat-body {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.stat-num {
  font-size: 20px;
  font-weight: 700;
  color: var(--color-text-primary);
  letter-spacing: -0.02em;
}

.stat-lbl {
  font-size: 12.5px;
  color: var(--color-text-secondary);
  margin-top: 2px;
}

.stat-change {
  font-size: 12px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 2px;

  &.up { color: #16a34a; }
  &.down { color: #dc2626; }
}

.crm-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  gap: 12px;
  flex-wrap: wrap;
}

.toolbar-left, .toolbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pipeline-tabs {
  display: flex;
  gap: 4px;
  background: #fff;
  border-radius: 12px;
  padding: 4px;
  box-shadow: var(--shadow-sm);
}

.pipe-tab {
  padding: 7px 16px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  color: var(--color-text-secondary);
  transition: all 0.25s ease;
  display: flex;
  align-items: center;
  gap: 6px;

  &:hover {
    color: var(--color-text-primary);
    background: #f8f7f5;
  }

  &.active {
    background: var(--color-accent);
    color: #fff;
    box-shadow: 0 2px 8px rgba(29, 90, 243, 0.3);
  }
}

.pipe-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

.pipe-count {
  font-size: 11px;
  padding: 1px 6px;
  border-radius: 20px;
  background: rgba(0, 0, 0, 0.06);

  .active > .pipe-count { background: rgba(255, 255, 255, 0.2); }
}

.pipeline-view {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  padding-bottom: 8px;
  margin-bottom: 24px;
}

.pipeline-col {
  min-width: 280px;
  flex: 1;
}

.col-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  padding: 0 4px;
}

.col-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13.5px;
  font-weight: 600;
  color: var(--color-text-primary);
}

.col-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

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

.col-cards {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.opportunity-card {
  background: #fff;
  border-radius: var(--radius-md);
  padding: 16px;
  box-shadow: var(--shadow-sm);
  border: 1px solid rgba(0, 0, 0, 0.04);
  transition: all 0.2s ease;
  cursor: pointer;

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

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

.opp-name {
  font-size: 14px;
  font-weight: 650;
  color: var(--color-text-primary);
}

.opp-company {
  font-size: 12.5px;
  color: var(--color-text-secondary);
  margin-bottom: 12px;
}

.opp-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-bottom: 12px;
}

.opp-detail {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: var(--color-text-secondary);
}

.opp-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.opp-amount {
  font-size: 16px;
  font-weight: 700;
  color: var(--color-accent);
}

.opp-progress {
  width: 80px;
}

.opp-avatars {
  display: flex;
  margin-top: 10px;
}

.mini-avatar {
  width: 26px;
  height: 26px;
  border-radius: 8px;
  color: #fff;
  font-size: 11px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: -6px;
  border: 2px solid #fff;
}

.add-card-placeholder {
  border: 2px dashed #e8e6e1;
  border-radius: var(--radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
  cursor: pointer;
  color: #c4c0b8;
  transition: all 0.25s ease;

  &:hover {
    border-color: var(--color-accent);
    color: var(--color-accent);
    background: #f8faff;
  }
}

.customer-section {
  background: #fff;
  border-radius: var(--radius-lg);
  padding: 22px;
  box-shadow: var(--shadow-sm);
  border: 1px solid rgba(0, 0, 0, 0.04);
}

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

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

.cust-name-cell {
  display: flex;
  align-items: center;
  gap: 12px;
}

.cust-avatar {
  width: 36px;
  height: 36px;
  border-radius: 10px;
  color: #fff;
  font-size: 13px;
  font-weight: 700;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.cust-name {
  display: block;
  font-size: 13.5px;
  font-weight: 600;
  color: var(--color-text-primary);
}

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

.status-dot-wrap {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  justify-content: center;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
}

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

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

  .crm-toolbar {
    flex-direction: column;
    align-items: stretch;
  }

  .toolbar-right {
    justify-content: space-between;
  }
}
</style>
