<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" :inline="true" :model="queryParams" label-position="left" label-width="130px">
            <el-row>
              <el-form-item label="管理机构" prop="manageCom">
                <el-select v-model="queryParams.manageCom" 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="payeeName">
                <el-input v-model="queryParams.payeeName" clearable placeholder="请输入收款人姓名"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="收款人银行账号" prop="bankAccount">
                <el-input v-model="queryParams.bankAccount" clearable placeholder="请输入付款人银行账号"
                          @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="实付号" prop="businessReceiptNumber">
                <el-input v-model="queryParams.businessPaymentNumber" clearable placeholder="请输入实收号"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="保单号" prop="policyNumber">
                <el-input v-model="queryParams.policyNumber" clearable placeholder="请输入保单号"
                          @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="业务号" prop="businessNumber">
                <el-input v-model="queryParams.businessNumber" clearable placeholder="请输入业务号"
                          @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="数据来源" prop="fromSystem">
                <el-select v-model="queryParams.fromSystem" clearable placeholder="请输入数据来源">
                  <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付费方式" prop="paymentMethod">
                <el-select v-model="queryParams.paymentMethod" clearable placeholder="请输入付费方式">
                  <el-option v-for="dict in sys_pay_method" :key="dict.value" :label="dict.value + '-' + dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付费状态" prop="paymentStatus">
                <el-select v-model="queryParams.paymentStatus" clearable placeholder="请输入付费状态">
                  <el-option v-for="dict in bls_transfer_status" :key="dict.value" :label="dict.label"
                             :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="应付日期">
                <el-date-picker
                  v-model="dateRangeRece"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="付费日期">
                <el-date-picker
                  v-model="dateRangeChar"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
              <!-- 新增制盘时间选择器 -->
              <el-form-item label="制盘时间">
                <el-date-picker
                  v-model="dateRangeSend"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="退票时间">
                <el-date-picker
                  v-model="dateRangeReversal"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="金额" prop="amount">
                <el-input v-model="amountBigen" clearable style="width: 40%" />
                <div style="margin: 0 10px">-</div>
                <el-input v-model="amountEnd" clearable style="width: 40%" />
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button icon="Search" type="primary" @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">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="payablesList">
        <el-table-column align="center" label="实付号" prop="businessPaymentNumber" show-overflow-tooltip
                         width="150px" />
        <el-table-column align="center" label="数据来源" prop="fromSystem" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="付费方式" prop="paymentMethod" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_pay_method" :value="scope.row.paymentMethod" />
          </template>
        </el-table-column>
<!--        <el-table-column align="center" label="渠道" prop="channel" show-overflow-tooltip width="100px">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="sys_channel" :value="scope.row.channel" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column align="center" label="机构" prop="manageCom" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_managecom" :value="scope.row.manageCom" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款人名称" prop="payeeName" show-overflow-tooltip width="200px" />
        <el-table-column align="center" label="收款人开户行" prop="bankCode" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.bankCode" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款人银行账号" prop="bankAccount" show-overflow-tooltip width="250px" />
        <el-table-column align="center" label="应付日期" prop="payableDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payableDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="实付时间" prop="paymentDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
<!--        <el-table-column align="center" label="保单号" prop="policyNumber" show-overflow-tooltip width="200px" />-->
        <el-table-column align="center" label="业务号" prop="businessNumber" show-overflow-tooltip width="200px" />
        <el-table-column align="center" label="金额" prop="amount" show-overflow-tooltip width="150px" />
        <el-table-column align="center" label="在途状态" prop="inTransitStatus" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="bls_transit_status" :value="scope.row.inTransitStatus" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="工单状态" prop="paymentStatus" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="bls_transfer_status" :value="scope.row.paymentStatus" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="发盘时间" prop="sendDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="成功失败标记" prop="successFailureMark" show-overflow-tooltip
                         width="150px">
          <template #default="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.successFailureMark" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="失败原因" prop="failureReason" show-overflow-tooltip width="250px" />
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
      <el-row>
        <el-button v-hasPermi="['bls:payables:export']" icon="Download" type="success" @click="handleExport">导出数据</el-button>
      </el-row>
    </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 lang="ts" name="Payables" setup>
import { parseTime } from '@/utils/ruoyi';
import { PayablesQuery, PayablesVO } from '@/api/bls/payables/types';
import { listPayables, exportPayablesAsync, getExportProgress, cancelExportTask, getLatestRunningTask } from '@/api/bls/payables';
import {queryManageCom} from "@/api/bls/cache";
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 loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRangeRece = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeChar = ref<[DateModelType, DateModelType]>(['', '']);
const amountBigen = ref<number | null>(null);
const amountEnd = ref<number | null>(null);
const amountRange = ref<[number | null, number | null]>([null, null]);
// 新增制盘时间变量
const dateRangeSend = ref<[DateModelType, DateModelType]>(['', '']);
const dateRangeReversal = 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 payablesList = ref([]);

const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { sys_pay_method } = toRefs<any>(proxy?.useDict('sys_pay_method'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_transfer_status, sys_common_status, bls_transit_status } = toRefs<any>(
  proxy?.useDict('bls_transfer_status', 'sys_common_status', 'bls_transit_status')
);

const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);

const data = reactive<SinglePageData<PayablesQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageCom: undefined,
    appntName: undefined,
    bankAccount: undefined,
    businessReceiptNumber: undefined,
    policyNumber: undefined,
    businessNumber: undefined,
    fromSystem: undefined,
    chargeType: undefined,
    chargeStatus: undefined,
    paymentMethod: undefined,
    params: {}
  },
  rules: {}
});

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeRece.value = ['', ''];
  dateRangeChar.value = ['', ''];
  // 重置制盘时间
  dateRangeSend.value = ['', ''];
  dateRangeReversal.value = ['', ''];
  amountEnd.value = null;
  amountBigen.value = null;
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    loading.value = true;
    if (!checkAmount()) {
      loading.value = false;
      return;
    }
    let exportParams = { ...queryParams.value };
    exportParams = proxy?.addDateRange(exportParams, dateRangeRece.value, 'Rece');
    exportParams = proxy?.addDateRange(exportParams, dateRangeChar.value, 'Char');
    exportParams = proxy?.addDateRange(exportParams, dateRangeSend.value, 'Send');
    exportParams = proxy?.addDateRange(exportParams, dateRangeReversal.value, 'Reversal');
    const res = await exportPayablesAsync(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(
            '/bls/payables/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('payables') === -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 getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeRece.value, 'Rece');
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeChar.value, 'Char');
  // 添加制盘时间到查询参数
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeSend.value, 'Send');
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeReversal.value, 'Reversal');
  if (!checkAmount()) {
    loading.value = false;
    return;
  }
  amountRange.value = [amountBigen.value, amountEnd.value];
  queryParams.value = proxy?.addDateRange(queryParams.value, amountRange.value, 'Amount');
  const res = await listPayables(queryParams.value);
  payablesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const checkAmount = () => {
  const regex = /^\d+(\.\d{1,2})?$/;
  const fields = [
    { name: 'amountBigen', value: amountBigen.value },
    { name: 'amountEnd', value: amountEnd.value }
  ];
  for (const field of fields) {
    if (field.value && !regex.test(field.value)) {
      proxy?.$modal.msgError(`${field.name} 金额只能为数字且最多2位小数`);
      return false;
    }
  }
  if (amountBigen.value && amountEnd.value && amountBigen.value > amountEnd.value) {
    proxy?.$modal.msgError('开始金额不能大于终止金额');
    return false;
  }
  return true;
};
/** 模糊查询 */
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 getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

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