<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="对账日期">
                <el-date-picker
                  v-model="dateRange"
                  end-placeholder="结束日期"
                  range-separator="-"
                  start-placeholder="开始日期"
                  type="daterange"
                  value-format="YYYY-MM-DD"
                />
              </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>


      <div class="mb-8">
        <h3 class="text-lg font-bold mb-4">资金系统</h3>
        <el-table v-loading="fundLoading" :data="fundList" height="300" @row-dblclick="handleRowDblClick">
          <el-table-column align="center" label="批次号" prop="transSeq" width="200" />
          <el-table-column align="center" label="对账时间" prop="transDate" width="200">
            <template #default="{ row }">
              {{ parseTime(row.transDate) }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="总笔数" prop="totalCount" width="200" />
          <el-table-column align="center" label="总金额" prop="totalAmount" width="200">
            <template #default="{ row }">
              {{ row.totalAmount}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="对账类型" prop="fundType" width="200" />
          <el-table-column align="center" label="状态" prop="checkStatus" width="200">
            <template #default="{ row }">
              <el-tag
                :type="getResultTagType(row.status)"
                :class="getResultTagClass(row.status)">
                {{ getResultText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="350" fixed="right">
            <template #default="{ row }">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                  v-hasPermi="['bls:reconciliation:query']"
                  link
                  type="primary"
                  icon="View"
                  @click="handleViewDetail(row)"
                >查看</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="fundTotal > 0"
          v-model:limit="fundQueryParams.pageSize"
          v-model:page="fundQueryParams.pageNum"
          :total="fundTotal"
          @pagination="handleFundPagination"
        />
      </div>
      <div>
        <h3 class="text-lg font-bold mb-4">其他系统</h3>
        <el-table v-loading="checkLoading" :data="checkList" height="300">
          <el-table-column align="center" label="批次号" prop="reqSeqId" width="200" />
          <el-table-column align="center" label="对账时间" prop="transDate" width="200">
            <template #default="{ row }">
              {{ row.transDate ? parseTime(row.transDate) : 'N/A' }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="收付标记" prop="transCode" width="100" />
          <el-table-column align="center" label="来源系统" prop="fromSystem" width="100" />
          <el-table-column align="center" label="交易流水" prop="rdSeq" width="200" />
          <el-table-column align="center" label="外部系统对账结果" prop="accountResult" width="200" />
          <el-table-column align="center" label="对账结果" prop="checkAccountResult" width="200">
            <template #default="{ row }">
              <el-tag
                :type="getResultTagType(row.checkAccountResult)"
                :class="getResultTagClass(row.checkAccountResult)">
                {{ getResultText(row.checkAccountResult) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" label="失败原因" prop="checkAccountReason" />

        </el-table>
        <pagination
          v-show="checkTotal > 0"
          v-model:limit="checkQueryParams.pageSize"
          v-model:page="checkQueryParams.pageNum"
          :total="checkTotal"
          @pagination="handleCheckPagination"
        />
      </div>
    </el-card>
    <el-dialog
      v-model="detailDialogVisible"
      :title="detailDialogTitle"
      width="80%"
      append-to-body
    >
      <el-table v-loading="detailLoading" :data="detailList" height="500">
        <el-table-column align="center" label="收付标记" prop="transDode" width="120" />
        <el-table-column align="center" label="资金流水号" prop="fundRdSeq" width="200" />
        <el-table-column align="center" label="业务流水号" prop="busTransSeq" width="180" />
        <el-table-column align="center" label="业务交易子流水号" prop="rdSeq" width="180" />
        <el-table-column align="center" label="对账时间" prop="payMadeDate" width="200">
          <template #default="{ row }">
            {{ row.payMadeDate ? parseTime(row.payMadeDate) : 'N/A' }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="收付机构"
          prop="corpEntity"
          width="100"
          :formatter="(row) => formatDictLabel(sys_managecom, row.corpEntity)"
        />
        <el-table-column align="center" label="收付账户" prop="corpAct" width="180" />
        <el-table-column align="center" label="金额" prop="amount" width="100">
          <template #default="{ row }">
            {{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="客户账号" prop="oppAct" width="100" />
        <el-table-column align="center" label="客户户名" prop="oppActName" width="100" />
        <el-table-column align="center" label="币别" prop="currency" width="80" />
        <el-table-column align="center" label="状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getResultTagType(row.status)"
              :class="getResultTagClass(row.status)">
              {{ getResultText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { queryFund, queryCheck,queryFundInfo } from '@/api/bls/reconciliation';
import { parseTime } from '@/utils/ruoyi';
import { computed } from 'vue';

const manageComMap = computed(() => {
  const map: Record<string, string> = {};
  (sys_managecom.value || []).forEach(item => {
    map[item.value] = item.label; // { "1001": "总公司", "1002": "分公司" }
  });
  return map;
});

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

// 详情弹窗相关状态
const detailDialogVisible = ref(false); // 控制弹窗显示
const detailDialogTitle = ref('资金对账明细'); // 弹窗标题
const detailLoading = ref(false); // 明细加载状态
const detailList = ref([]); // 明细数据
const currentTransSeq = ref(''); // 当前选中的批次号

const fundLoading = ref(true);
const checkLoading = ref(true);
const showSearch = ref(true);
const fundTotal = ref(0);
const checkTotal = ref(0);
const fundList = ref([]);
const checkList = ref([]);
const dateRange = ref<[string, string]>(['', '']);


const formatDictLabel = (dictRef, value) => {
  if (!value) return '—';
  const dictItems = dictRef?.value ?? [];
  const dictItem = dictItems.find((item) => item.value === value);
  return dictItem?.label ?? value;
};
const fundQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  transSeq: undefined,
  params: {}
});
const checkQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  reqSeqId: undefined,
  params: {}
});
const queryParams = reactive({
  transSeq: undefined
});
/** 获取对账结果列表 */
const getList = async () => {
  fundLoading.value = true;
  checkLoading.value = true;
  try {
    // 处理日期范围参数
    const dateParams = {};
    if (dateRange.value?.length === 2) {
      dateParams.beginTime = dateRange.value[0];
      dateParams.endTime = dateRange.value[1];
    }
    // 修改10：同时调用两个接口
    const [fundRes, checkRes] = await Promise.all([
      queryFund({
        ...fundQueryParams,
        transSeq: queryParams.transSeq,
        params: { ...dateParams }
      }),
      queryCheck({
        ...checkQueryParams,
        reqSeqId: queryParams.transSeq,
        params: { ...dateParams }
      })
    ]);
    fundList.value = fundRes.rows;
    fundTotal.value = fundRes.total;
    checkList.value = checkRes.rows;
    checkTotal.value = checkRes.total;
  } finally {
    fundLoading.value = false;
    checkLoading.value = false;
  }
};
const handleRowDblClick = (row: any) => {
  handleViewDetail(row);
};
const handleFundPagination = (pagination: any) => {
  fundQueryParams.pageNum = pagination.page;
  fundQueryParams.pageSize = pagination.limit;
  getList();
};

const handleCheckPagination = (pagination: any) => {
  checkQueryParams.pageNum = pagination.page;
  checkQueryParams.pageSize = pagination.limit;
  getList();
};
const handleViewDetail = async (row: any) => {
  try {
    detailLoading.value = true;
    currentTransSeq.value = row.transSeq;
    detailDialogTitle.value = `资金对账明细 - ${row.transSeq}`;

    const res = await queryFundInfo({ transSeq: row.transSeq });
    //  console.log("接口响应数据:", res);


    if (res.code === 200) {
      detailList.value = res.data || [];
    } else {
      detailList.value = [];
      proxy?.$modal.msgError(res.msg || '获取明细失败');
    }

    detailDialogVisible.value = true;
  } catch (error) {
    proxy?.$modal.msgError('获取详情失败: ' + error.message);
  } finally {
    detailLoading.value = false;
  }
};

/** 搜索与重置 */
const handleQuery = () => {
  fundQueryParams.pageNum = 1;
  checkQueryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.transSeq = undefined;
  proxy?.resetForm('queryFormRef');
  handleQuery();
};

onMounted(() => {
  getList();
});
// 获取标签类型（颜色）
const getResultTagType = (result) => {
  if (result === 'Y') return 'success';
  if (result === 'N') return 'danger';
  return 'warning'; // 未知状态用黄色警告
};

// 获取显示文本
const getResultText = (result) => {
  if (result === 'Y') return '成功';
  if (result === 'N') return '失败';
  return result;
};

// 可选：添加自定义样式类
const getResultTagClass = (result) => {
  return result === 'N' ? 'custom-danger-style' : '';
};

</script>
<style scoped>
.custom-danger-style {
  font-weight: bold;
  transform: scale(1.05);
}
</style>
