<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" :rules="rules" :inline="true" label-width="100px">
            <el-form-item label="来源系统" prop="sourceCode">
              <el-select v-model="queryParams.sourceCode" placeholder="请选择来源系统" clearable>
                <el-option v-for="dict in bfs_buss_system" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="场景编码" prop="bussType">
              <el-select v-model="queryParams.bussType" clearable placeholder="请选择场景编码">
                <template #header>
                  <el-input v-model="likeCostName" placeholder="可根据场景编码或名称模糊查询" @input="filterByCostIdName"></el-input>
                </template>
                <el-option
                  v-for="option in filteredCostList"
                  :key="option.costId"
                  :label="option.costId + '-' + option.costName"
                  :value="option.costId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="保单号" prop="policyNo">
              <el-input v-model="queryParams.policyNo" clearable placeholder="请输入团体保单号" />
            </el-form-item>
            <el-form-item label="业务号码" prop="businessNo">
              <el-input v-model="queryParams.businessNo" clearable placeholder="请输入业务号码" />
            </el-form-item>
            <el-form-item label="管理机构" prop="policyOrgCode">
              <el-select v-model="queryParams.policyOrgCode" clearable placeholder="请输入保单管理机构">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredManagecom"
                  :key="dict.dictValue"
                  :label="dict.dictValue + '-' + dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="交易日期" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
          <el-row>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button v-hasPermi="['bfs:businessdata:export']" icon="Download" type="success" @click="handleExport">导出</el-button>
            </el-form-item>
          </el-row>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="bussnessDataList">
        <el-table-column label="来源系统" align="center" prop="sourceCode" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="bfs_buss_system" :value="scope.row.sourceCode" />
          </template>
        </el-table-column>
        <el-table-column label="业务场景类别编码" align="center" prop="bussType" width="100px" show-overflow-tooltip />
        <el-table-column label="业务场景类别名称" align="center" prop="bussName" width="220px" show-overflow-tooltip />
        <el-table-column label="保单险种" align="center" prop="policyProductId" width="200px" show-overflow-tooltip />
        <el-table-column label="团单号" align="center" prop="policyNo" width="200px" show-overflow-tooltip />
        <el-table-column label="保单号" align="center" prop="singlePolicyNo" width="200px" show-overflow-tooltip />
        <el-table-column label="险种代码" align="center" prop="productCode" show-overflow-tooltip />
        <el-table-column label="总金额" align="center" prop="amount" width="100px" show-overflow-tooltip />
        <el-table-column label="不含税金额" align="center" prop="income" width="100px" show-overflow-tooltip />
        <el-table-column label="税额" align="center" prop="tax" width="100px" show-overflow-tooltip />
        <el-table-column label="交易日期" align="center" prop="businessDate" width="150px" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="案件ID" align="center" prop="claimId" width="200px" show-overflow-tooltip />
        <el-table-column label="应付号" align="center" prop="actugetno" width="200px" show-overflow-tooltip />
        <el-table-column label="理赔回退标识" align="center" prop="isBack" show-overflow-tooltip />
        <el-table-column label="业务渠道" align="center" prop="channelCode" show-overflow-tooltip />
        <el-table-column label="销售渠道" align="center" prop="salesChannel" show-overflow-tooltip />
        <el-table-column label="收付机构" align="center" prop="subManageCom" width="200px" show-overflow-tooltip />
        <el-table-column label="银行账户代码" align="center" prop="bankAccount" width="200px" show-overflow-tooltip />
        <el-table-column label="银行账户名称" align="center" prop="bankAccountName" width="200px" show-overflow-tooltip />
        <el-table-column label="支付方式" align="center" prop="payMode" show-overflow-tooltip />
        <el-table-column label="保单业务交易号码" align="center" prop="transactionNo" width="200px" show-overflow-tooltip />
        <el-table-column label="保单管理机构" align="center" prop="policyOrgCode" width="200px" show-overflow-tooltip />
        <el-table-column label="首年标志" align="center" prop="snflag" show-overflow-tooltip />
        <el-table-column label="首期标志" align="center" prop="sqflag" show-overflow-tooltip />
        <el-table-column label="缴别" align="center" prop="payIntervalType" show-overflow-tooltip />
        <el-table-column label="缴费期限" align="center" prop="payInterval" show-overflow-tooltip />
        <el-table-column label="缴费期限标志" align="center" prop="payIntervalFlag" show-overflow-tooltip />
        <el-table-column label="业务来源" align="center" prop="businessSource" show-overflow-tooltip />
        <el-table-column label="费用类型" align="center" prop="expenseType" show-overflow-tooltip />
        <el-table-column label="健康险业务标识" align="center" prop="healthLabel" show-overflow-tooltip />
        <el-table-column label="银行记账码" align="center" prop="matchCode" width="200px" show-overflow-tooltip />
        <el-table-column label="开户行" align="center" prop="hbkId" show-overflow-tooltip />
        <el-table-column label="账户标示" align="center" prop="hktId" show-overflow-tooltip />
        <el-table-column label="业务性质" align="center" prop="operSourceType" show-overflow-tooltip />
        <el-table-column label="税率" align="center" prop="taxRate" show-overflow-tooltip />
        <el-table-column label="统一社会信用代码" align="center" prop="taxregno" width="200px" show-overflow-tooltip />
        <el-table-column label="税码" align="center" prop="taxCode" show-overflow-tooltip />
        <el-table-column label="佣金大类编码" align="center" prop="cwCode" show-overflow-tooltip />
        <el-table-column label="佣金项编码" align="center" prop="cwItem" show-overflow-tooltip />
        <el-table-column label="承诺项目" align="center" prop="budgetCode" show-overflow-tooltip />
        <el-table-column label="业务号码" align="center" prop="businessNo" width="200px" show-overflow-tooltip />
      </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="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 lang="ts">
import { getBussnessData, getCacheList, exportBussnessData, getBussnessExportProgress, bussnessCancelExport, getBussnessLatestExportTask } from '@/api/bfs/busnessQury/costBalance';
import {queryManageCom} from "@/api/bfs/cache";
import { ElMessage } from 'element-plus';
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from 'vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { bfs_buss_system, sys_managecom } = toRefs<any>(proxy?.useDict('bfs_buss_system', 'sys_managecom'));

const total = ref(0);
const showSearch = ref(true);
const loading = ref(false);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sourceCode: undefined,
    bussType: undefined,
    policyNo: undefined,
    businessNo: undefined,
    policyOrgCode: undefined,
    dateRange: undefined
  },
  rules: {
    policyOrgCode: [{ required: true, message: '保单管理机构不能为空', trigger: 'blur' }],
    dateRange: [{ required: true, message: '交易日期不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const likeCostName = ref('');
const filteredCostList = ref([]);
const selectCostList = ref([]);
const likeName = ref('');
const filteredManagecom = ref([]);
const queryFormRef = ref<ElFormInstance>();
const bussnessDataList = ref([]);
const sys_managecomCache = ref([]);
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 getCache = async () => {
  const res = await getCacheList();
  selectCostList.value = res.data.costIdList;
  filteredCostList.value = selectCostList.value;
};

const getCacheManageCom = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

const filterByCostIdName = () => {
  if (likeCostName.value) {
    filteredCostList.value = selectCostList.value.filter((item) => {
      return item.costId.includes(likeCostName.value) || item.costName.includes(likeCostName.value);
    });
  } else {
    filteredCostList.value = selectCostList.value;
  }
};

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecomCache.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecomCache.value;
  }
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
};

const getList = () => {
  queryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const res = await getBussnessData(proxy?.addDateRange(queryParams.value, queryParams.value.dateRange));
      bussnessDataList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
};
/** 导出按钮操作 */
const handleExport = async () => {
  try {
    loading.value = true;
    const exportParams = proxy?.addDateRange({ ...queryParams.value }, queryParams.value.dateRange);
    const res = await exportBussnessData(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 bussnessCancelExport(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 getBussnessExportProgress(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(
            'bfs/bussnessQury/exportBussnessData/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 getBussnessLatestExportTask();
    const task = res.data;
    if (task && task.taskId) {
      const fileName = task.fileName || '';
      if (fileName && fileName.indexOf('业务数据信息') === -1 && fileName.indexOf('bussnessData') === -1) {
        return;
      }
      exportProgress.taskId = task.taskId;
      exportProgress.percentage = task.progress || 0;
      exportProgress.processedCount = task.processedCount || 0;
      exportProgress.totalCount = task.totalCount || 0;
      if (task.status === 'running') {
        showBackgroundTip.value = true;
        showExportProgress();
      }
    }
  } catch (error) {}
};

onMounted(() => {
  getCache();
  getCacheManageCom();
  restoreExportTask();
});
</script>

<style scoped lang="scss">
.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>
