<template>
  <div class="reconciliation-page">
    <div class="layout-wrapper">
      <div class="content-panel">
        <div class="summary-wrapper">
          <div v-for="item in summaryCards" :key="item.label" class="summary-card">
            <div class="summary-label">
              {{ item.label }}
            </div>
            <div class="summary-value">
              {{ item.value }}
            </div>
          </div>
        </div>
        <ProTable
          ref="proTable"
          :columns="columns"
          :request-api="getTableList"
          :data-callback="dataCallback"
          :request-auto="false"
        >
          <template #tableHeader>
            <el-button type="primary" :icon="Download" :disabled="!canExport" @click="handleExport"> 导出 </el-button>
            <el-button type="primary" :icon="Download" :disabled="!canExport" @click="handleExportAll"> 全部导出 </el-button>
          </template>
          <template #operation="scope">
            <el-button type="primary" link :icon="EditPen" @click="handleDetail(scope.row)"> 查看详情 </el-button>
          </template>
        </ProTable>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onActivated, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import type { Course } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import type { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getAllLawFirmList, getOverview, exportAllLawFirmList } from "@/api/modules/lawyer";
import { useDownload } from "@/hooks/useDownload";
import { useUserStore } from "@/stores/modules/user";
import { Download, EditPen } from "@element-plus/icons-vue";

const proTable = ref<ProTableInstance>();
const router = useRouter();

const summaryData = ref({
  totalOrderCount: 0,
  totalOrderAmountYuan: 0,
  platformServiceFeeYuan: 0
});
const canExport = computed(() => {
  const table = proTable.value;
  if (!table) return false;
  const data = table.tableData as any;
  if (Array.isArray(data)) return data.length > 0;
  if (data && typeof data === "object" && Array.isArray((data as any).list)) return (data as any).list.length > 0;
  return false;
});

const columns = reactive<ColumnProps[]>([
  { prop: "index", label: "序号", type: "index", width: 60, align: "center" },
  { label: "律所名称", prop: "firmName", minWidth: 280, search: { el: "input", props: { placeholder: "请输入律所名称" } } },
  { label: "订单数量(元)", prop: "totalOrderCount", width: 260, align: "center" },
  { label: "订单金额(元)", prop: "totalOrderAmountYuan", width: 260, align: "center" },
  {
    label: "平台信息服务费",
    prop: "platformServiceFeeYuan",
    width: 260,
    align: "center",
    render: scope => scope.row.platformServiceFeeYuan * 100 + "%"
  },
  {
    label: "订单日期",
    prop: "orderTime",
    isShow: false,
    search: {
      el: "date-picker",
      props: {
        type: "monthrange",
        valueFormat: "YYYY-MM",
        format: "YYYY-MM",
        startPlaceholder: "开始月份",
        endPlaceholder: "结束月份",
        rangeSeparator: "至",
        unlinkPanels: true
      }
    }
  },
  { label: "操作", prop: "operation", width: 260, align: "center", fixed: "right" }
]);
const buildQueryParams = (params: any) => {
  const tempParams = { ...params };
  delete tempParams.time;
  const newParams = {
    ...tempParams,
    pageNum: tempParams.pageNum,
    pageSize: tempParams.pageSize
  };
  if (params.orderTime) {
    newParams.startTime = params.orderTime[0] + "-00";
    newParams.endTime = params.orderTime[1] + "-31";
  }
  delete newParams.orderTime;
  return newParams;
};

const fetchOverview = async (params: any) => {
  try {
    const res: any = await getOverview(params);
    const overview = res?.data;
    summaryData.value = {
      totalOrderCount: Number(overview.totalOrderCount) || 0,
      totalOrderAmountYuan: Number(overview.totalOrderAmountYuan) || 0,
      platformServiceFeeYuan: Number(overview.platformServiceFeeYuan) || 0
    };
  } catch (error) {
    summaryData.value = {
      totalOrderCount: 0,
      totalOrderAmountYuan: 0,
      platformServiceFeeYuan: 0
    };
    console.error("获取对账概览失败", error);
  }
};

const getTableList = async (params: any) => {
  const queryParams = buildQueryParams(params);
  const [listRes] = await Promise.all([getAllLawFirmList(queryParams), fetchOverview(queryParams)]);
  return listRes;
};
const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

// 处理推广板块字符串
const filters = reactive({
  firmName: "",
  dateRange: [] as string[]
});

const summaryCards = computed(() => [
  { label: "总订单数量", value: summaryData.value.totalOrderCount },
  { label: "总订单金额", value: formatCurrency(summaryData.value.totalOrderAmountYuan) },
  { label: "平台信息服务费", value: formatCurrency(summaryData.value.platformServiceFeeYuan) }
]);

const refreshTable = () => {
  proTable.value?.getTableList();
};

const handleSearch = () => {
  if (!proTable.value) return;
  if (filters.firmName) proTable.value.searchParam.firmName = filters.firmName;
  else delete proTable.value.searchParam.firmName;

  if (filters.dateRange?.length === 2) {
    proTable.value.searchParam.time = filters.dateRange;
  } else {
    delete proTable.value.searchParam.time;
  }
  proTable.value.search();
};

const handleReset = () => {
  filters.firmName = "";
  filters.dateRange = [];
  handleSearch();
};

const formatCurrency = (val?: number | string) => {
  return `¥${val || 0}`;
};

const handleDetail = (row: any) => {
  if (!row?.firmId) return;
  router.push({
    path: "/lawyerManagement/reconciliation/lawyerDetail",
    query: {
      firmId: row.firmId,
      firmName: row.firmName
    }
  });
};

const buildExportParams = (override: Record<string, any> = {}) => {
  const table = proTable.value;
  const searchParam = table?.searchParam ? { ...table.searchParam } : {};
  const pageable = table?.pageable
    ? { pageNum: table.pageable.pageNum, pageSize: table.pageable.pageSize }
    : { pageNum: 1, pageSize: 10 };
  const baseParams = {
    ...searchParam,
    pageNum: pageable.pageNum,
    pageSize: pageable.pageSize,
    ...override
  };
  return buildQueryParams(baseParams);
};

const handleExport = async () => {
  if (!canExport.value) return;
  const params = buildExportParams();
  await useDownload(exportAllLawFirmList, "对账数据", params);
};

const handleExportAll = async () => {
  if (!canExport.value) return;
  const params = buildExportParams({ pageNum: 1, pageSize: 999 });
  await useDownload(exportAllLawFirmList, "对账数据-全部", params);
};

onMounted(() => {
  refreshTable();
});

onActivated(() => {
  refreshTable();
});
</script>

<style scoped lang="scss">
.reconciliation-page {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: calc(100vh - 150px);
  padding: 16px;
}
.layout-wrapper {
  display: flex;
  flex: 1;
  gap: 16px;
  align-items: stretch;
  height: 100%;
  min-height: 0;
}
.content-panel {
  display: flex;
  flex: 1;
  flex-direction: column;
  gap: 16px;
  min-height: 0;
}
.summary-wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}
.summary-card {
  padding: 16px;
  background: #ffffff;
  border: 1px solid #e2e6ef;
  border-radius: 12px;
}
.summary-label {
  margin-bottom: 4px;
  color: #7a7f87;
}
.summary-value {
  font-size: 24px;
  font-weight: 600;
  color: #1f2532;
}
.filter-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.filter-left {
  display: flex;
  flex-direction: column;
}
.filter-title {
  font-size: 20px;
  font-weight: 600;
  color: #16192c;
}
.filter-desc {
  font-size: 13px;
  color: #8c8f9c;
}
.filter-right {
  display: flex;
  gap: 12px;
}
:deep(.el-table) {
  border: 1px solid #e6e9ef;
  border-top: none;
  border-radius: 0 0 12px 12px;
}
.lawyer-info {
  display: flex;
  gap: 12px;
  align-items: center;
}
.lawyer-meta {
  display: flex;
  flex-direction: column;
  font-size: 13px;
  color: #7e7f8c;
}
.lawyer-name {
  font-size: 15px;
  font-weight: 600;
  color: #1c2130;
}
.lawyer-extra {
  font-size: 12px;
  color: #a5a7b3;
}
</style>
