<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-form-item label="验证时间" label-width="100px">
              <el-date-picker
                v-model="dateRangeApply"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="临时放行标记" prop="isTemporaryRelease" label-width="100px">
              <el-select v-model="queryParams.isTemporaryRelease" placeholder="请选择临时放行标记" clearable>
                <el-option v-for="dict in release_sign" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" style="margin-left: 40px" @click="handleQuery">查询</el-button>
                <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="similarRecognitionList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column v-if="false" label="记录ID" align="center" prop="recordId" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="出生日期" align="center" prop="birthday" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="来源系统" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <el-table-column label="主客户号" align="center" prop="customerNo" width="180" />
        <el-table-column label="相似主客户号" align="center" prop="similarCustomerNo" width="150" show-overflow-tooltip />
        <el-table-column label="子客户号" align="center" prop="subCustomerNo" width="180" />
        <el-table-column label="相似子客户号" align="center" prop="similarSubCustomerNo" width="120" show-overflow-tooltip />
        <el-table-column label="临时放行标记" align="center" prop="isTemporaryRelease">
          <template #default="scope">
            <dict-tag :options="release_sign" :value="scope.row.isTemporaryRelease" />
          </template>
        </el-table-column>
        <el-table-column label="验证原因" align="center" prop="verificationReason" width="150" />
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
      <el-button v-hasPermi="['customer:similarRecognition:export']" type="warning" plain icon="Download" @click="handleExport">下载</el-button>
    </el-card>

    <!-- 导出进度弹窗 -->
    <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="SimilarRecognition" lang="ts">
import {
  listSimilarRecognition,
  getSimilarRecognition,
  delSimilarRecognition,
  addSimilarRecognition,
  updateSimilarRecognition,
  exportSimilarRecognitionAsync,
  getExportProgress,
  cancelExportTask,
  getLatestRunningTask
} from '@/api/customer/similarRecognition';
import { SimilarRecognitionVO, SimilarRecognitionQuery, SimilarRecognitionForm } from '@/api/customer/similarRecognition/types';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import { onMounted, onActivated, getCurrentInstance, toRefs, ref, reactive } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_yes_no, sys_user_sex, sys_from_system, release_sign } = toRefs<any>(
  proxy?.useDict('sys_yes_no', 'sys_user_sex', 'sys_from_system', 'release_sign')
);

const similarRecognitionList = ref<SimilarRecognitionVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);
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 similarRecognitionFormRef = ref<ElFormInstance>();

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

const initFormData: SimilarRecognitionForm = {
  recordId: undefined,
  customerNo: undefined,
  similarCustomerNo: undefined,
  subCustomerNo: undefined,
  similarSubCustomerNo: undefined,
  name: undefined,
  gender: undefined,
  birthday: undefined,
  system: undefined,
  verificationReason: undefined,
  verificationDetails: undefined,
  verifiedBy: undefined,
  verificationTime: undefined,
  isTemporaryRelease: undefined,
  releaseStartTime: undefined,
  releaseEndTime: undefined,
  remarks: undefined
};
const data = reactive<PageData<SimilarRecognitionForm, SimilarRecognitionQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    customerNo: undefined,
    similarCustomerNo: undefined,
    subCustomerNo: undefined,
    similarSubCustomerNo: undefined,
    name: undefined,
    gender: undefined,
    birthday: undefined,
    system: undefined,
    verificationReason: undefined,
    verificationDetails: undefined,
    verifiedBy: undefined,
    verificationTime: undefined,
    isTemporaryRelease: undefined,
    releaseStartTime: undefined,
    releaseEndTime: undefined,
    remarks: undefined,
    params: {}
  },
  rules: {
    recordId: [{ required: true, message: '记录ID不能为空', trigger: 'blur' }],
    customerNo: [{ required: true, message: '主客户号不能为空', trigger: 'blur' }],
    similarCustomerNo: [{ required: true, message: '相似主客户号不能为空', trigger: 'blur' }],
    subCustomerNo: [{ required: true, message: '子客户号不能为空', trigger: 'blur' }],
    similarSubCustomerNo: [{ required: true, message: '相似子客户号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthday: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '来源系统不能为空', trigger: 'blur' }],
    verificationReason: [{ required: true, message: '验证原因不能为空', trigger: 'blur' }],
    verificationDetails: [{ required: true, message: '详细验证信息不能为空', trigger: 'blur' }],
    verifiedBy: [{ required: true, message: '验证操作员不能为空', trigger: 'blur' }],
    verificationTime: [{ required: true, message: '验证时间不能为空', trigger: 'blur' }],
    isTemporaryRelease: [{ required: true, message: '临时放行标记不能为空', trigger: 'blur' }],
    releaseStartTime: [{ required: true, message: '放行起期不能为空', trigger: 'blur' }],
    releaseEndTime: [{ required: true, message: '放行止期不能为空', trigger: 'blur' }],
    remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

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

/** 查询相似客户认定列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeApply.value, 'verification');
  const res = await listSimilarRecognition(queryParams.value);
  similarRecognitionList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeApply.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SimilarRecognitionVO[]) => {
  ids.value = selection.map((item) => item.recordId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加相似客户认定';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SimilarRecognitionVO) => {
  reset();
  const _recordId = row?.recordId || ids.value[0];
  const res = await getSimilarRecognition(_recordId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改相似客户认定';
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: SimilarRecognitionVO) => {
  const _recordIds = row?.recordId || ids.value;
  await proxy?.$modal.confirm('是否确认删除相似客户认定编号为"' + _recordIds + '"的数据项？').finally(() => (loading.value = false));
  await delSimilarRecognition(_recordIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    loading.value = true;
    const exportParams = proxy?.addDateRange({ ...queryParams.value }, dateRangeApply.value, 'verification');
    const res = await exportSimilarRecognitionAsync(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('导出任务提交失败');
  } finally {
    loading.value = false;
  }
};

/** 取消下载按钮操作 */
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) 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(
            'customer/similarRecognition/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('similarRecognition') === -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) {}
};

onMounted(() => {
  //getList();
  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>


