<template>
  <el-dialog
    :title="title"
    append-to-body
    :modelValue="openShow"
    width="70%"
    @close="closeDialog()"
  >
    <avue-form
      :option="excelOption"
      v-model="excelForm"
      :upload-after="uploadAfter"
      :upload-before="uploadBefore"
    >
      <template #readExcel>
        <el-button type="primary" @click="readExcel" v-if="!isDetail">
          读取文件<i class="el-icon-download el-icon--right"></i>
        </el-button>
      </template>
    </avue-form>
    <el-table v-show="isRead && !isDetail" :data="tableData">
      <el-table-column type="index" width="50" label="序号" />
      <el-table-column
        v-for="item in tableColumn"
        :key="item.prop"
        :label="item.label"
        :prop="item.prop"
        align="center"
      />
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import {
  readExcelBsEfficiencyTask,
  reportBsEfficiencyTask,
  subReportBsEfficiencyTask,
} from '@/api/performanceManagement/dataReporting';
export default {
  props: {
    title: {
      type: String,
      default: '',
    },
    showReport: {
      type: Boolean,
      default: false,
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
    row: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      openShow: false,
      excelForm: {
        excelFile: [],
      },
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '填报文件',
            prop: 'excelFile',
            type: 'upload',
            span: 12,
            limit: 1,
            fileSize: 50000,
            propsHttp: {
              res: 'data',
              attachId: 'attachId', // 关键：指定附件ID字段
            },
            accept: '.xls,.xlsx',
            tip: '请上传 .xls,.xlsx 标准格式文件，文件最大5M',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传文件',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '',
            prop: 'readExcel',
            formslot: true,
            span: 12,
          },
        ],
      },
      tableData: [],
      isRead: false,
      tableColumn: [
        { label: '员工工号', prop: 'cardNo' },
        { label: '姓名', prop: 'name' },
      ],
      attachId: null,
      formData: null,
    };
  },
  created() {
    this.openShow = this.showReport;
  },
  methods: {
    closeDialog(val) {
      this.openShow = false;
      // 清空数据
      this.excelForm = { excelFile: [] };
      this.attachId = null;
      this.tableData = [];
      this.isRead = false;
      this.$emit('closeDialog', val);
    },
    // 上传前（不用改，保留）
    uploadBefore(file, done, loading, column) {
      this.formData = file;
      done(); // 必须执行，允许上传
    },
    // 上传后（修复版）
    uploadAfter(file, done, loading, column) {
      console.log('上传成功返回:', file);
      // 正确获取 attachId
      this.attachId = file.attachId || file.data?.attachId;
      done();
    },
    // 读取Excel（关键修复）
    readExcel() {
      if (!this.attachId) {
        this.$message.warning('请先上传文件');
        return;
      }
      readExcelBsEfficiencyTask({ file: this.formData })
        .then(res => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.tableData || [];
            this.tableColumn = res.data.data.tableColumn || [];
            this.isRead = true;
            this.$message.success('文件读取成功');
          } else {
            this.$message.error('文件读取失败');
          }
        })
        .catch(() => {
          this.$message.error('文件读取接口异常');
        });
    },
    // 提交表单
    submitForm() {
      if (!this.attachId) {
        this.$message.error('请先上传文件');
        return;
      }
      let params = {};
      if (!this.isDetail) {
        params = {
          id: this.row.id,
          attachId: this.attachId,
          table: {
            tableData: this.tableData,
            tableColumn: this.tableColumn,
          },
        };
        reportBsEfficiencyTask(params).then(res => {
          if (res.data.code === 200) {
            this.$message.success('提交成功');
            this.closeDialog(true);
          } else {
            this.$message.error('提交失败');
          }
        });
      } else {
        params = {
          id: this.row.id,
          attachId: this.attachId,
        };
        subReportBsEfficiencyTask(params).then(res => {
          if (res.data.code === 200) {
            this.$message.success('提交成功');
            this.closeDialog(true);
          } else {
            this.$message.error('提交失败');
          }
        });
      }
    },
  },
};
</script>