<template>
  <div>
    <el-drawer title="详情" :visible.sync="visible" size="70%" @close='closeD'>
      <div class="box">
        <!-- 顶部信息展示区域 -->
        <div class="info-header">
          <div class="info-item">
            <span class="label">工厂：</span>
            <span class="value">{{ factoryName }}</span>
          </div>
          <div class="info-item">
            <span class="label">产线：</span>
            <span class="value">{{ lineName }}</span>
          </div>
          <div class="info-item">
            <span class="label">时间范围：</span>
            <span class="value">{{ timeRange }}</span>
          </div>
          <div class="info-item">
            <el-button type="primary" @click="handleExport">导出</el-button>
          </div>
        </div>

        <!-- 表格 -->
        <base-table :page="queryParams.pageNo" :limit="queryParams.pageSize" :table-props="tableProps"
          :table-data="tableData" :span-method="spanMethod" :max-height="tableH">
        </base-table>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import moment from 'moment';
import * as XLSX from 'xlsx';
import { getDefectSummaryDet } from '@/api/monitoring/defectSummary';
// import { publicFormatter } from '@/utils/dict'

const tableProps = [
  { prop: 'defectLevel', label: '缺陷等级' },
  { prop: 'defectName', label: '缺陷类型' },
  { prop: 'defectNum', label: '玻璃数量' }
]

export default {
  name: 'EnergyStatisticsDet',
  props: {},
  data() {
    return {
      visible: false,
      tableProps,
      tableData: [],
      tableBtn: [],
      tableH: this.tableHeight(115),
      total: 0,
      queryParams: { pageNo: 1, pageSize: 30 },
      factoryName: '',
      lineName: '',
      timeRange: '',
      name: '',
      energyType: '',
      energyTypeId: '',
      addOrEditTitle: "",
      centervisible: false,
      collectionList: [
        { value: 0, label: '否' },
        { value: 1, label: '是' }
      ],
      showBtn: true,
      selectedList: []
    }
  },
  created() {
    window.addEventListener('resize', () => {
      this.tableH = this.tableHeight(115)
    })
  },
  methods: {
    spanMethod({ row, column, rowIndex, columnIndex }) {
      const fields = ['defectLevel']
      const cellValue = row[column.property]
      if (cellValue && fields.includes(column.property)) {
        const prevRow = this.tableData[rowIndex - 1]
        let nextRow = this.tableData[rowIndex + 1]
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 }
        } else {
          let countRowspan = 1
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = this.tableData[++countRowspan + rowIndex]
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 }
          }
        }
      }
    },

    init(data) {
      this.visible = true;
      this.factoryName = data.factoryName || '';
      this.lineName = data.lineName || '';

      if (data.startTime && data.endTime) {
        const start = moment(data.startTime).format('yyyy-MM-DD HH:mm:ss');
        const end = moment(data.endTime).format('yyyy-MM-DD HH:mm:ss');
        this.timeRange = `${start} - ${end}`;
      } else {
        this.timeRange = '';
      }

      this.queryParams.factoryId = data.factoryId;
      this.queryParams.lineId = data.lineId;
      this.queryParams.startTime = data.startTime;
      this.queryParams.endTime = data.endTime;

      this.getList();
    },

    getList() {
      getDefectSummaryDet({ ...this.queryParams }).then((res) => {
        this.tableData = res.data || [];
      })
    },

    closeD() {
      this.$emit('closeDrawer');
    },

    closeDet() {
      this.getList();
    },

    // --- 重写的导出方法 ---
    // --- 修改后的导出方法 ---
    handleExport() {
      console.log("开始执行导出...");
      this.$modal.confirm('确定要导出表格数据吗？').then(() => {
        console.log("用户确认导出");

        // 1. 准备数据
        console.log("tableProps:", this.tableProps);
        console.log("tableData:", this.tableData);

        // 1.1 准备表头 (新增了 '工厂', '产线', '时间范围')
        const headers = ['工厂', '产线', '时间范围', ...this.tableProps.map(prop => prop.label)];
        console.log("生成的表头:", headers);

        // 1.2 准备表格数据
        const exportData = [];
        this.tableData.forEach((row) => {
          const newRow = [];
          // 先添加顶部信息列
          newRow.push(this.factoryName);
          newRow.push(this.lineName);
          newRow.push(this.timeRange);

          // 再添加表格数据列
          this.tableProps.forEach((prop) => {
            // 直接填入所有数据，不再对 defectLevel 进行合并判断
            newRow.push(row[prop.prop] !== undefined ? row[prop.prop] : '');
          });
          exportData.push(newRow);
        });
        console.log("处理后的数据:", exportData);

        // 2. 创建工作簿和工作表
        try {
          const worksheet = XLSX.utils.aoa_to_sheet([headers, ...exportData]);
          console.log("工作表创建成功");
          const workbook = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(workbook, worksheet, '缺陷详情数据');
          console.log("工作簿创建成功");

          // 3. 触发下载
          const fileName = `${this.factoryName}-${this.lineName}-缺陷汇总详情-${moment().format('YYYYMMDDHHmmss')}.xlsx`;
          console.log("准备下载文件:", fileName);
          XLSX.writeFile(workbook, fileName);
          console.log("下载触发成功");
        } catch (error) {
          console.error("生成Excel文件时出错:", error);
          this.$modal.msgError('导出失败，生成文件时出错！');
        }

      }).catch((error) => {
        console.log("用户取消导出或发生错误:", error);
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.box {
  padding: 0 32px;
}

.info-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 16px;

  .info-item {
    display: flex;
    align-items: center;
    margin-right: 32px;
    font-size: 16px;
    margin-bottom: 8px;

    .label {
      color: #606266;
      margin-right: 8px;
      font-weight: 500;
    }

    .value {
      color: #303133;
    }
  }
}
</style>
