<template>
  <div class="recommendation-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="searchForm" class="search-form-inline">
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.customerName"
            placeholder="客户姓名/电话/公司"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="推荐状态">
          <el-select
            v-model="searchForm.referralStatus"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="item in ReferralStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐码">
          <el-input
            v-model="searchForm.referralCode"
            placeholder="推荐码"
            clearable
          />
        </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.totalCount || 0 }}</div>
            <div class="stat-label">总推荐</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card warning">
            <div class="stat-value">{{ statistics.pendingCount || 0 }}</div>
            <div class="stat-label">待确认</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card success">
            <div class="stat-value">{{ statistics.validCount || 0 }}</div>
            <div class="stat-label">有效推荐</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card primary">
            <div class="stat-value">{{ statistics.settledCount || 0 }}</div>
            <div class="stat-label">已结算</div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="table-toolbar">
      <div class="toolbar-left">
        <el-button
          type="success"
          :disabled="selectedRows.length === 0"
          @click="handleBatchSettle"
        >
          批量结算 ({{ selectedRows.length }})
        </el-button>
        <el-button @click="handleExport">导出数据</el-button>
      </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="id" label="ID" width="80" />
      <el-table-column prop="referralCode" label="推荐码" width="120" />
      <el-table-column prop="referrerName" label="推荐人" width="110">
        <template #default="{ row }">
          <span v-if="row.referrerName">{{ row.referrerName }}</span>
          <el-tag v-else type="info" size="small">匿名</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="referrerPhone" label="推荐人电话" width="120" />
      <el-table-column prop="customerName" label="客户姓名" width="100" />
      <el-table-column prop="customerPhone" label="客户电话" width="130">
        <template #default="{ row }">
          <span>{{ row.customerPhone }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="customerCompany"
        label="公司名称"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="requirement"
        label="需求描述"
        min-width="180"
        show-overflow-tooltip
      />
      <el-table-column
        prop="referralFee"
        label="推荐费"
        width="100"
        align="right"
      >
        <template #default="{ row }">
          <span v-if="row.referralFee" class="text-red font-bold"
            >¥{{ row.referralFee }}</span
          >
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="referralStatus" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.referralStatus)">{{
            getStatusText(row.referralStatus)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="推荐时间" width="170" />
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <!-- 待确认: 确认 / 作废 -->
          <template v-if="row.referralStatus === 0">
            <el-button
              link
              type="success"
              size="small"
              @click="handleConfirm(row)"
              >确认</el-button
            >
            <el-button
              link
              type="danger"
              size="small"
              @click="handleInvalid(row)"
              >作废</el-button
            >
          </template>
          <!-- 有效: 结算 -->
          <template v-else-if="row.referralStatus === 1">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleSettle(row)"
              >结算</el-button
            >
            <el-button
              link
              type="danger"
              size="small"
              @click="handleInvalid(row)"
              >作废</el-button
            >
          </template>
          <!-- 已结算: 查看 -->
          <template v-else-if="row.referralStatus === 3">
            <el-tag type="success" size="small">已结算</el-tag>
          </template>
          <!-- 无效 -->
          <template v-else-if="row.referralStatus === 2">
            <el-tooltip
              :content="row.invalidReason || '无原因'"
              placement="top"
            >
              <el-tag type="info" size="small">无效</el-tag>
            </el-tooltip>
          </template>
        </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="settleDialogVisible"
      title="结算推荐费"
      width="450px"
      :close-on-click-modal="false"
    >
      <el-form ref="settleFormRef" :model="settleForm" label-width="90px">
        <el-form-item label="推荐费金额">
          <el-input-number
            v-model="settleForm.amount"
            :precision="2"
            :min="0"
            :max="99999"
            :step="10"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结算备注">
          <el-input
            v-model="settleForm.remarks"
            type="textarea"
            :rows="3"
            placeholder="选填"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="settleDialogVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="settleLoading"
          @click="handleSettleSubmit"
          >确定结算</el-button
        >
      </template>
    </el-dialog>

    <!-- 作废弹窗 -->
    <el-dialog
      v-model="invalidDialogVisible"
      title="作废推荐"
      width="450px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="invalidFormRef"
        :model="invalidForm"
        :rules="invalidFormRules"
        label-width="90px"
      >
        <el-form-item label="作废原因" prop="reason">
          <el-input
            v-model="invalidForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入作废原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="invalidDialogVisible = false">取消</el-button>
        <el-button
          type="danger"
          :loading="invalidLoading"
          @click="handleInvalidSubmit"
          >确认作废</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 {
    pageReferral,
    getStatistics,
    confirmReferral,
    invalidateReferral,
    settleReferral,
    batchSettleReferrals,
    exportReferrals,
    ReferralStatusOptions,
    type ReferralRecord,
    type ReferralParam
  } from '@/api/app/referral';

  // 搜索表单
  const searchForm = reactive<ReferralParam>({
    referralStatus: undefined,
    referralCode: undefined,
    customerName: undefined,
    startDate: undefined,
    endDate: undefined
  });
  const dateRange = ref<string[]>([]);
  const loading = ref(false);
  const tableData = ref<ReferralRecord[]>([]);
  const selectedRows = ref<ReferralRecord[]>([]);
  const statistics = ref<Record<string, number>>({});

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

  // 结算弹窗
  const settleDialogVisible = ref(false);
  const settleLoading = ref(false);
  const settleFormRef = ref<FormInstance>();
  const settleForm = reactive({
    id: 0,
    amount: 0,
    remarks: ''
  });

  // 作废弹窗
  const invalidDialogVisible = ref(false);
  const invalidLoading = ref(false);
  const invalidFormRef = ref<FormInstance>();
  const invalidForm = reactive({
    id: 0,
    reason: ''
  });
  const invalidFormRules: FormRules = {
    reason: [{ required: true, message: '请输入作废原因', trigger: 'blur' }]
  };

  // 状态映射
  function getStatusText(status?: number) {
    if (status === null || status === undefined) return '-';
    const item = ReferralStatusOptions.find((s) => s.value === status);
    return item ? item.label : '-';
  }

  function getStatusType(status?: number) {
    switch (status) {
      case 0:
        return 'warning';
      case 1:
        return 'success';
      case 2:
        return 'info';
      case 3:
        return '';
      default:
        return 'info';
    }
  }

  // 日期处理
  function handleDateChange(val: string[] | null) {
    if (val && val.length === 2) {
      searchForm.startDate = val[0];
      searchForm.endDate = val[1];
    } else {
      searchForm.startDate = undefined;
      searchForm.endDate = undefined;
    }
  }

  // 加载统计数据
  async function loadStatistics() {
    try {
      statistics.value = await getStatistics({ ...searchForm });
    } catch {
      // ignore
    }
  }

  // 加载列表
  async function loadData() {
    loading.value = true;
    try {
      const result = await pageReferral({
        ...searchForm,
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
      tableData.value = result.list;
      pagination.total = result.total;
    } catch (err: unknown) {
      ElMessage.error((err as Error).message || '加载失败');
    } finally {
      loading.value = false;
    }
  }

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

  function handleReset() {
    searchForm.referralStatus = undefined;
    searchForm.referralCode = undefined;
    searchForm.customerName = undefined;
    searchForm.startDate = undefined;
    searchForm.endDate = undefined;
    dateRange.value = [];
    pagination.pageNum = 1;
    loadStatistics();
    loadData();
  }

  // 分页
  function handleSizeChange() {
    pagination.pageNum = 1;
    loadData();
  }

  function handlePageChange() {
    loadData();
  }

  // 表格选择
  function handleSelectionChange(rows: ReferralRecord[]) {
    selectedRows.value = rows;
  }

  // 确认有效
  async function handleConfirm(row: ReferralRecord) {
    try {
      await ElMessageBox.confirm('确认该推荐有效？', '确认推荐');
      await confirmReferral(row.id!);
      ElMessage.success('确认成功');
      loadData();
      loadStatistics();
    } catch (err: unknown) {
      if ((err as Error).message) {
        ElMessage.error((err as Error).message);
      }
    }
  }

  // 作废
  function handleInvalid(row: ReferralRecord) {
    invalidForm.id = row.id!;
    invalidForm.reason = '';
    invalidDialogVisible.value = true;
  }

  async function handleInvalidSubmit() {
    if (!invalidFormRef.value) return;
    try {
      await invalidFormRef.value.validate();
      invalidLoading.value = true;
      await invalidateReferral(invalidForm.id, invalidForm.reason);
      ElMessage.success('已作废');
      invalidDialogVisible.value = false;
      loadData();
      loadStatistics();
    } catch (err: unknown) {
      if ((err as Error).message) {
        ElMessage.error((err as Error).message);
      }
    } finally {
      invalidLoading.value = false;
    }
  }

  // 结算
  function handleSettle(row: ReferralRecord) {
    settleForm.id = row.id!;
    settleForm.amount = parseFloat(String(row.referralFee || 0));
    settleForm.remarks = '';
    settleDialogVisible.value = true;
  }

  async function handleSettleSubmit() {
    if (!settleFormRef.value) return;
    settleLoading.value = true;
    try {
      await settleReferral(
        settleForm.id,
        settleForm.amount,
        settleForm.remarks
      );
      ElMessage.success('结算成功');
      settleDialogVisible.value = false;
      loadData();
      loadStatistics();
    } catch (err: unknown) {
      if ((err as Error).message) {
        ElMessage.error((err as Error).message);
      }
    } finally {
      settleLoading.value = false;
    }
  }

  // 批量结算
  async function handleBatchSettle() {
    const validRows = selectedRows.value.filter((r) => r.referralStatus === 1);
    if (validRows.length === 0) {
      ElMessage.warning('请选择状态为「有效」的记录');
      return;
    }
    try {
      await ElMessageBox.confirm(
        `确认结算选中的 ${validRows.length} 条推荐？`,
        '批量结算'
      );
      const ids = validRows.map((r) => r.id!);
      await batchSettleReferrals(ids);
      ElMessage.success('批量结算成功');
      selectedRows.value = [];
      loadData();
      loadStatistics();
    } catch (err: unknown) {
      if ((err as Error).message) {
        ElMessage.error((err as Error).message);
      }
    }
  }

  // 导出
  async function handleExport() {
    try {
      const data = await exportReferrals({ ...searchForm });
      if (!data || data.length === 0) {
        ElMessage.warning('无数据可导出');
        return;
      }
      // 生成 CSV
      const headers = Object.keys(data[0]);
      const csvContent = [
        headers.join(','),
        ...data.map((row) =>
          headers
            .map((h) => {
              const val = (row as Record<string, unknown>)[h];
              return typeof val === 'string' && val.includes(',')
                ? `"${val}"`
                : val ?? '';
            })
            .join(',')
        )
      ].join('\n');
      const blob = new Blob(['\ufeff' + csvContent], {
        type: 'text/csv;charset=utf-8'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `推荐记录_${new Date().toISOString().slice(0, 10)}.csv`;
      a.click();
      URL.revokeObjectURL(url);
      ElMessage.success('导出成功');
    } catch (err: unknown) {
      ElMessage.error((err as Error).message || '导出失败');
    }
  }

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

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

  .statistics-cards {
    margin-bottom: 16px;

    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      text-align: center;
      border: 1px solid #ebeef5;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #333;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }

      &.warning .stat-value {
        color: #e6a23c;
      }
      &.success .stat-value {
        color: #67c23a;
      }
      &.primary .stat-value {
        color: #409eff;
      }
    }
  }

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

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

  .text-red {
    color: #f56c6c;
  }

  .font-bold {
    font-weight: bold;
  }
</style>
