<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"
          :data-export="handleExport"
          :export-disabled="!canExport"
        >
          <template #tableHeader>
            <el-button type="primary" :icon="Download" :disabled="!canExport" @click="handleExport"> 导出 </el-button>
          </template>
          <template #lawyerName="scope">
            <div class="lawyer-info">
              <el-avatar :size="48" :src="scope.row.headImg" />
              <div class="lawyer-meta">
                <div class="lawyer-name">
                  {{ scope.row.lawyerName }}
                </div>
                <div class="lawyer-extra">执业证号：{{ scope.row.lawyerCertificateNo }}</div>
              </div>
            </div>
          </template>
          <template #operation="scope">
            <el-button type="primary" link :icon="EditPen" @click="handleDetail(scope.row)"> 查看详情 </el-button>
          </template>
        </ProTable>
      </div>
    </div>
    <DetailDialog ref="detailDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onActivated, onMounted, computed } from "vue";
import { useRoute } 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 DetailDialog from "./detailDialog.vue";
import { getLawyerList, getOverview, exportLawyerListWithName } from "@/api/modules/lawyer";
import { useUserStore } from "@/stores/modules/user";
import { Download, EditPen } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useDownload } from "@/hooks/useDownload";

const proTable = ref<ProTableInstance>();
const detailDialog = ref<any>(null);
const userStore = useUserStore();
const route = useRoute();
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 summaryData = ref({
  totalOrderCount: 0,
  totalOrderAmountYuan: 0,
  platformServiceFeeYuan: 0
});
const isAdmin = computed(() => userStore.userInfo?.name === "admin");
const routeFirmId = computed(() => (route.query.firmId as string) || "");
const fallbackFirmId = computed(() => userStore.userInfo?.roleId || "");
const currentFirmId = computed(() => {
  if (routeFirmId.value) return routeFirmId.value;
  if (isAdmin.value) return fallbackFirmId.value;
  return fallbackFirmId.value;
});

const columns = reactive<ColumnProps[]>([
  { prop: "index", label: "序号", type: "index", width: 60, align: "center" },
  { label: "律师信息", prop: "lawyerName", 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",
    width: 180,
    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;
  if (currentFirmId.value) {
    newParams.firmId = currentFirmId.value;
  }
  return newParams;
};

const fetchOverview = async (params: any) => {
  try {
    const res: any = await getOverview(params);
    const overview = res?.data;
    summaryData.value = {
      totalOrderCount: overview.totalOrderCount || 0,
      totalOrderAmountYuan: overview.totalOrderAmountYuan || 0,
      platformServiceFeeYuan: 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([getLawyerList(queryParams), fetchOverview(queryParams)]);
  return listRes;
};
const dataCallback = (data: any) => {
  return {
    list: data.records,
    total: data.total
  };
};

const filters = reactive({
  lawyerName: "",
  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.lawyerName) proTable.value.searchParam.lawyerName = filters.lawyerName;
  else delete proTable.value.searchParam.lawyerName;

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

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

const handleDetail = (row: any) => {
  detailDialog.value?.open(row.lawyerId);
};

const handleExport = async () => {
  if (!currentFirmId.value) {
    ElMessage.warning("缺少律所信息，无法导出");
    return;
  }
  if (!canExport.value) {
    ElMessage.warning("暂无可导出的数据");
    return;
  }
  const params: any = { ...(proTable.value?.searchParam || {}), firmId: currentFirmId.value };
  params.page = 1;
  params.size = 10;
  await useDownload(exportLawyerListWithName, "对账数据", 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;
}
.page-heading {
  font-size: 16px;
  font-weight: 600;
  color: #1c2130;
}
.page-heading .heading-label {
  margin-right: 6px;
  font-weight: normal;
  color: #7a7f87;
}
.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;
}
.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>
