<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row>
              <el-form-item label="使用厂商" prop="vendor">
                <el-select v-model="queryParams.providerId" placeholder="请选择使用厂商" clearable>
                  <el-option
                    v-for="provider in serviceProviderList"
                    :key="provider.providerId"
                    :label="provider.providerName"
                    :value="provider.providerId"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="归属系统" prop="system">
                <el-select v-model="queryParams.system" placeholder="请选择所属系统" clearable>
                  <el-option v-for="dict in msg_system" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="销售渠道" prop="salesChannel">
                <el-select v-model="queryParams.salesChannel" placeholder="请选择销售渠道" clearable>
                  <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>

            </el-row>
            <!--            <el-form-item label="短信来源" prop="smsSource">-->
            <!--              <el-select v-model="queryParams.smsSource" placeholder="请选择短信来源" clearable>-->
            <!--                <el-option v-for="dict in sms_source" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <!--            &lt;!&ndash;-->

            <!--            &ndash;&gt;-->

            <el-row>
              <el-form-item  label="业务渠道" prop="businessChannel">
                <el-select v-model="queryParams.businessChannel" placeholder="请选择业务渠道" clearable>
                  <el-option v-for="dict in business_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="短信名称" prop="smsName">
                <el-input v-model="queryParams.smsName" placeholder="请输入短信名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="发送方式" prop="sendType">
                <el-select v-model="queryParams.sendType" placeholder="请选择短信分类" clearable>
                  <el-option v-for="dict in send_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker v-model="queryParams.beginDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择开始日期" />
            </el-form-item>

            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker v-model="queryParams.endDate" clearable type="date" value-format="YYYY-MM-DD" placeholder="请选择结束日期" />
            </el-form-item>
            <el-form-item style="width: 100%">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['msg:checklist:export']">导出</el-button>
          </el-col>
<!--          <el-col :span="1.5">-->
<!--            <el-button type="success" plain icon="Document" @click="handleExportDetail" v-hasPermi="['msg:smscount:export']">导出明细</el-button>-->
<!--          </el-col>-->
        </el-row>
      </template>
      <el-table v-loading="loading" :data="checklistList" @selection-change="handleSelectionChange">
        <!-- 发送方式 -->
        <el-table-column label="发送方式" align="center" prop="sendType">
          <template #default="scope">
            <dict-tag v-if="scope.row.sendType" :options="send_type" :value="scope.row.sendType" />
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 使用厂商 -->
        <el-table-column label="使用厂商" align="center">
          <template #default="scope">
            {{ getProviderName(scope.row.providerId) }}
          </template>
        </el-table-column>

        <!-- 发送时间 -->
        <el-table-column label="发送时间" align="center" prop="sendTime">
          <template #default="scope">
            <span v-if="scope.row.sendTime">{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 短信名称 -->
        <el-table-column label="短信名称" align="center" prop="smsName">
          <template #default="scope">
            {{ scope.row.smsName || '-' }}
          </template>
        </el-table-column>

        <!-- 发送状态 -->
        <el-table-column label="发送状态" align="center" prop="sendStatus">
          <template #default="scope">
            <dict-tag v-if="scope.row.sendStatus" :options="send_status" :value="scope.row.sendStatus" />
            <span v-else>-</span>
          </template>
        </el-table-column>

        <!-- 短信分类 -->
        <el-table-column label="短信分类" align="center" prop="smsType">
          <template #default="scope">
            <span v-if="!scope.row.smsType">-</span>
            <dict-tag v-else-if="hasDictValue(sms_type, scope.row.smsType)" :options="sms_type" :value="scope.row.smsType" />
            <span v-else>{{ scope.row.smsType }}</span>
          </template>
        </el-table-column>

        <!-- 销售渠道 -->
        <el-table-column label="销售渠道" align="center" prop="salesChannel">
          <template #default="scope">
            <span v-if="!scope.row.salesChannel">-</span>
            <dict-tag v-else-if="hasDictValue(sales_channel, scope.row.salesChannel)" :options="sales_channel" :value="scope.row.salesChannel" />
            <span v-else>{{ scope.row.salesChannel }}</span>
          </template>
        </el-table-column>

        <!-- 归属系统 -->
        <el-table-column label="归属系统" align="center" prop="system">
          <template #default="scope">
            <span v-if="!scope.row.system">-</span>
            <dict-tag v-else-if="hasDictValue(msg_system, scope.row.system)" :options="msg_system" :value="scope.row.system" />
            <span v-else>{{ scope.row.system }}</span>
          </template>
        </el-table-column>

        <!-- 业务渠道 -->
        <el-table-column label="业务渠道" align="center" prop="businessChannel">
          <template #default="scope">
            <span v-if="!scope.row.businessChannel">-</span>
            <dict-tag v-else-if="hasDictValue(business_channel, scope.row.businessChannel)" :options="business_channel" :value="scope.row.businessChannel" />
            <span v-else>{{ scope.row.businessChannel }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改短信统计查询对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body>
      <el-form ref="smscountFormRef" :model="form" disabled>
        <el-form-item label="模板唯一标识" prop="templateId">
          <el-input v-model="form.templateId" placeholder="模板唯一标识" />
        </el-form-item>
        <el-form-item label="接收人" prop="recipient" label-width="90px">
          <el-input v-model="form.recipient" placeholder="接收人" />
        </el-form-item>
        <el-form-item label="电话号码" prop="phoneNumber" label-width="90px">
          <el-input v-model="form.phoneNumber" placeholder="电话号码" />
        </el-form-item>
        <el-form-item label="短信内容">
          <editor v-model="form.smsContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime" label-width="90px">
          <el-date-picker v-model="form.sendTime" clearable type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="发送时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发送状态" prop="sendStatus" label-width="90px">
          <el-select v-model="form.sendStatus" placeholder="发送状态">
            <el-option v-for="dict in send_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发送类型" prop="sendType" label-width="90px">
          <el-select v-model="form.sendType" placeholder="发送类型">
            <el-option v-for="dict in send_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="申请批次ID" prop="batchId" label-width="90px">
          <el-input v-model="form.batchId" placeholder="申请批次ID" />
        </el-form-item>
        <el-form-item label="请求报文ID" prop="requestId" label-width="90px">
          <el-input v-model="form.requestId" placeholder="请求报文ID" />
        </el-form-item>
        <el-form-item label="使用厂商" prop="vendor" label-width="90px">
          <el-input v-model="form.vendor" placeholder="使用厂商" />
        </el-form-item>
        <el-form-item label="实际发送条数" prop="actualCount" label-width="90px">
          <el-input v-model="form.actualCount" placeholder="实际发送条数" />
        </el-form-item>
        <el-form-item label="业务渠道" prop="businessChannel" label-width="90px">
          <el-select v-model="form.businessChannel" placeholder="业务渠道">
            <el-option v-for="dict in business_channel" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信来源" prop="smsSource" label-width="90px">
          <el-select v-model="form.smsSource" placeholder="短信来源">
            <el-option v-for="dict in sms_source" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="短信名称" prop="smsName" label-width="90px">
          <el-input v-model="form.smsName" placeholder="短信名称" />
        </el-form-item>
        <el-form-item label="短信分类" prop="smsType" label-width="90px">
          <el-select v-model="form.smsType" placeholder="短信分类">
            <el-option v-for="dict in sms_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <!--<el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button> -->
          <el-button @click="cancel">返 回</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导出进度弹窗 -->
    <el-dialog v-model="exportProgressVisible" title="导出进度" width="400px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="text-align: center; padding: 20px 0">
        <el-progress type="circle" :percentage="exportProgress.percentage" :width="120" :status="exportProgress.percentage === 100 ? 'success' : undefined" />
        <p style="margin-top: 20px; font-size: 14px; color: #606266">已导出 {{ exportProgress.processedCount }} / {{ exportProgress.totalCount }} 条</p>
        <p style="margin-top: 10px; font-size: 12px; color: #909399">点击"后台运行"后任务将继续，完成后自动下载</p>
      </div>
      <template #footer>
        <el-button @click="handleBackgroundFail">取消下载</el-button>
        <el-button @click="handleBackgroundRun">后台运行</el-button>
      </template>
    </el-dialog>

    <!-- 后台运行气泡 -->
    <transition name="el-fade-in">
      <div v-if="showBackgroundTip" class="background-export-tip" @click="reopenProgressDialog">
        <el-icon :size="20" color="#409EFF" style="margin-bottom: 5px"><Loading /></el-icon>
        <div style="font-size: 12px">导出中 {{ exportProgress.percentage }}%</div>
        <div style="font-size: 11px; color: #909399; margin-top: 2px">点击查看</div>
      </div>
    </transition>
  </div>
</template>

<script setup name="Smscount" lang="ts">
import {
  listSmscount,
  getSmscount,
  delSmscount,
  addSmscount,
  updateSmscount,
  getSettlement,
  postSettlement, getChecklist,
  exportSmsChecklistAsync, getExportProgress, cancelExportTask, getLatestRunningTask
} from '@/api/msg/smscount';
import { SmscountVO, SmscountQuery, SmscountForm } from '@/api/msg/smscount/types';
import { queryMSMTemplateList } from '@/api/msg/mestemp';
import { parseTime } from '@/utils/ruoyi';
import { getAllSmsManualChannelConfig } from '@/api/msg/smsServiceConfig';
import { Loading } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { onMounted, onActivated, getCurrentInstance, toRefs, ref, reactive } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { send_type, sms_type, sms_source, business_channel, send_status, msg_system, sales_channel } = toRefs<any>(
  proxy?.useDict('send_type', 'sms_type', 'sms_source', 'business_channel', 'send_status', 'msg_system', 'sales_channel')
);

const serviceProviderList = ref<any[]>([]);
const likeName = ref('');
const templateList = ref<any[]>([]);
const filteredList = ref<any[]>([]);

const checklistList = ref<any[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const exportProgressVisible = ref(false);
const showBackgroundTip = ref(false);
const exportProgress = reactive({
  taskId: '',//任务ID
  percentage: 0,//进度
  processedCount: 0,//已处理
  totalCount: 0//总数
});
let exportTimer: any; //轮询定时
const isExportCancelled = ref(false); //是否已取消导出
const isDownloaded = ref(false); //是否已经下载
const hasShownFailedMessage = ref(false); //是否已显示失败提示

const queryFormRef = ref<ElFormInstance>();
const smscountFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: SmscountForm = {
  sendId: undefined,
  templateId: undefined,
  recipient: undefined,
  phoneNumber: undefined,
  smsContent: undefined,
  sendTime: undefined,
  sendStatus: undefined,
  sendType: undefined,
  batchId: undefined,
  requestId: undefined,
  vendor: undefined,
  actualCount: undefined,
  businessChannel: undefined,
  smsSource: undefined,
  smsName: undefined,
  smsType: undefined
};
const data = reactive<PageData<SmscountForm, SmscountQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateId: undefined,
    recipient: undefined,
    phoneNumber: undefined,
    smsContent: undefined,
    sendTime: undefined,
    sendStatus: undefined,
    sendType: undefined,
    batchId: undefined,
    requestId: undefined,
    providerId: undefined,
    actualCount: undefined,
    businessChannel: undefined,
    smsSource: undefined,
    smsName: undefined,
    smsType: undefined,
    templateCode: undefined,
    system: undefined,
    salesChannel: undefined,
    beginDate: undefined,
    endDate: undefined,
    params: {}
  },
  rules: {
    sendId: [{ required: true, message: '发送记录唯一标识不能为空', trigger: 'blur' }],
    templateId: [{ required: true, message: '模板唯一标识不能为空', trigger: 'blur' }],
    recipient: [{ required: true, message: '接收人不能为空', trigger: 'blur' }],
    phoneNumber: [{ required: true, message: '电话号码不能为空', trigger: 'blur' }],
    smsContent: [{ required: true, message: '短信内容不能为空', trigger: 'blur' }],
    sendTime: [{ required: true, message: '发送时间不能为空', trigger: 'blur' }],
    sendStatus: [{ required: true, message: '发送状态不能为空', trigger: 'change' }],
    sendType: [{ required: true, message: '发送类型不能为空', trigger: 'change' }],
    batchId: [{ required: true, message: '申请批次ID不能为空', trigger: 'blur' }],
    requestId: [{ required: true, message: '请求报文ID不能为空', trigger: 'blur' }],
    vendor: [{ required: true, message: '使用厂商不能为空', trigger: 'blur' }],
    actualCount: [{ required: true, message: '实际发送条数不能为空', trigger: 'blur' }],
    businessChannel: [{ required: true, message: '业务渠道不能为空', trigger: 'change' }],
    smsSource: [{ required: true, message: '短信来源不能为空', trigger: 'change' }],
    smsName: [{ required: true, message: '短信名称不能为空', trigger: 'blur' }],
    smsType: [{ required: true, message: '短信分类不能为空', trigger: 'change' }]
  }
});
// 检查字典表中是否有对应的值
const hasDictValue = (dictList: any[], value: string) => {
  return dictList && dictList.some(item => item.value === value);
};
// 厂商选择相关方法
const getProviderName = (providerId: number | string) => {
  if (!providerId) return '-';
  const provider = serviceProviderList.value.find((item) => item.providerId == providerId);
  return provider ? provider.providerName : providerId;
};
const getAllServiceConfig = async () => {
  try {
    const res = await getAllSmsManualChannelConfig();
    serviceProviderList.value = res || [];
  } catch (error) {
    serviceProviderList.value = [];
  }
};

const { queryParams, form, rules } = toRefs(data);

/** 短信费用统计查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    // 直接传递所有查询参数，包括分页参数
    const res = await getChecklist(queryParams.value);

    // 处理响应数据
    checklistList.value = res.rows;
    total.value = res.total;
  } catch (error) {

  } finally {
    loading.value = false;
  }
};
/** 分页事件处理 */
const handlePagination = (pagination: any) => {
  queryParams.value.pageNum = pagination.page;
  queryParams.value.pageSize = pagination.limit;
  getList();
};
// 格式化金额显示
const formatCurrency = (amount) => {
  if (amount === undefined || amount === null) return '-';
  if (typeof amount === 'number') {
    return '¥' + amount.toFixed(2);
  }
  return amount;
};

// // 格式化成功率显示
// const formatSuccessRate = (rate) => {
//   if (rate === undefined || rate === null) return '-';
//   if (typeof rate === 'number') {
//     return rate.toFixed(2) + '%';
//   }
//   return rate;
// };
//
// // 获取模板名称
// const getTemplateName = (templateCode) => {
//   if (!templateCode) return '-';
//   const template = templateList.value.find(t => t.templateCode === templateCode);
//   return template ? template.templateName : templateCode;
// };
// /** 取消按钮 */
// const cancel = () => {
//   reset();
//   dialog.visible = false;
// };

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  smscountFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  if (queryParams.value.beginDate) {
    queryParams.value.beginDate = parseTime(queryParams.value.beginDate, '{y}-{m}-{d}');
  }
  if (queryParams.value.endDate) {
    queryParams.value.endDate = parseTime(queryParams.value.endDate, '{y}-{m}-{d}');
  }
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.templateCode = undefined;
  queryParams.value.system = undefined;
  queryParams.value.salesChannel = undefined;
  queryParams.value.beginDate = undefined;
  queryParams.value.endDate = undefined;
  queryParams.value.providerId = undefined;
  queryParams.value.pageNum = 1;
  likeName.value = '';
  filteredList.value = templateList.value;
  getList();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: SmscountVO[]) => {
  ids.value = selection.map((item) => item.sendId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// /** 新增按钮操作 */
// const handleAdd = () => {
//   reset();
//   dialog.visible = true;
//   dialog.title = '添加短信统计查询';
// };

// /** 修改按钮操作 */
// const handleUpdate = async (row?: SmscountVO) => {
//   reset();
//   const _sendId = row?.sendId || ids.value[0];
//   const res = await getSmscount(_sendId);
//   Object.assign(form.value, res.data);
//   dialog.visible = true;
//   dialog.title = '修改短信统计查询';
// };

// /** 提交按钮 */
// const submitForm = () => {
//   smscountFormRef.value?.validate(async (valid: boolean) => {
//     if (valid) {
//       buttonLoading.value = true;
//       if (form.value.sendId) {
//         await updateSmscount(form.value).finally(() => (buttonLoading.value = false));
//       } else {
//         await addSmscount(form.value).finally(() => (buttonLoading.value = false));
//       }
//       proxy?.$modal.msgSuccess('操作成功');
//       dialog.visible = false;
//       await getList();
//     }
//   });
// };

// /** 删除按钮操作 */
// const handleDelete = async (row?: SmscountVO) => {
//   const _sendIds = row?.sendId || ids.value;
//   await proxy?.$modal.confirm('是否确认删除短信统计查询编号为"' + _sendIds + '"的数据项？').finally(() => (loading.value = false));
//   await delSmscount(_sendIds);
//   proxy?.$modal.msgSuccess('删除成功');
//   await getList();
// };

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 创建导出参数对象，确保字典值正确映射
    const exportParams = {
      ...queryParams.value,
      salesChannel: queryParams.value.salesChannel ?
        getSalesChannelValue(queryParams.value.salesChannel) :
        undefined,
      system: queryParams.value.system ?
        getDictValue(msg_system.value, queryParams.value.system) :
        undefined,
      businessChannel: queryParams.value.businessChannel ?
        getDictValue(business_channel.value, queryParams.value.businessChannel) :
        undefined,
      sendType: queryParams.value.sendType ?
        getDictValue(send_type.value, queryParams.value.sendType) :
        undefined
    };

    // 移除分页参数，确保导出所有数据
    delete exportParams.pageNum;
    delete exportParams.pageSize;

    const res = await exportSmsChecklistAsync(exportParams);
    const taskId = res.msg || res.data;
    if (!taskId) {
      proxy?.$modal.msgError('获取任务ID失败');
      return;
    }
    exportProgress.taskId = taskId;
    proxy?.$modal.msgSuccess('导出任务已提交，正在后台生成文件...');
    showExportProgress();
  } catch (error) {
    proxy?.$modal.msgError('导出任务提交失败');
  }
};
/** 获取字典值 */
const getDictValue = (dictList: any[], label: string) => {
  const dict = dictList?.find(item => item.label === label);
  return dict ? dict.value : label;
};
/** 取消下载按钮操作 */
const handleBackgroundFail = async() => {
  if (!exportProgress.taskId) return;
  isExportCancelled.value = true;
  isDownloaded.value = false;
  hasShownFailedMessage.value = true;
  clearInterval(exportTimer);
  exportTimer = null;
  exportProgressVisible.value = false;
  showBackgroundTip.value = false;
  try {
    await cancelExportTask(exportProgress.taskId);
  } catch (error) {}
  proxy?.$modal.msgWarning('导出任务已取消');
  exportProgress.taskId = '';
};

/** 显示导出进度弹窗 */
const showExportProgress = () => {
  exportProgress.percentage = 0;
  exportProgress.processedCount = 0;
  exportProgress.totalCount = 0;
  exportProgressVisible.value = false;
  showBackgroundTip.value = true;
  isExportCancelled.value = false;
  isDownloaded.value = false;
  hasShownFailedMessage.value = false;
  const cleanupExport = () => {
    clearInterval(exportTimer);
    exportTimer = null;
    exportProgressVisible.value = false;
    showBackgroundTip.value = false;
  };

  const checkProgress = async () => {
    try {
      if (!exportProgress.taskId || isExportCancelled.value) return;
      const res = await getExportProgress(exportProgress.taskId);
      const task = res.data;
      if (!task) {
        cleanupExport();
        return;
      }
      exportProgress.percentage = task.progress || 0;
      exportProgress.processedCount = task.processedCount || 0;
      exportProgress.totalCount = task.totalCount || 0;
      
      if (task.status === 'completed') {
        if (!isExportCancelled.value && !isDownloaded.value) {
          isDownloaded.value = true;
          cleanupExport();
          proxy?.download(
            '/msg/checklist/export/download/' + exportProgress.taskId,
            {},
            task.fileName || '短信发送清单.xlsx'
          );
          proxy?.$modal.msgSuccess('导出完成！文件下载中...');
        }else{
          cleanupExport();
        }
      } else if (task.status === 'failed') {
        cleanupExport();
        if(!hasShownFailedMessage.value){
          hasShownFailedMessage.value = true;
          if (isExportCancelled.value || (task.errorMessage && task.errorMessage.indexOf('取消') !== -1)) {
            proxy?.$modal.msgWarning('导出任务已取消');
          } else {
            proxy?.$modal.msgError('导出失败：' + (task.errorMessage || '未知错误'));
          }
        }
      }
    } catch (error: any) {
      if (error?.message?.includes('任务不存在') || error?.message?.includes('已过期')){
        cleanupExport();
        return;
      }
      cleanupExport();
      proxy?.$modal.msgError('查询导出进度失败');
    }
  };
  checkProgress();
  if (exportTimer) {
    clearInterval(exportTimer);
    exportTimer = null;
  }
  exportTimer = setInterval(checkProgress, 500);
};

const handleBackgroundRun = () => {
  exportProgressVisible.value = false;
  showBackgroundTip.value = true;
  ElMessage.info('任务将在后台继续，完成后自动下载');
};

const reopenProgressDialog = () => {
  exportProgressVisible.value = true;
  showBackgroundTip.value = false;
};

/** 恢复未完成的导出任务 */
const restoreExportTask = async () => {
  try {
    const res = await getLatestRunningTask();
    const task = res.data;
    if (task && task.taskId) {
      const fileName = task.fileName || '';
      if (fileName && fileName.indexOf('短信发送清单') === -1 && fileName.indexOf('smsChecklist') === -1) {
        return;
      }
      exportProgress.taskId = task.taskId;
      exportProgress.percentage = task.progress || 0;
      exportProgress.processedCount = task.processedCount || 0;
      exportProgress.totalCount = task.totalCount || 0;

      if (task.status != 'completed') {
        showBackgroundTip.value = true;
        showExportProgress();
      }
    }
  } catch (error) {}
};
/** 导出明细按钮操作 */
// const handleExportDetail = () => {
//   // 创建导出参数对象，确保销售渠道值正确映射
//   const exportParams = {
//     ...queryParams.value,
//     // 确保销售渠道值正确映射
//     salesChannel: queryParams.value.salesChannel ?
//       getSalesChannelValue(queryParams.value.salesChannel) :
//       undefined
//   };
//
//   // 移除分页参数，确保导出所有数据
//   delete exportParams.pageNum;
//   delete exportParams.pageSize;
//
//   proxy?.download(
//     'msg/checklist/exportdetail',
//     exportParams,
//     `短信统计明细_${new Date().getTime()}.xlsx`
//   );
// };
/** 获取销售渠道对应的值 */
const getSalesChannelValue = (label: string) => {
  const channel = sales_channel.value.find(item => item.label === label);
  return channel ? channel.value : label;
};
onMounted(() => {
  getList();
  getAllServiceConfig();
  restoreExportTask();
});
</script>
<style scoped>
.background-export-tip {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 100px;
  height: 100px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
}

.background-export-tip:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
  border-color: #409EFF;
}
</style>
