<template>
  <div class="customer-lead-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" class="search-form-inline">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="姓名/电话/公司" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option
              v-for="item in LeadStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="来源">
          <el-select v-model="searchForm.sourceType" placeholder="请选择" clearable>
            <el-option
              v-for="item in LeadSourceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务员">
          <el-select v-model="searchForm.salesmanId" placeholder="请选择" clearable filterable>
            <el-option
              v-for="item in salesmanList"
              :key="item.userId"
              :label="item.nickname || item.realName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <div class="stat-card">
            <div class="stat-value">{{ statistics.total || 0 }}</div>
            <div class="stat-label">总客资</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card warning">
            <div class="stat-value">{{ statistics.pending || 0 }}</div>
            <div class="stat-label">待跟进</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ statistics.dealed || 0 }}</div>
            <div class="stat-label">已成交</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card primary">
            <div class="stat-value">¥{{ statistics.dealAmount || 0 }}</div>
            <div class="stat-label">成交金额</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleCreate">新增客资</el-button>
        <el-button type="success" @click="handleBatchDispatch">批量派单</el-button>
        <el-button @click="handleExport">导出数据</el-button>
      </div>
      <div class="toolbar-right">
        <el-checkbox v-model="showAssigned" @change="handleShowAssignedChange">只看未分配</el-checkbox>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="leadId" label="ID" width="80" />
      <el-table-column prop="name" label="客户姓名" min-width="100" />
      <el-table-column prop="phone" label="联系电话" width="130" />
      <el-table-column prop="company" label="公司名称" min-width="150" show-overflow-tooltip />
      <el-table-column prop="need" label="需求描述" min-width="180" show-overflow-tooltip />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ row.statusText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sourceType" label="来源" width="100">
        <template #default="{ row }">
          <span>{{ getSourceText(row.sourceType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="assignedUserName" label="业务员" width="120">
        <template #default="{ row }">
          <span v-if="row.assignedUserName">{{ row.assignedUserName }}</span>
          <el-tag v-else type="info" size="small">待分配</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="followCount" label="跟进次数" width="90" align="center" />
      <el-table-column prop="dealAmount" label="成交金额" width="110">
        <template #default="{ row }">
          <span v-if="row.dealAmount">¥{{ row.dealAmount }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="170" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" size="small" @click="handleDetail(row)">详情</el-button>
          <el-button link type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="success" size="small" @click="handleDispatch(row)">派单</el-button>
          <el-button link type="warning" size="small" @click="handleFollow(row)">跟进</el-button>
          <el-button link type="danger" size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入客户姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="formData.company" placeholder="请输入公司名称" />
        </el-form-item>
        <el-form-item label="需求描述">
          <el-input v-model="formData.need" type="textarea" :rows="3" placeholder="请输入需求描述" />
        </el-form-item>
        <el-form-item label="分配业务员">
          <el-select v-model="formData.assignedUserId" placeholder="请选择业务员" clearable filterable>
            <el-option
              v-for="item in salesmanList"
              :key="item.userId"
              :label="item.nickname || item.realName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="formData.remarks" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="客资详情" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户姓名">{{ currentRow?.name }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentRow?.phone }}</el-descriptions-item>
        <el-descriptions-item label="公司名称">{{ currentRow?.company || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentRow?.status)">{{ currentRow?.statusText }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="来源">{{ getSourceText(currentRow?.sourceType) }}</el-descriptions-item>
        <el-descriptions-item label="分配业务员">{{ currentRow?.assignedUserName || '待分配' }}</el-descriptions-item>
        <el-descriptions-item label="推荐人">{{ currentRow?.referrerName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="跟进次数">{{ currentRow?.followCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="成交金额">¥{{ currentRow?.dealAmount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ currentRow?.appointmentTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="需求描述" :span="2">{{ currentRow?.need || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentRow?.remarks || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentRow?.createTime }}</el-descriptions-item>
        <el-descriptions-item label="派单时间">{{ currentRow?.dispatchTime || '-' }}</el-descriptions-item>
      </el-descriptions>
      
      <!-- 跟进记录 -->
      <div class="follow-history">
        <h4>跟进记录</h4>
        <el-timeline v-if="followHistory.length > 0">
          <el-timeline-item
            v-for="item in followHistory"
            :key="item.followId"
            :timestamp="item.createTime"
            placement="top"
          >
            <el-card>
              <p><strong>{{ item.followTypeText }}</strong> - {{ item.userName }}</p>
              <p>{{ item.followContent }}</p>
              <p v-if="item.nextFollowTime" class="next-follow">下次跟进：{{ item.nextFollowTime }} - {{ item.nextFollowPlan }}</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无跟进记录" />
      </div>
    </el-dialog>

    <!-- 派单弹窗 -->
    <el-dialog v-model="dispatchVisible" title="派单" width="500px">
      <el-form ref="dispatchFormRef" :model="dispatchForm" :rules="dispatchRules" label-width="100px">
        <el-form-item label="选择业务员" prop="toUserId">
          <el-select v-model="dispatchForm.toUserId" placeholder="请选择业务员" filterable>
            <el-option
              v-for="item in salesmanList"
              :key="item.userId"
              :label="item.nickname || item.realName"
              :value="item.userId"
            >
              <span>{{ item.nickname || item.realName }}</span>
              <span class="lead-count"> ({{ item.leadCount || 0 }}个客资)</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="派单备注">
          <el-input v-model="dispatchForm.remarks" type="textarea" :rows="3" placeholder="请输入派单备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dispatchVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDispatchSubmit">确定派单</el-button>
      </template>
    </el-dialog>

    <!-- 跟进弹窗 -->
    <el-dialog v-model="followVisible" title="添加跟进记录" width="600px">
      <el-form ref="followFormRef" :model="followForm" :rules="followRules" label-width="100px">
        <el-form-item label="跟进方式" prop="followType">
          <el-radio-group v-model="followForm.followType">
            <el-radio v-for="item in FollowTypeOptions" :key="item.value" :label="item.value">
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="跟进内容" prop="followContent">
          <el-input v-model="followForm.followContent" 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"
          />
        </el-form-item>
        <el-form-item label="下次跟进计划">
          <el-input v-model="followForm.nextFollowPlan" type="textarea" :rows="2" placeholder="请输入下次跟进计划" />
        </el-form-item>
        <el-form-item label="更新状态">
          <el-switch v-model="followForm.updateStatus" />
        </el-form-item>
        <el-form-item v-if="followForm.updateStatus" label="新状态">
          <el-select v-model="followForm.newStatus" placeholder="请选择">
            <el-option
              v-for="item in LeadStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="followVisible = false">取消</el-button>
        <el-button type="primary" @click="handleFollowSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import {
  pageCustomerLead,
  getCustomerLeadDetail,
  createCustomerLead,
  updateCustomerLead,
  updateCustomerLeadStatus,
  dispatchLead,
  batchDispatchLeads,
  addLeadFollowLog,
  getLeadFollowHistory,
  getLeadStatistics
} from '@/api/cms/customerLead';
import {
  CustomerLead,
  CustomerLeadParam,
  LeadDispatchParam,
  LeadFollowParam,
  LeadStatusOptions,
  LeadSourceOptions,
  FollowTypeOptions
} from '@/api/cms/customerLead/model';
import { listUser } from '@/api/system/user';

const loading = ref(false);
const tableData = ref<CustomerLead[]>([]);
const selectedRows = ref<CustomerLead[]>([]);
const statistics = ref<Record<string, number>>({});
const salesmanList = ref<any[]>([]);

// 搜索表单
const searchForm = reactive<CustomerLeadParam>({
  keyword: '',
  status: undefined,
  sourceType: '',
  salesmanId: undefined,
  startDate: '',
  endDate: ''
});
const dateRange = ref<string[]>([]);

// 分页
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
});

// 弹窗状态
const dialogVisible = ref(false);
const detailVisible = ref(false);
const dispatchVisible = ref(false);
const followVisible = ref(false);
const dialogTitle = ref('新增客资');
const isEdit = ref(false);

// 当前行数据
const currentRow = ref<CustomerLead | null>(null);

// 表单数据
const formData = reactive<CustomerLead>({
  name: '',
  phone: '',
  company: '',
  need: '',
  assignedUserId: undefined,
  remarks: ''
});

const formRef = ref<FormInstance>();
const formRules: FormRules = {
  name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }]
};

// 派单表单
const dispatchForm = reactive<LeadDispatchParam>({
  leadId: undefined,
  toUserId: undefined,
  remarks: ''
});
const dispatchFormRef = ref<FormInstance>();
const dispatchRules: FormRules = {
  toUserId: [{ required: true, message: '请选择业务员', trigger: 'change' }]
};

// 跟进表单
const followForm = reactive<LeadFollowParam>({
  leadId: undefined,
  followType: 1,
  followContent: '',
  nextFollowTime: '',
  nextFollowPlan: '',
  updateStatus: false,
  newStatus: undefined
});
const followFormRef = ref<FormInstance>();
const followRules: FormRules = {
  followType: [{ required: true, message: '请选择跟进方式', trigger: 'change' }],
  followContent: [{ required: true, message: '请输入跟进内容', trigger: 'blur' }]
};

// 跟进历史
const followHistory = ref<any[]>([]);

// 显示选项
const showAssigned = ref(false);

// 加载数据
async function loadData() {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    };
    
    const result = await pageCustomerLead(params);
    tableData.value = result.list;
    pagination.total = result.total;
    
    // 如果选中只看未分配，筛选
    if (showAssigned.value) {
      tableData.value = tableData.value.filter(item => !item.assignedUserId);
    }
  } catch (error: any) {
    ElMessage.error(error.message || '加载数据失败');
  } finally {
    loading.value = false;
  }
}

// 加载统计数据
async function loadStatistics() {
  try {
    const result = await getLeadStatistics({});
    statistics.value = result.basic || {};
  } catch (error) {
    console.error('加载统计数据失败', error);
  }
}

// 加载业务员列表
async function loadSalesmanList() {
  try {
    const result = await listUser({ type: 1, pageSize: 100 });
    salesmanList.value = result.list || [];
  } catch (error) {
    console.error('加载业务员列表失败', error);
  }
}

// 搜索
function handleSearch() {
  pagination.pageNum = 1;
  loadData();
  loadStatistics();
}

// 重置
function handleReset() {
  Object.assign(searchForm, {
    keyword: '',
    status: undefined,
    sourceType: '',
    salesmanId: undefined,
    startDate: '',
    endDate: ''
  });
  dateRange.value = [];
  handleSearch();
}

// 日期选择
function handleDateChange(val: string[]) {
  if (val && val.length === 2) {
    searchForm.startDate = val[0];
    searchForm.endDate = val[1];
  } else {
    searchForm.startDate = '';
    searchForm.endDate = '';
  }
}

// 分页
function handleSizeChange(val: number) {
  pagination.pageSize = val;
  loadData();
}

function handlePageChange(val: number) {
  pagination.pageNum = val;
  loadData();
}

// 选择变化
function handleSelectionChange(rows: CustomerLead[]) {
  selectedRows.value = rows;
}

// 获取状态类型
function getStatusType(status?: number) {
  const option = LeadStatusOptions.find(item => item.value === status);
  return option?.color || 'info';
}

// 获取来源文本
function getSourceText(source?: string) {
  const option = LeadSourceOptions.find(item => item.value === source);
  return option?.label || source || '-';
}

// 新增
function handleCreate() {
  dialogTitle.value = '新增客资';
  isEdit.value = false;
  Object.assign(formData, {
    leadId: undefined,
    name: '',
    phone: '',
    company: '',
    need: '',
    assignedUserId: undefined,
    remarks: ''
  });
  dialogVisible.value = true;
}

// 编辑
async function handleEdit(row: CustomerLead) {
  dialogTitle.value = '编辑客资';
  isEdit.value = true;
  try {
    const detail = await getCustomerLeadDetail(row.leadId!);
    Object.assign(formData, detail);
    dialogVisible.value = true;
  } catch (error: any) {
    ElMessage.error(error.message || '获取详情失败');
  }
}

// 详情
async function handleDetail(row: CustomerLead) {
  currentRow.value = row;
  try {
    const detail = await getCustomerLeadDetail(row.leadId!);
    currentRow.value = detail;
    followHistory.value = await getLeadFollowHistory(row.leadId!);
    detailVisible.value = true;
  } catch (error: any) {
    ElMessage.error(error.message || '获取详情失败');
  }
}

// 提交表单
async function handleSubmit() {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          await updateCustomerLead(formData);
          ElMessage.success('更新成功');
        } else {
          await createCustomerLead(formData);
          ElMessage.success('创建成功');
        }
        dialogVisible.value = false;
        loadData();
        loadStatistics();
      } catch (error: any) {
        ElMessage.error(error.message || '操作失败');
      }
    }
  });
}

// 派单
function handleDispatch(row: CustomerLead) {
  dispatchForm.leadId = row.leadId;
  dispatchForm.toUserId = undefined;
  dispatchForm.remarks = '';
  dispatchVisible.value = true;
}

// 批量派单
function handleBatchDispatch() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要派单的客资');
    return;
  }
  
  dispatchForm.leadIds = selectedRows.value.map(row => row.leadId!);
  dispatchForm.batchMode = true;
  dispatchForm.toUserId = undefined;
  dispatchForm.remarks = '';
  dispatchVisible.value = true;
}

// 提交派单
async function handleDispatchSubmit() {
  if (!dispatchFormRef.value) return;
  
  await dispatchFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dispatchForm.batchMode) {
          const result = await batchDispatchLeads(dispatchForm);
          ElMessage.success(`成功派单 ${result.successCount} 条，失败 ${result.failCount} 条`);
        } else {
          await dispatchLead(dispatchForm);
          ElMessage.success('派单成功');
        }
        dispatchVisible.value = false;
        loadData();
        loadStatistics();
      } catch (error: any) {
        ElMessage.error(error.message || '派单失败');
      }
    }
  });
}

// 跟进
function handleFollow(row: CustomerLead) {
  followForm.leadId = row.leadId;
  followForm.followType = 1;
  followForm.followContent = '';
  followForm.nextFollowTime = '';
  followForm.nextFollowPlan = '';
  followForm.updateStatus = false;
  followForm.newStatus = undefined;
  followVisible.value = true;
}

// 提交跟进
async function handleFollowSubmit() {
  if (!followFormRef.value) return;
  
  await followFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await addLeadFollowLog(followForm);
        ElMessage.success('添加跟进成功');
        followVisible.value = false;
        loadData();
        loadStatistics();
      } catch (error: any) {
        ElMessage.error(error.message || '添加跟进失败');
      }
    }
  });
}

// 删除
function handleDelete(row: CustomerLead) {
  ElMessageBox.confirm('确定要删除这条客资吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 调用删除接口
    ElMessage.success('删除成功');
    loadData();
    loadStatistics();
  }).catch(() => {});
}

// 导出
async function handleExport() {
  try {
    // 实际项目中调用导出接口
    ElMessage.info('导出功能开发中...');
  } catch (error: any) {
    ElMessage.error(error.message || '导出失败');
  }
}

// 显示切换
function handleShowAssignedChange() {
  handleSearch();
}

onMounted(() => {
  loadData();
  loadStatistics();
  loadSalesmanList();
});
</script>

<style scoped lang="scss">
.customer-lead-container {
  padding: 16px;
}

.search-form {
  background: #fff;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.statistics-cards {
  margin-bottom: 16px;
  
  .stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    
    .stat-value {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 8px;
    }
    
    .stat-label {
      font-size: 14px;
      opacity: 0.9;
    }
    
    &.warning {
      background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    
    &.success {
      background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    &.primary {
      background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
  }
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .toolbar-left {
    display: flex;
    gap: 8px;
  }
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.follow-history {
  margin-top: 24px;
  border-top: 1px solid #eee;
  padding-top: 16px;
  
  h4 {
    margin-bottom: 16px;
    font-size: 16px;
  }
  
  .next-follow {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }
}

.lead-count {
  color: #909399;
  font-size: 12px;
  margin-left: 8px;
}
</style>
