<template>
  <el-dropdown trigger="click" @command="handleExport">
    <el-button type="success" icon="el-icon-download">导出</el-button>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item command="page">导出本页数据</el-dropdown-item>
        <el-dropdown-item command="all">导出全部数据</el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script>
import { dataToExcel } from "@/utils/exportExcel";

const ACT_STATE_MAP = { 0: "草稿中", 1: "进行中", 2: "被退回", 3: "被撤回", 4: "已完成", 5: "已关闭" };

export default {
  name: "OfmExportBtn",
  props: {
    getTableRef: { type: Function, required: true },
    columns: { type: Array, required: true },
    fileName: { type: String, default: "台账数据" },
  },
  methods: {
    // 将嵌套字段和特殊类型展平为简单字符串，避免 getNestedValue 对 null 嵌套对象崩溃
    flattenData(list) {
      if (!Array.isArray(list)) return [];
      return list.map(row => {
        const flat = { ...row };
        // 审批状态展平
        const actState = row.ticket_?.act_state;
        flat._act_state_text = ACT_STATE_MAP[actState] ?? "";
        flat._state_name = row.ticket_?.state_?.name ?? "";
        // 数组/JSONField 字段统一转为字符串
        for (const key of Object.keys(flat)) {
          if (Array.isArray(flat[key])) {
            flat[key] = flat[key].join("、");
          }
        }
        // 布尔值转文字
        if (row.is_lending !== undefined) flat._is_lending_text = row.is_lending ? "是" : "否";
        if (row.is_city !== undefined) flat._is_city_text = row.is_city ? "是" : "否";
        if (row.is_change !== undefined) flat._is_change_text = row.is_change ? "是" : "否";
        if (row.is_promotion !== undefined) flat._is_promotion_text = row.is_promotion ? "是" : "否";
        return flat;
      });
    },
    // 把 columns 中的嵌套/type_dict 列替换为展平后的 key
    getFlatColumns() {
      return this.columns.map(col => {
        if (col.key === "ticket_.act_state") return { ...col, key: "_act_state_text", type_dict: undefined };
        if (col.key === "is_lending") return { ...col, key: "_is_lending_text", type_dict: undefined };
        if (col.key === "is_city") return { ...col, key: "_is_city_text", type_dict: undefined };
        return col;
      });
    },
    doExport(data) {
      const flatData = this.flattenData(data);
      const flatCols = this.getFlatColumns();
      dataToExcel(flatCols, flatData, this.fileName);
    },
    handleExport(command) {
      const table = this.getTableRef();
      if (!table) return;
      if (command === "page") {
        this.doExport(table.tableData);
      } else if (command === "all") {
        const query = Object.assign({}, table.query, table.tableParams, { page: 0 });
        const loading = this.$loading({ lock: true, text: "数据导出中...", background: "rgba(0,0,0,0.1)" });
        table.apiObj.req(query).then((res) => {
          loading.close();
          this.doExport(res);
        }).catch((err) => {
          loading.close();
          console.error("导出失败", err);
          this.$message.error("导出失败");
        });
      }
    },
  },
};
</script>
