<script setup lang="ts">
import type { CrmLeadBo, CrmLeadFollowBo, CrmLeadFollowVo, CrmLeadStatsVo, CrmLeadVo, LeadConvertRequest } from '@/api/crm';
import type { ErpCustomerSelectVo } from '@/api/crm';
import type { UserInfo } from '@/api/user';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted, ref } from 'vue';
import { addLeadFollow, assignLead, convertLeadToDealer, createLead, deleteLead, getLeadFollowRecords, getLeadList, getLeadStats, invalidateLead, restoreLead, updateLead, getErpCustomerSelect } from '@/api/crm';
import { getUserSelectList } from '@/api/user';

// 线索列表数据
const leadList = ref<CrmLeadVo[]>([]);
const leadLoading = ref(false);
const leadTotal = ref(0);

// Stats数据（从后端获取全量统计）
const statsData = ref<CrmLeadStatsVo | null>(null);

// 计算环比变化率
function calcChangeRate(current: number, previous: number): { rate: string, up: boolean } {
  if (previous === 0) {
    return { rate: current > 0 ? '+新增' : '0%', up: current > 0 };
  }
  const change = ((current - previous) / previous) * 100;
  const sign = change >= 0 ? '+' : '';
  return { rate: `${sign}${change.toFixed(1)}%`, up: change >= 0 };
}

// Stats展示数据
const leadStats = ref([
  { label: '线索总数', value: '0', icon: 'User' as const, change: '0%', up: true, bg: '#eef5ff', color: '#1d5af3' },
  { label: '高意向线索', value: '0', icon: 'StarFilled' as const, change: '0%', up: true, bg: '#fef2f2', color: '#dc2626' },
  { label: '本月新增', value: '0', icon: 'Calendar' as const, change: '0%', up: true, bg: '#f0fdf4', color: '#16a34a' },
  { label: '转化率', value: '0%', icon: 'DataAnalysis' as const, change: '0%', up: true, bg: '#faf5ff', color: '#9333ea' },
]);

// 加载统计数据
async function loadLeadStats() {
  try {
    const res = await getLeadStats();
    if (res.data) {
      statsData.value = res.data;

      // 计算环比
      const totalChange = calcChangeRate(res.data.monthlyNewCount, res.data.lastMonthNewCount);
      const highIntentChange = calcChangeRate(res.data.monthlyHighIntentCount, res.data.lastMonthHighIntentCount);
      const newChange = calcChangeRate(res.data.monthlyNewCount, res.data.lastMonthNewCount);
      const conversionChange = calcChangeRate(res.data.monthlyConvertedCount, res.data.lastMonthConvertedCount);

      leadStats.value = [
        { label: '线索总数', value: res.data.totalCount.toString(), icon: 'User' as const, change: totalChange.rate, up: totalChange.up, bg: '#eef5ff', color: '#1d5af3' },
        { label: '高意向线索', value: res.data.highIntentCount.toString(), icon: 'StarFilled' as const, change: highIntentChange.rate, up: highIntentChange.up, bg: '#fef2f2', color: '#dc2626' },
        { label: '本月新增', value: res.data.monthlyNewCount.toString(), icon: 'Calendar' as const, change: newChange.rate, up: newChange.up, bg: '#f0fdf4', color: '#16a34a' },
        { label: '转化率', value: `${res.data.conversionRate}%`, icon: 'DataAnalysis' as const, change: conversionChange.rate, up: conversionChange.up, bg: '#faf5ff', color: '#9333ea' },
      ];
    }
  }
  catch (error: any) {
    ElMessage.error(error?.message || '加载统计数据失败');
  }
}

// 线索筛选参数
const leadFilters = ref({
  keyword: '',
  intentLevel: '',
  ownerUserId: '',
  leadStatus: '',
  pageNum: 1,
  pageSize: 10,
});

// 线索详情Drawer
const showDetailDrawer = ref(false);
const currentLead = ref<CrmLeadVo | null>(null);
const followRecords = ref<CrmLeadFollowVo[]>([]);

// 跟进记录Drawer
const showFollowDrawer = ref(false);
const followForm = ref<CrmLeadFollowBo>({
  leadId: 0,
  followType: 'phone',
  content: '',
  nextFollowTime: undefined,
});

// 新建线索Dialog
const showAddLeadDialog = ref(false);
const leadForm = ref<CrmLeadBo>({
  companyName: '',
  contactName: '',
  mobile: '',
  wechat: '',
  province: '',
  city: '',
  regionId: undefined,
  sourceType: '',
  activityName: '',
  referrerName: '',
  industry: '',
  companyScale: '',
  storeCount: undefined,
  ownerUserId: undefined,
  remark: '',
});

// 编辑线索Dialog
const showEditLeadDialog = ref(false);
const editLeadForm = ref<CrmLeadBo>({
  leadId: 0,
  companyName: '',
  contactName: '',
  mobile: '',
  wechat: '',
  province: '',
  city: '',
  regionId: undefined,
  sourceType: '',
  activityName: '',
  referrerName: '',
  industry: '',
  companyScale: '',
  storeCount: undefined,
  ownerUserId: undefined,
  remark: '',
});

// 手机号验证规则
const mobileValidator = (value: string) => {
  if (!value) {
    return '请输入手机号';
  }
  const mobileRegex = /^1[3-9]\d{9}$/;
  if (!mobileRegex.test(value)) {
    return '手机号格式不正确';
  }
  return '';
};

// 分配线索Dialog
const showAssignDialog = ref(false);
const assignForm = ref({
  leadId: 0,
  ownerUserId: 0,
});
const userList = ref<UserInfo[]>([]);
const userLoading = ref(false);

// 转经销商Dialog
const showConvertDialog = ref(false);
const convertForm = ref<LeadConvertRequest>({
  leadId: 0,
  dealerName: '',
  dealerCode: '',
  customerCode: '',
  signedAt: '',
  level: 'C',
});

// ERP客户选择器
const erpCustomerSelectList = ref<ErpCustomerSelectVo[]>([]);
const erpSelectLoading = ref(false);

// 加载ERP客户选择列表
async function loadErpCustomerSelect(keyword?: string) {
  erpSelectLoading.value = true;
  try {
    const res = await getErpCustomerSelect(keyword);
    erpCustomerSelectList.value = res.data || [];
  } catch {
    ElMessage.error('加载ERP客户列表失败');
  } finally {
    erpSelectLoading.value = false;
  }
}

// 选择ERP客户后自动填充经销商名称
async function handleErpCustomerSelect(customerCode: string) {
  const customer = erpCustomerSelectList.value.find(c => c.customerCode === customerCode);
  if (customer) {
    convertForm.value.dealerName = customer.customerName;
  }
}

// 加载线索列表
async function loadLeads() {
  leadLoading.value = true;
  try {
    const params = {
      companyName: leadFilters.value.keyword,
      intentLevel: leadFilters.value.intentLevel,
      ownerUserId: leadFilters.value.ownerUserId ? Number(leadFilters.value.ownerUserId) : undefined,
      leadStatus: leadFilters.value.leadStatus,
      pageNum: leadFilters.value.pageNum,
      pageSize: leadFilters.value.pageSize,
    };
    const res = await getLeadList(params);
    leadList.value = res.rows || [];
    leadTotal.value = res.total || 0;
  }
  catch (error: any) {
    ElMessage.error(error?.message || '加载线索列表失败');
  }
  finally {
    leadLoading.value = false;
  }
}

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

// AI意向Badge类型
function getIntentBadgeType(level: string): 'danger' | 'warning' | 'info' {
  if (level === 'high')
    return 'danger';
  if (level === 'medium')
    return 'warning';
  return 'info';
}

// 查看ERP客户详情
function viewErpCustomer(lead: CrmLeadVo) {
  if (lead.customerCode) {
    ElMessage.info(`ERP客户编码：${lead.customerCode},可在经销商页面查看详情`);
  }
}

// 线索详情
async function showLeadDetail(lead: CrmLeadVo) {
  currentLead.value = lead;
  showDetailDrawer.value = true;
  await loadFollowRecords(lead.leadId);
}

// 加载跟进记录
async function loadFollowRecords(leadId: number) {
  try {
    const res = await getLeadFollowRecords(leadId);
    followRecords.value = res.data || [];
  }
  catch (error: any) {
    ElMessage.error(error?.message || '加载跟进记录失败');
  }
}

// 打开跟进Drawer
function openFollowDrawer(lead: CrmLeadVo) {
  followForm.value.leadId = lead.leadId;
  followForm.value.followType = 'phone';
  followForm.value.content = '';
  followForm.value.nextFollowTime = undefined;
  showFollowDrawer.value = true;
}

// 提交跟进记录
async function submitFollow() {
  if (!followForm.value.content) {
    ElMessage.warning('请输入跟进内容');
    return;
  }
  try {
    await addLeadFollow(followForm.value);
    ElMessage.success('跟进记录已保存');
    showFollowDrawer.value = false;
    await loadLeads();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '保存跟进记录失败');
  }
}

// 打开新建线索Dialog
function openAddLeadDialog() {
  leadForm.value = {
    companyName: '',
    contactName: '',
    mobile: '',
    wechat: '',
    province: '',
    city: '',
    regionId: undefined,
    sourceType: '',
    activityName: '',
    referrerName: '',
    industry: '',
    companyScale: '',
    storeCount: undefined,
    ownerUserId: undefined,
    remark: '',
  };
  showAddLeadDialog.value = true;
}

// 提交新建线索
async function submitLead() {
  if (!leadForm.value.companyName || !leadForm.value.contactName || !leadForm.value.mobile) {
    ElMessage.warning('请填写必填信息');
    return;
  }

  const mobileError = mobileValidator(leadForm.value.mobile);
  if (mobileError) {
    ElMessage.warning(mobileError);
    return;
  }

  try {
    await createLead(leadForm.value);
    ElMessage.success('线索创建成功');
    showAddLeadDialog.value = false;
    await loadLeads();
    await loadLeadStats();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '创建线索失败');
  }
}

// 打开编辑线索Dialog
function openEditLeadDialog(lead: CrmLeadVo) {
  editLeadForm.value = {
    leadId: lead.leadId,
    companyName: lead.companyName,
    contactName: lead.contactName,
    mobile: lead.mobile,
    wechat: lead.wechat || '',
    province: lead.province || '',
    city: lead.city || '',
    regionId: lead.regionId,
    sourceType: lead.sourceType || '',
    activityName: lead.activityName || '',
    referrerName: lead.referrerName || '',
    industry: lead.industry || '',
    companyScale: lead.companyScale || '',
    storeCount: lead.storeCount,
    ownerUserId: lead.ownerUserId,
    remark: lead.remark || '',
  };
  showEditLeadDialog.value = true;
  loadUserList();
}

// 提交编辑线索
async function submitEditLead() {
  if (!editLeadForm.value.companyName || !editLeadForm.value.contactName || !editLeadForm.value.mobile) {
    ElMessage.warning('请填写必填信息');
    return;
  }

  const mobileError = mobileValidator(editLeadForm.value.mobile);
  if (mobileError) {
    ElMessage.warning(mobileError);
    return;
  }

  try {
    await updateLead(editLeadForm.value);
    ElMessage.success('线索更新成功');
    showEditLeadDialog.value = false;
    await loadLeads();
    await loadLeadStats();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '更新线索失败');
  }
}

// 作废线索
async function handleInvalidateLead(lead: CrmLeadVo) {
  try {
    await ElMessageBox.confirm(
      `确定要作废线索"${lead.companyName}"吗？作废后线索将不再显示在正常列表中。`,
      '作废确认',
      {
        confirmButtonText: '确定作废',
        cancelButtonText: '取消',
        type: 'warning',
      },
    );

    await invalidateLead(lead.leadId);
    ElMessage.success('线索已作废');
    await loadLeads();
    await loadLeadStats();
  }
  catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '作废失败');
    }
  }
}

// 恢复线索
async function handleRestoreLead(lead: CrmLeadVo) {
  try {
    await ElMessageBox.confirm(
      `确定要恢复线索"${lead.companyName}"吗？恢复后线索将重新进入正常流程。`,
      '恢复确认',
      {
        confirmButtonText: '确定恢复',
        cancelButtonText: '取消',
        type: 'info',
      },
    );

    await restoreLead(lead.leadId);
    ElMessage.success('线索已恢复');
    await loadLeads();
    await loadLeadStats();
  }
  catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '恢复失败');
    }
  }
}

// 打开转化Dialog
function convertToDealer(lead: CrmLeadVo) {
  convertForm.value = {
    leadId: lead.leadId,
    dealerName: lead.companyName,
    dealerCode: '',
    customerCode: lead.customerCode || '',
    signedAt: '',
    level: 'C',
  };
  showConvertDialog.value = true;
  loadErpCustomerSelect(); // 加载ERP客户选择列表
}

// 提交转化
async function submitConvert() {
  if (!convertForm.value.dealerName || !convertForm.value.dealerCode) {
    ElMessage.warning('请填写经销商名称和编码');
    return;
  }

  // 校验ERP客户编码必填
  if (!convertForm.value.customerCode) {
    ElMessage.warning('请选择ERP客户编码，经销商必须绑定ERP客户');
    return;
  }

  try {
    await convertLeadToDealer(convertForm.value);
    ElMessage.success('线索转化成功,已创建经销商');
    showConvertDialog.value = false;
    loadLeads();
    loadLeadStats();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '转化失败');
  }
}

// 加载用户列表(用于分配)
async function loadUserList(keyword?: string) {
  userLoading.value = true;
  try {
    const res = await getUserSelectList(keyword);
    userList.value = res.data || [];
  }
  catch (error: any) {
    ElMessage.error(error?.message || '加载用户列表失败');
  }
  finally {
    userLoading.value = false;
  }
}

// 打开分配Dialog
function openAssignDialog(lead: CrmLeadVo) {
  assignForm.value.leadId = lead.leadId;
  assignForm.value.ownerUserId = lead.ownerUserId || 0;
  showAssignDialog.value = true;
  loadUserList();
}

// 提交分配
async function submitAssign() {
  if (!assignForm.value.ownerUserId) {
    ElMessage.warning('请选择负责人');
    return;
  }

  try {
    await assignLead({ leadId: assignForm.value.leadId, ownerUserId: assignForm.value.ownerUserId });
    ElMessage.success('分配成功');
    showAssignDialog.value = false;
    loadLeads();
  }
  catch (error: any) {
    ElMessage.error(error?.message || '分配失败');
  }
}

// 删除线索
async function handleDeleteLead(lead: CrmLeadVo) {
  try {
    await ElMessageBox.confirm(`确定要删除线索"${lead.companyName}"吗?删除后无法恢复。`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    await deleteLead(lead.leadId.toString());
    ElMessage.success('删除成功');
    loadLeads();
  }
  catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error?.message || '删除失败');
    }
  }
}

onMounted(() => {
  loadLeadStats();
  loadLeads();
});
</script>

<template>
  <div class="lead-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1 class="page-title">线索中心</h1>
      <p class="page-desc">管理潜在客户线索，跟进转化</p>
    </div>

    <!-- Header Stats -->
    <div class="lead-stats">
      <div
        v-for="s in leadStats"
        :key="s.label"
        class="lead-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>

    <!-- 筛选栏 -->
    <div class="leads-filter-bar">
      <el-input
        v-model="leadFilters.keyword"
        placeholder="搜索公司、联系人..."
        clearable
        style="width: 240px"
        @keyup.enter="loadLeads"
      />
      <el-select
        v-model="leadFilters.intentLevel"
        placeholder="AI意向等级"
        clearable
        style="width: 140px"
        @change="loadLeads"
      >
        <el-option label="高意向" value="high" />
        <el-option label="中意向" value="medium" />
        <el-option label="低意向" value="low" />
      </el-select>
      <el-select
        v-model="leadFilters.leadStatus"
        placeholder="线索状态"
        clearable
        style="width: 140px"
        @change="loadLeads"
      >
        <el-option label="新线索" value="new" />
        <el-option label="跟进中" value="following" />
        <el-option label="已转化" value="converted" />
        <el-option label="已作废" value="invalid" />
      </el-select>
      <el-button type="primary" @click="loadLeads">
        搜索
      </el-button>
      <el-button type="success" @click="openAddLeadDialog">
        <el-icon><Plus /></el-icon> 新建线索
      </el-button>
    </div>

    <!-- 线索列表表格 -->
    <el-table v-loading="leadLoading" :data="leadList" stripe style="width: 100%">
      <el-table-column prop="companyName" label="公司名称" min-width="180">
        <template #default="{ row }">
          <div class="lead-name-cell">
            <el-tag v-if="row.intentLevel === 'high'" type="danger" effect="plain">
              {{ row.companyName }}
            </el-tag>
            <span v-else>{{ row.companyName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="contactName" label="联系人" width="100" />
      <el-table-column prop="mobile" label="手机" width="120">
        <template #default="{ row }">
          {{ maskPhone(row.mobile) }}
        </template>
      </el-table-column>
      <el-table-column prop="intentLevelName" label="AI意向" width="120">
        <template #default="{ row }">
          <div class="ai-intent-cell">
            <el-tag :type="row.intentLevel ? getIntentBadgeType(row.intentLevel) : 'info'" size="small">
              {{ row.intentLevelName || '--' }}
            </el-tag>
            <span class="ai-score">{{ Math.round(row.aiScore || 0) }}分</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="ownerUserName" label="负责人" width="100">
        <template #default="{ row }">
          <el-avatar v-if="row.ownerUserName" :size="32">
            {{ row.ownerUserName.charAt(0) }}
          </el-avatar>
          <span v-else>--</span>
        </template>
      </el-table-column>
      <el-table-column prop="leadStatusName" label="状态" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" link size="small" @click="showLeadDetail(row)">
              详情
            </el-button>
            <el-button
              v-if="row.leadStatus !== 'converted' && row.leadStatus !== 'invalid'"
              type="primary"
              link
              size="small"
              @click="openEditLeadDialog(row)"
            >
              编辑
            </el-button>
            <el-button type="primary" link size="small" @click="openFollowDrawer(row)">
              跟进
            </el-button>
            <el-button
              v-if="row.leadStatus !== 'converted' && row.leadStatus !== 'invalid'"
              type="warning"
              link
              size="small"
              @click="openAssignDialog(row)"
            >
              分配
            </el-button>
            <el-button
              v-if="row.leadStatus !== 'converted' && row.leadStatus !== 'invalid'"
              type="success"
              link
              size="small"
              @click="convertToDealer(row)"
            >
              转经销商
            </el-button>
            <el-button
              v-if="row.leadStatus !== 'converted' && row.leadStatus !== 'invalid'"
              type="info"
              link
              size="small"
              @click="handleInvalidateLead(row)"
            >
              作废
            </el-button>
            <el-button
              v-if="row.leadStatus === 'invalid'"
              type="success"
              link
              size="small"
              @click="handleRestoreLead(row)"
            >
              恢复
            </el-button>
            <el-button
              v-if="row.leadStatus === 'invalid'"
              type="danger"
              link
              size="small"
              @click="handleDeleteLead(row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="leadFilters.pageNum"
      v-model:page-size="leadFilters.pageSize"
      :total="leadTotal"
      layout="total, prev, pager, next, jumper"
      style="margin-top: 16px; justify-content: flex-end"
      @current-change="loadLeads"
    />

    <!-- 线索详情Drawer -->
    <el-drawer v-model="showDetailDrawer" title="线索详情" size="50%">
      <el-descriptions v-if="currentLead" :column="2" border>
        <el-descriptions-item label="公司名称">
          {{ currentLead.companyName }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">
          {{ currentLead.contactName }}
        </el-descriptions-item>
        <el-descriptions-item label="手机">
          {{ currentLead.mobile }}
        </el-descriptions-item>
        <el-descriptions-item label="ERP客户编码">
          <el-link v-if="currentLead.customerCode" type="primary" @click="viewErpCustomer(currentLead)">
            {{ currentLead.customerCode }}
          </el-link>
          <span v-else>--</span>
        </el-descriptions-item>
        <el-descriptions-item label="来源">
          {{ currentLead.sourceTypeName || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="行业">
          {{ currentLead.industryName || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="门店数">
          {{ currentLead.storeCount || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="AI意向等级">
          <el-progress
            :percentage="Math.round(currentLead.aiScore || 0)"
            :stroke-width="20"
            :color="currentLead.intentLevel ? getIntentBadgeType(currentLead.intentLevel) === 'danger' ? '#dc2626' : getIntentBadgeType(currentLead.intentLevel) === 'warning' ? '#f59e0b' : '#0ea5e9' : '#0ea5e9'"
          />
        </el-descriptions-item>
        <el-descriptions-item label="风险等级">
          <el-tag :type="currentLead.riskLevel === 'high' ? 'danger' : currentLead.riskLevel === 'medium' ? 'warning' : 'info'">
            {{ currentLead.riskLevelName || '--' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="负责人">
          {{ currentLead.ownerUserName || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ currentLead.leadStatusName || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="下次跟进时间">
          {{ currentLead.nextFollowTime || '--' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ currentLead.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ currentLead.remark || '--' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 跟进记录Timeline -->
      <el-divider content-position="left">
        跟进记录
      </el-divider>
      <el-timeline>
        <el-timeline-item v-for="follow in followRecords" :key="follow.followId" :timestamp="follow.createTime" placement="top">
          <el-card>
            <div class="follow-header">
              <span class="follow-type">{{ follow.followTypeName || '--' }}</span>
              <span class="follow-user">{{ follow.followUserName || '--' }}</span>
            </div>
            <div class="follow-content">
              {{ follow.content }}
            </div>
            <div v-if="follow.aiSummary" class="follow-ai-summary">
              <el-icon><MagicStick /></el-icon> AI摘要:{{ follow.aiSummary }}
            </div>
            <div v-if="follow.nextFollowTime" class="follow-next">
              下次跟进:{{ follow.nextFollowTime }}
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>
    </el-drawer>

    <!-- 跟进记录Drawer -->
    <el-drawer v-model="showFollowDrawer" title="跟进记录" size="40%">
      <el-form :model="followForm" label-width="100px">
        <el-form-item label="跟进方式">
          <el-select v-model="followForm.followType" placeholder="选择跟进方式">
            <el-option label="电话" value="phone" />
            <el-option label="企业微信" value="wecom" />
            <el-option label="拜访" value="visit" />
            <el-option label="邮件" value="email" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="跟进内容">
          <el-input v-model="followForm.content" type="textarea" :rows="4" placeholder="请输入跟进内容" />
        </el-form-item>
        <el-form-item label="下次跟进时间">
          <el-date-picker
            v-model="followForm.nextFollowTime"
            type="datetime"
            placeholder="选择下次跟进时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showFollowDrawer = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitFollow">
          保存跟进
        </el-button>
      </template>
    </el-drawer>

    <!-- 新建线索Dialog -->
    <el-dialog v-model="showAddLeadDialog" title="新建线索" width="600px" :close-on-click-modal="false">
      <el-form :model="leadForm" label-width="100px">
        <el-form-item label="公司名称" required>
          <el-input v-model="leadForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="leadForm.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input v-model="leadForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="微信号">
          <el-input v-model="leadForm.wechat" placeholder="请输入微信号(可选)" />
        </el-form-item>
        <el-row :gutter="16" style="margin-bottom: 18px">
          <el-col :span="12">
            <el-form-item label="省份">
              <el-input v-model="leadForm.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市">
              <el-input v-model="leadForm.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="来源类型">
          <el-select v-model="leadForm.sourceType" placeholder="选择来源类型" style="width: 100%">
            <el-option label="活动" value="activity" />
            <el-option label="推荐" value="referral" />
            <el-option label="网站" value="website" />
            <el-option label="展会" value="exhibition" />
            <el-option label="企业微信" value="wecom" />
            <el-option label="ERP客户" value="erp" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="leadForm.sourceType === 'activity'" label="活动名称">
          <el-input v-model="leadForm.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item v-if="leadForm.sourceType === 'referral'" label="推荐人">
          <el-input v-model="leadForm.referrerName" placeholder="请输入推荐人" />
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="leadForm.industry" placeholder="请输入行业" />
        </el-form-item>
        <el-form-item label="门店数">
          <el-input-number v-model="leadForm.storeCount" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="leadForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddLeadDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitLead">
          创建线索
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑线索Dialog -->
    <el-dialog v-model="showEditLeadDialog" title="编辑线索" width="600px" :close-on-click-modal="false">
      <el-form :model="editLeadForm" label-width="100px">
        <el-form-item label="公司名称" required>
          <el-input v-model="editLeadForm.companyName" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="editLeadForm.contactName" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="手机号" required>
          <el-input v-model="editLeadForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="微信号">
          <el-input v-model="editLeadForm.wechat" placeholder="请输入微信号(可选)" />
        </el-form-item>
        <el-row :gutter="16" style="margin-bottom: 18px">
          <el-col :span="12">
            <el-form-item label="省份">
              <el-input v-model="editLeadForm.province" placeholder="请输入省份" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市">
              <el-input v-model="editLeadForm.city" placeholder="请输入城市" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="来源类型">
          <el-select v-model="editLeadForm.sourceType" placeholder="选择来源类型" style="width: 100%">
            <el-option label="活动" value="activity" />
            <el-option label="推荐" value="referral" />
            <el-option label="网站" value="website" />
            <el-option label="展会" value="exhibition" />
            <el-option label="企业微信" value="wecom" />
            <el-option label="ERP客户" value="erp" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="editLeadForm.sourceType === 'activity'" label="活动名称">
          <el-input v-model="editLeadForm.activityName" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item v-if="editLeadForm.sourceType === 'referral'" label="推荐人">
          <el-input v-model="editLeadForm.referrerName" placeholder="请输入推荐人" />
        </el-form-item>
        <el-form-item label="行业">
          <el-input v-model="editLeadForm.industry" placeholder="请输入行业" />
        </el-form-item>
        <el-form-item label="门店数">
          <el-input-number v-model="editLeadForm.storeCount" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editLeadForm.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditLeadDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitEditLead">
          保存修改
        </el-button>
      </template>
    </el-dialog>

    <!-- 分配线索Dialog -->
    <el-dialog v-model="showAssignDialog" title="分配线索" width="500px" :close-on-click-modal="false">
      <el-alert type="info" :closable="false" style="margin-bottom: 16px">
        选择负责人来跟进此线索
      </el-alert>

      <el-form :model="assignForm" label-width="100px">
        <el-form-item label="负责人" required>
          <el-select
            v-model="assignForm.ownerUserId"
            placeholder="请选择负责人"
            filterable
            :loading="userLoading"
            style="width: 100%"
            @filter-change="(keyword: string) => loadUserList(keyword)"
          >
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="`${user.nickName}(${user.userName})${user.deptName ? ' - ' + user.deptName : ''}`"
              :value="user.userId"
            >
              <div style="display: flex; align-items: center; justify-content: space-between">
                <span>{{ user.nickName }}({{ user.userName }})</span>
                <span v-if="user.deptName" style="color: #8492a6; font-size: 13px">{{ user.deptName }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAssignDialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitAssign">
          确认分配
        </el-button>
      </template>
    </el-dialog>

    <!-- 转经销商Dialog -->
    <el-dialog v-model="showConvertDialog" title="线索转经销商" width="600px" :close-on-click-modal="false">
      <el-alert type="info" :closable="false" style="margin-bottom: 16px">
        转化为经销商前，必须绑定ERP客户编码
      </el-alert>

      <el-form :model="convertForm" label-width="120px">
        <el-form-item label="ERP客户编码" required>
          <el-select
            v-model="convertForm.customerCode"
            placeholder="请选择ERP客户"
            filterable
            :loading="erpSelectLoading"
            style="width: 100%"
            @change="handleErpCustomerSelect"
          >
            <el-option
              v-for="customer in erpCustomerSelectList"
              :key="customer.customerCode"
              :label="`${customer.customerName} (${customer.customerCode})`"
              :value="customer.customerCode"
            >
              <div style="display: flex; justify-content: space-between">
                <span>{{ customer.customerName }}</span>
                <span style="color: #909399">{{ customer.customerCode }}</span>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经销商名称">
          <el-input v-model="convertForm.dealerName" placeholder="自动从ERP获取" disabled />
        </el-form-item>
        <el-form-item label="经销商编码" required>
          <el-input v-model="convertForm.dealerCode" placeholder="请输入经销商编码,如DL20260001" />
        </el-form-item>
        <el-form-item label="签约时间">
          <el-date-picker
            v-model="convertForm.signedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择签约时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="经销商等级">
          <el-select v-model="convertForm.level" style="width: 100%">
            <el-option label="A级经销商" value="A" />
            <el-option label="B级经销商" value="B" />
            <el-option label="C级经销商(默认)" value="C" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showConvertDialog = false">
          取消
        </el-button>
        <el-button type="success" @click="submitConvert">
          确认转化
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.lead-page {
  padding: 20px;
  background: #f8f7f5;
  min-height: 100vh;
}

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

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

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

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

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

.leads-filter-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  background: #fff;
  padding: 16px;
  border-radius: 12px;
  box-shadow: var(--shadow-sm);
  flex-wrap: wrap;
}

.lead-name-cell {
  display: flex;
  align-items: center;
}

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

.follow-type {
  font-weight: 600;
  color: var(--color-text-primary);
}

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

.follow-content {
  margin-bottom: 8px;
  color: var(--color-text-primary);
}

.follow-ai-summary {
  padding: 8px 12px;
  background: #f8f7f5;
  border-radius: 6px;
  font-size: 12px;
  color: var(--color-text-secondary);
  display: flex;
  align-items: center;
  gap: 6px;
}

.follow-next {
  margin-top: 8px;
  font-size: 12px;
  color: var(--color-text-secondary);
}

.operation-buttons {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  gap: 2px;
}

.operation-buttons .el-button {
  padding: 4px 1px;
}

.ai-intent-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.ai-score {
  font-size: 12px;
  color: var(--color-text-secondary);
  font-weight: 500;
}

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

  .leads-filter-bar {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>