<template>
  <div class="app-container">
    <el-card shadow="never" style="margin-bottom: 12px">
      <el-form :inline="true" :model="queryForm" size="small" label-width="90px">
        <el-form-item label="报表ID">
          <el-input :value="currentReportId" disabled style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询报表</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never">
      <div slot="header" class="flex-header">
        <div>
          <el-button type="success" size="mini" icon="el-icon-setting" @click="openPrintSettingPage">打印设置</el-button>
        </div>
        <span>报表结果（{{ runtimeInfo.dataSourceMode || "-" }} / {{ runtimeInfo.total || 0 }} 行）</span>
      </div>

      <el-table v-loading="loading" :data="rows" border stripe>
        <el-table-column
          v-for="field in allFields"
          :key="field"
          :label="field"
          :prop="field"
          min-width="140"
          show-overflow-tooltip
        />
      </el-table>
      <pagination
        v-show="runtimeInfo.total > 0"
        :total="runtimeInfo.total"
        :page.sync="queryForm.pageNum"
        :limit.sync="queryForm.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
  </div>
</template>

<script>
import { queryReportRuntime } from "@/api/erp/runtime";

export default {
  name: "ErpUserReportPage",
  data() {
    return {
      loading: false,
      queryForm: {
        pageNum: 1,
        pageSize: 20
      },
      queryContext: {
        filters: [],
        sorts: []
      },
      currentReportId: "",
      runtimeInfo: {
        dataSourceMode: "",
        total: 0
      },
      rows: [],
      allFields: []
    };
  },
  created() {
    this.syncReportIdFromRoute();
    if (this.currentReportId) {
      this.handleQuery();
    }
  },
  watch: {
    $route() {
      this.syncReportIdFromRoute();
      this.resetQuery();
    }
  },
  methods: {
    syncReportIdFromRoute() {
      const idFromQuery = this.$route.query.reportId;
      const idFromCompat = this.$route.query.reportI;
      const idFromParams = this.$route.params.reportId;
      this.currentReportId = String(idFromQuery || idFromCompat || idFromParams || "").trim();
    },
    resetQueryResultOnly() {
      this.runtimeInfo = { dataSourceMode: "", total: 0 };
      this.rows = [];
      this.allFields = [];
    },
    buildRuntimeQueryPayload(override = {}) {
      return {
        pageNum: override.pageNum || this.queryForm.pageNum,
        pageSize: override.pageSize || this.queryForm.pageSize,
        filters: Array.isArray(override.filters) ? override.filters : this.queryContext.filters || [],
        sorts: Array.isArray(override.sorts) ? override.sorts : this.queryContext.sorts || []
      };
    },
    handleQuery() {
      const reportId = this.currentReportId;
      if (!reportId) {
        this.$modal.msgWarning("当前菜单未绑定报表ID，请联系管理员检查菜单配置");
        return;
      }
      this.loading = true;
      queryReportRuntime(reportId, this.buildRuntimeQueryPayload())
        .then((res) => {
          const data = res.data || {};
          this.runtimeInfo = {
            dataSourceMode: data.dataSourceMode || "",
            total: data.total || 0
          };
          this.rows = data.rows || [];
          const firstRow = this.rows[0] || {};
          this.allFields = Object.keys(firstRow);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    resetQuery() {
      this.queryForm = {
        pageNum: 1,
        pageSize: 20
      };
      this.resetQueryResultOnly();
      if (this.currentReportId) {
        this.handleQuery();
      }
    },
    handleSearch() {
      this.queryForm.pageNum = 1;
      this.handleQuery();
    },
    openPrintSettingPage() {
      if (!this.currentReportId) {
        this.$modal.msgWarning("当前菜单未绑定报表ID，请联系管理员检查菜单配置");
        return;
      }
      this.$router.push({
        path: "/erp/report/print",
        query: {
          reportId: this.currentReportId,
          pageNum: this.queryForm.pageNum,
          pageSize: this.queryForm.pageSize
        }
      });
    }
  }
};
</script>

<style scoped>
.flex-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
