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

// Stats
const opportunityTotal = ref(0);

const crmStats = computed(() => [
  { label: '商机总数', value: opportunityTotal.value.toLocaleString(), icon: 'TrendCharts' 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: 0 },
  { key: 'lead', label: '线索', color: '#94a3b8', count: 0 },
  { key: 'negotiation', label: '谈判中', color: '#f59e0b', count: 0 },
  { key: 'proposal', label: '方案', color: '#8b5cf6', count: 0 },
  { key: 'closing', label: '赢单', color: '#22c55e', count: 0 },
];

// 商机列表数据（真实数据）
const opportunityList = ref<CrmOpportunityVo[]>([]);
const opportunityLoading = ref(false);

// 加载商机列表
async function loadOpportunities() {
  opportunityLoading.value = true;
  try {
    const res = await getOpportunityList({ pageNum: 1, pageSize: 100 });
    opportunityList.value = res.rows || [];
    opportunityTotal.value = res.total || 0;
    updatePipelineCounts();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '加载商机列表失败');
  }
  finally {
    opportunityLoading.value = false;
  }
}

// 更新pipeline计数
function updatePipelineCounts() {
  pipeline[0].count = opportunityList.value.length;
  pipeline[1].count = opportunityList.value.filter((o: CrmOpportunityVo) => o.stage === 'lead').length;
  pipeline[2].count = opportunityList.value.filter((o: CrmOpportunityVo) => o.stage === 'negotiation').length;
  pipeline[3].count = opportunityList.value.filter((o: CrmOpportunityVo) => o.stage === 'proposal').length;
  pipeline[4].count = opportunityList.value.filter((o: CrmOpportunityVo) => o.stage === 'closing').length;
}

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

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

<template>
  <div class="crm-page">
    <!-- Header Stats -->
    <div class="crm-stats">
      <div
        v-for="s 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>

    <!-- Pipeline Section -->
    <div class="pipeline-section">
      <!-- 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 }" />
              {{ stage.label }}
              <span class="pipe-count">{{ stage.count }}</span>
            </div>
          </div>
        </div>
        <div class="toolbar-right">
          <el-input placeholder="搜索商机..." clearable style="width: 220px" />
          <el-button type="primary" round>
            <el-icon><Plus /></el-icon> 新建商机
          </el-button>
        </div>
      </div>

      <!-- Pipeline View -->
      <div v-loading="opportunityLoading" 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 }" />
              {{ stage.label }}
            </span>
            <span class="col-count">{{ stage.count }}</span>
          </div>
          <div class="col-cards">
            <div v-for="opp in getCardsForStage(stage.key)" :key="opp.opportunityId" class="opportunity-card">
              <div class="opp-header">
                <span class="opp-name">{{ opp.opportunityName }}</span>
                <el-tag v-if="opp.stage === 'closing'" type="success" size="small" effect="plain" round>
                  赢单
                </el-tag>
                <el-tag v-else-if="opp.stage === 'lead'" type="info" size="small" effect="plain" round>
                  线索
                </el-tag>
              </div>
              <div class="opp-company">
                {{ opp.dealerName || '经销商' }}
              </div>
              <div class="opp-details">
                <div class="opp-detail">
                  <el-icon :size="13">
                    <User />
                  </el-icon>
                  <span>{{ opp.ownerUserName || '--' }}</span>
                </div>
                <div class="opp-detail">
                  <el-icon :size="13">
                    <Calendar />
                  </el-icon>
                  <span>{{ opp.expectedCloseDate || '--' }}</span>
                </div>
              </div>
              <div class="opp-footer">
                <span class="opp-amount">{{ opp.amount ? `¥${opp.amount.toLocaleString()}` : '--' }}</span>
                <div class="opp-progress">
                  <el-progress :percentage="opp.probability || 0" :stroke-width="4" :show-text="false" :color="stage.color" />
                </div>
              </div>
              <div class="opp-avatars">
                <div v-if="opp.ownerUserName" class="mini-avatar" :style="{ background: '#1d5af3' }">
                  {{ opp.ownerUserName.charAt(0) }}
                </div>
              </div>
            </div>
            <div class="add-card-placeholder">
              <el-icon :size="20">
                <Plus />
              </el-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
  </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; }
}

.pipeline-section {
  background: #fff;
  border-radius: var(--radius-lg);
  padding: 20px;
  box-shadow: var(--shadow-sm);
  margin-bottom: 20px;
}

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

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

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

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

  .toolbar-left,
  .toolbar-right {
    width: 100%;
  }

  .pipeline-tabs {
    flex-wrap: wrap;
  }
}
</style>