<template>
  <div class="app-container" v-loading="loading">
    <el-row>
      <el-form label-width="80px" inline>
        <!-- 根据 reportType 显示不同的日期选择器 -->
        <template v-if="['out', 'loss'].includes(reportType)">
          <el-form-item label="时间范围" prop="timeRange">
            <time-range-picker v-model="queryParams" start-key="startTime" end-key="endTime"
              :default-start-time="defaultStartTime" :default-end-time="defaultEndTime" @quick-select="handleQuery" />
          </el-form-item>
        </template>
        <el-form-item v-else-if="reportType === 'day'" label="日期" prop="date">
          <el-date-picker style="width: 200px;" v-model="dayDate" type="date" value-format="yyyy-MM-dd"
            placeholder="选择日期" @change="handleDateChange"></el-date-picker>
        </el-form-item>
        <el-form-item v-else-if="reportType === 'month'" label="日期" prop="date">
          <el-date-picker style="width: 200px;" v-model="monthDate" type="month" value-format="yyyy-MM"
            placeholder="选择月份" @change="handleDateChange"></el-date-picker>
        </el-form-item>
        <el-form-item v-else-if="reportType === 'year'" label="日期" prop="date">
          <el-date-picker style="width: 200px;" v-model="yearDate" type="year" value-format="yyyy" placeholder="选择年份"
            @change="handleDateChange"></el-date-picker>
        </el-form-item>
        <template v-else-if="reportType === 'team'">
          <el-form-item label="开始日期">
            <el-date-picker style="width: 200px;" v-model="queryParams.byCreateTimeStart" type="date"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束日期">
            <el-date-picker style="width: 200px;" v-model="queryParams.byCreateTimeEnd" type="date"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="班组">
            <el-select v-model="queryParams.team" placeholder="请选择班组" style="width: 200px;">
              <el-option label="甲" value="甲" />
              <el-option label="乙" value="乙" />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker style="width: 200px;" v-model="queryParams.startTime" type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择开始日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker style="width: 200px;" v-model="queryParams.endTime" type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择结束日期"></el-date-picker>
          </el-form-item>
        </template>
        <el-form-item label="入场钢卷号" prop="enterCoilNo">
          <el-input style="width: 200px; display: inline-block;" v-model="queryParams.enterCoilNo"
            placeholder="请输入入场钢卷号" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="当前钢卷号" prop="currentCoilNo">
          <el-input style="width: 200px;" v-model="queryParams.currentCoilNo" placeholder="请输入当前钢卷号" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="产品名称" prop="itemName">
          <el-input style="width: 200px;" v-model="queryParams.itemName" placeholder="请输入产品名称" clearable
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="规格" prop="itemSpecification">
          <memo-input style="width: 200px;" v-model="queryParams.itemSpecification" storageKey="coilSpec"
            placeholder="请选择规格" clearable @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="材质" prop="itemMaterial">
          <dict-select style="width: 200px;" v-model="queryParams.itemMaterial" dict-type="coil_material"
            placeholder="请选择材质" clearable @keyup.enter.native="handleQuery" multiple />
        </el-form-item>
        <el-form-item label="厂家" prop="itemManufacturer">
          <dict-select style="width: 200px;" v-model="queryParams.itemManufacturer" dict-type="coil_manufacturer"
            placeholder="请选择厂家" clearable @keyup.enter.native="handleQuery" multiple />
        </el-form-item>
        <el-form-item label="品质" prop="qualityStatusCsv">
          <muti-select v-model="queryParams.qualityStatusCsv" :options="dict.type.coil_quality_status"
            placeholder="请选择品质" clearable />
        </el-form-item>
        <!-- <el-form-item v-if="['team', 'day', 'month', 'year', 'all'].includes(reportType)" label="逻辑库位"
          prop="warehouseIds">
          <el-select v-model="warehouseIds" collapse-tags multiple placeholder="请选择逻辑库位" style="width: 200px;">
            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="逻辑库位" prop="warehouseId">
          <warehouse-select v-model="queryParams.warehouseId" placeholder="请选择仓库/库区/库位"
            style="width: 100%; display: inline-block; width: 200px;" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button v-if="['out', 'team', 'day', 'month', 'year', 'all'].includes(reportType)" type="primary"
            @click="exportData">导出产出钢卷</el-button>
          <el-button v-if="['loss', 'team', 'day', 'month', 'year', 'all'].includes(reportType)" type="primary"
            @click="exportLossData">导出消耗钢卷</el-button>
          <el-button type="primary" @click="settingVisible = true">列设置</el-button>
          <el-button v-if="['out', 'team', 'day', 'month', 'year', 'all'].includes(reportType)" type="primary"
            @click="saveOutputReport">保存产出报表</el-button>
          <el-button v-if="['loss', 'team', 'day', 'month', 'year', 'all'].includes(reportType)" type="primary"
            @click="saveLossReport">保存消耗报表</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <!-- out 类型的统计信息 -->
    <el-descriptions v-if="reportType === 'out'" title="统计信息" :column="3" border>
      <el-descriptions-item label="总钢卷数量">{{ outSummary.totalCount }}</el-descriptions-item>
      <el-descriptions-item label="总重">{{ outSummary.totalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="均重">{{ outSummary.avgWeight }}t</el-descriptions-item>
    </el-descriptions>

    <!-- loss 类型的统计信息 -->
    <el-descriptions v-else-if="reportType === 'loss'" title="统计信息" :column="3" border>
      <el-descriptions-item label="总钢卷数量">{{ lossSummary.totalCount }}</el-descriptions-item>
      <el-descriptions-item label="总重">{{ lossSummary.totalWeight }}t</el-descriptions-item>
      <el-descriptions-item label="均重">{{ lossSummary.avgWeight }}t</el-descriptions-item>
    </el-descriptions>

    <!-- team, day, month, year, all 类型的统计信息 -->
    <template v-else>
      <el-descriptions title="统计信息" :column="3" border>
        <el-descriptions-item label="产出数量">{{ summary.outCount }}</el-descriptions-item>
        <el-descriptions-item label="产出总重">{{ summary.outTotalWeight }}t</el-descriptions-item>
        <el-descriptions-item label="产出均重">{{ summary.outAvgWeight }}t</el-descriptions-item>

        <el-descriptions-item label="消耗数量">{{ summary.lossCount }}</el-descriptions-item>
        <el-descriptions-item label="消耗总重">{{ summary.lossTotalWeight }}t</el-descriptions-item>
        <el-descriptions-item label="消耗均重">{{ summary.lossAvgWeight }}t</el-descriptions-item>

        <el-descriptions-item label="数量差值">{{ summary.countDiff }}</el-descriptions-item>
        <el-descriptions-item label="总重差值">{{ summary.weightDiff }}</el-descriptions-item>
        <el-descriptions-item label="均重差值">{{ summary.avgWeightDiff }}t</el-descriptions-item>

        <!-- 成品率 -->
        <el-descriptions-item label="成品率">{{ summary.passRate }}</el-descriptions-item>
        <el-descriptions-item label="损耗率">{{ summary.lossRate }}</el-descriptions-item>
        <!-- 异常率 -->
        <el-descriptions-item label="异常率">{{ summary.abRate }}</el-descriptions-item>
        <!-- 正品率 -->
        <el-descriptions-item label="正品率">{{ summary.passRate2 }}</el-descriptions-item>
      </el-descriptions>

      <!-- 已处理M统计信息 -->
      <el-descriptions title="已处理M统计信息" :column="3" border>
        <el-descriptions-item label="产出数量">{{ mSummary.outCount }}</el-descriptions-item>
        <el-descriptions-item label="产出总重">{{ mSummary.outTotalWeight }}t</el-descriptions-item>
        <el-descriptions-item label="产出均重">{{ mSummary.outAvgWeight }}t</el-descriptions-item>

        <el-descriptions-item label="消耗数量">{{ mSummary.lossCount }}</el-descriptions-item>
        <el-descriptions-item label="消耗总重">{{ mSummary.lossTotalWeight }}t</el-descriptions-item>
        <el-descriptions-item label="消耗均重">{{ mSummary.lossAvgWeight }}t</el-descriptions-item>

        <el-descriptions-item label="数量差值">{{ mSummary.countDiff }}</el-descriptions-item>
        <el-descriptions-item label="总重差值">{{ mSummary.weightDiff }}</el-descriptions-item>
        <el-descriptions-item label="均重差值">{{ mSummary.avgWeightDiff }}t</el-descriptions-item>
        <!-- 成品率 -->
        <el-descriptions-item label="成品率">{{ mSummary.passRate }}</el-descriptions-item>
        <el-descriptions-item label="损耗率">{{ mSummary.lossRate }}</el-descriptions-item>
        <!-- 异常率 -->
        <el-descriptions-item label="异常率">{{ mSummary.abRate }}</el-descriptions-item>
        <!-- 正品率 -->
        <el-descriptions-item label="正品率">{{ mSummary.passRate2 }}</el-descriptions-item>
      </el-descriptions>

      <!-- 异常统计（team 类型显示） -->
      <el-descriptions v-if="reportType === 'team'" title="异常统计" :column="4" border>
        <el-descriptions-item v-for="item in abSummary" :key="item.label" :label="item.label">{{ item.value
        }}</el-descriptions-item>
      </el-descriptions>

      <!-- 班组统计信息（team 类型显示） -->
      <template v-if="reportType === 'team'">
        <el-descriptions title="班组统计信息" :column="3" border>
        </el-descriptions>
        <el-table :data="teamSummary" border>
          <el-table-column label="班组" align="center" prop="team" />
          <el-table-column label="产出数量" align="center" prop="outCount" />
          <el-table-column label="产出总重" align="center" prop="outWeight" />
        </el-table>
      </template>
    </template>

    <!-- 明细信息和标签页 -->
    <el-descriptions title="明细信息" :column="3" border>
    </el-descriptions>
    <el-tabs v-if="reportType !== 'out' && reportType !== 'loss'" v-model="activeTab">
      <el-tab-pane label="投入钢卷" name="loss">
        <coil-table :data="lossList" :columns="lossColumns" :loading="loading" height="calc(100vh - 360px)" />
      </el-tab-pane>
      <el-tab-pane label="产出钢卷" name="output">
        <coil-table :data="outList" :columns="outputColumns" :loading="loading" height="calc(100vh - 360px)" />
      </el-tab-pane>
    </el-tabs>
    <!-- out 类型只显示产出钢卷 -->
    <coil-table v-else-if="reportType === 'out'" :columns="outputColumns" :data="outList"></coil-table>
    <!-- loss 类型只显示投入钢卷 -->
    <coil-table v-else-if="reportType === 'loss'" :columns="lossColumns" :data="lossList"></coil-table>

    <el-dialog title="列设置" :visible.sync="settingVisible" width="50%">
      <el-radio-group v-model="activeColumnConfig">
        <el-radio-button label="coil-report-loss">投入明细配置</el-radio-button>
        <el-radio-button label="coil-report-output">产出明细配置</el-radio-button>
      </el-radio-group>
      <columns-setting :reportType="activeColumnConfig"></columns-setting>
    </el-dialog>
  </div>
</template>

<script>
import { listCoilWithIds } from "@/api/wms/coil";
import {
  listPendingAction,
} from '@/api/wms/pendingAction';
import MemoInput from "@/components/MemoInput";
import MutiSelect from "@/components/MutiSelect";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
import CoilNo from "@/components/KLPService/Renderer/CoilNo.vue";
import WarehouseSelect from "@/components/KLPService/WarehouseSelect";
import { calcSummary, calcAbSummary, calcTeamSummary, calcMSummary } from "@/views/wms/report/js/calc";
import CoilTable from "@/views/wms/report/components/coilTable";
import ColumnsSetting from "@/views/wms/report/components/setting/columns";
import TimeRangePicker from "@/views/wms/report/components/timeRangePicker.vue";

import { saveReportFile } from "@/views/wms/report/js/reportFile";

export default {
  name: 'MergeTemplate',
  props: {
    actionType: {
      type: [Number, String],
      required: true
    },
    productionLine: {
      type: String,
      default: '',
    },
    reportType: {
      type: String,
      default: 'day', // day | month | year | all | team | out | loss
    },
    warehouseOptions: {
      type: Array,
      default: () => []
    }
  },
  components: {
    MemoInput,
    MutiSelect,
    ProductInfo,
    RawMaterialInfo,
    CoilNo,
    WarehouseSelect,
    CoilTable,
    ColumnsSetting,
    TimeRangePicker
  },
  dicts: ['product_coil_status', 'coil_material', 'coil_itemname', 'coil_manufacturer', 'coil_quality_status'],
  data() {
    // 工具函数：个位数补零
    const addZero = (num) => num.toString().padStart(2, '0')

    // 获取当前日期
    const now = new Date()
    const currentYear = `${now.getFullYear()}`
    const currentMonth = `${now.getFullYear()}-${addZero(now.getMonth() + 1)}`
    const currentDay = `${now.getFullYear()}-${addZero(now.getMonth() + 1)}-${addZero(now.getDate())}`

    // 获取昨天的日期（用于 out 和 loss 类型的默认时间）
    const yesterday = new Date(now)
    yesterday.setDate(yesterday.getDate() - 1)
    const yesYear = yesterday.getFullYear()
    const yesMonth = addZero(yesterday.getMonth() + 1)
    const yesDay = addZero(yesterday.getDate())
    const defaultStartTime = `${yesYear}-${yesMonth}-${yesDay} 07:00:00`
    const defaultEndTime = `${now.getFullYear()}-${addZero(now.getMonth() + 1)}-${addZero(now.getDate())} 07:00:00`

    /**
     * 生成指定日期/月份/年份的时间范围字符串
     * @param {string} dateStr - 支持格式：yyyy（年份）、yyyy-MM（月份）或 yyyy-MM-dd（具体日期）
     * @returns {object} 包含start（开始时间）和end（结束时间）的对象
     */
    const getDayTimeRange = (dateStr) => {
      // 先校验输入格式是否合法
      const yearPattern = /^\d{4}$/; // yyyy 正则
      const monthPattern = /^\d{4}-\d{2}$/; // yyyy-MM 正则
      const dayPattern = /^\d{4}-\d{2}-\d{2}$/; // yyyy-MM-dd 正则

      let startDate, endDate;

      if (yearPattern.test(dateStr)) {
        // 处理 yyyy 格式：获取本年第一天和最后一天
        startDate = `${dateStr}-01-01`;
        endDate = `${dateStr}-12-31`;
      } else if (monthPattern.test(dateStr)) {
        // 处理 yyyy-MM 格式：获取本月第一天和最后一天
        const [year, month] = dateStr.split('-').map(Number);
        // 第一天：yyyy-MM-01
        startDate = `${dateStr}-01`;
        // 最后一天：通过 new Date(year, month, 0) 计算（month是原始月份，比如2代表2月，传2则取3月0日=2月最后一天）
        const lastDayOfMonth = new Date(year, month, 0).getDate();
        endDate = `${dateStr}-${lastDayOfMonth.toString().padStart(2, '0')}`;
      } else if (dayPattern.test(dateStr)) {
        // 处理 yyyy-MM-dd 格式：直接使用传入的日期
        startDate = dateStr;
        endDate = dateStr;
      } else {
        throw new Error('输入格式错误，请传入 yyyy、yyyy-MM 或 yyyy-MM-dd 格式的字符串');
      }

      // 拼接时间部分
      return {
        start: `${startDate} 00:00:00`,
        end: `${endDate} 23:59:59`
      };
    };

    const { start, end } = getDayTimeRange(currentMonth);

    return {
      lossList: [],
      outList: [],
      activeTab: 'loss',
      activeColumnConfig: 'coil-report-loss',
      settingVisible: false,
      loading: false,
      dayDate: currentDay,
      monthDate: currentMonth,
      yearDate: currentYear,
      defaultStartTime,
      defaultEndTime,
      getDayTimeRange,
      queryParams: {
        startTime: start,
        endTime: end,
        // byCreateTimeStart: start,
        // byCreateTimeEnd: end,
        enterCoilNo: '',
        currentCoilNo: '',
        warehouseId: '',
        itemName: '',
        itemSpecification: '',
        itemMaterial: '',
        itemManufacturer: '',
        team: '',
        pageSize: 9999,
        pageNum: 1,
      },
      warehouseIds: [
        '1988150099140866050',
        '1988150263284953089',
        '1988150545175736322',
        '1988150150521090049',
        '2019583656787259393',
        '2019583325311414274',
        '2019583429955104769',
        '2019583137616310273',
      ],
      lossColumns: [],
      outputColumns: [],
      actionIds: ''
    }
  },
  computed: {
    summary() {
      return calcSummary(this.outList, this.lossList)
    },
    mSummary() {
      return calcMSummary(this.outList, this.lossList)
    },
    abSummary() {
      return calcAbSummary(this.outList)
    },
    teamSummary() {
      const teamOutSummary = calcTeamSummary(this.outList);
      const allTeams = [...new Set(Object.keys(teamOutSummary))];
      return allTeams.map(team => {
        const outData = teamOutSummary[team] || { count: 0, weight: 0 };
        const formatWeight = (weight) => Number(weight || 0).toFixed(2);
        return {
          team: team,
          outCount: outData.count,
          outWeight: formatWeight(outData.weight)
        };
      });
    },
    // out 类型的统计
    outSummary() {
      const totalCount = this.outList.length;
      const totalWeight = this.outList.reduce((acc, cur) => acc + parseFloat(cur.netWeight), 0);
      const avgWeight = totalCount > 0 ? (totalWeight / totalCount).toFixed(2) : 0;
      return {
        totalCount,
        totalWeight: totalWeight.toFixed(2),
        avgWeight,
      };
    },
    // loss 类型的统计
    lossSummary() {
      const totalCount = this.lossList.length;
      const totalWeight = this.lossList.reduce((acc, cur) => acc + parseFloat(cur.netWeight), 0);
      const avgWeight = totalCount > 0 ? (totalWeight / totalCount).toFixed(2) : 0;
      return {
        totalCount,
        totalWeight: totalWeight.toFixed(2),
        avgWeight,
      };
    }
  },
  watch: {
    warehouseOptions: {
      handler(newVal) {
        if (newVal) {
          this.warehouseIds = newVal.map(item => item.value);
        }
      },
      immediate: true
    }
  },
  created() {
    this.initDateByReportType()
    this.handleQuery()
    this.loadColumns()
  },
  methods: {
    // 根据 reportType 初始化日期
    initDateByReportType() {
      if (this.reportType === 'out' || this.reportType === 'loss') {
        // out 和 loss 类型使用默认时间
        this.queryParams.startTime = this.defaultStartTime;
        this.queryParams.endTime = this.defaultEndTime;
      } else if (this.reportType === 'team') {
        // team 类型初始化 byCreateTimeStart 和 byCreateTimeEnd
        const { start, end } = this.getDayTimeRange(this.dayDate);
        this.queryParams.byCreateTimeStart = start;
        this.queryParams.byCreateTimeEnd = end;
      } else {
        let dateStr;
        if (this.reportType === 'year') {
          dateStr = this.yearDate;
        } else if (this.reportType === 'month') {
          dateStr = this.monthDate;
        } else if (this.reportType === 'day') {
          dateStr = this.dayDate;
        } else {
          // all 类型，默认使用当前月份
          dateStr = this.monthDate;
        }
        const { start, end } = this.getDayTimeRange(dateStr);
        this.queryParams.startTime = start;
        this.queryParams.endTime = end;
      }
    },
    // 日期变更处理
    handleDateChange() {
      let dateStr;
      if (this.reportType === 'year') {
        dateStr = this.yearDate;
      } else if (this.reportType === 'month') {
        dateStr = this.monthDate;
      } else if (this.reportType === 'day') {
        dateStr = this.dayDate;
      }
      if (dateStr) {
        const { start, end } = this.getDayTimeRange(dateStr);
        this.queryParams.startTime = start;
        this.queryParams.endTime = end;
        this.handleQuery();
      }
    },
    handleQuery() {
      this.getList()
    },
    async getList() {
      this.loading = true;

      // 所有报表类型都使用原始的 listPendingAction 方式获取数据
      const res = await listPendingAction({ ...this.queryParams, actionTypes: this.actionType, actionStatus: 2 });
      // 获取两层数据
      const lossIds = res.rows.filter(item => item.coilId).map(item => item.coilId);
      const lossActionIds = res.rows.filter(item => item.actionId).map(item => item.actionId);
      this.actionIds = lossActionIds.join(',')
      // 使用new Set去重
      const outIds = [...new Set(res.rows.filter(item => item.processedCoilIds).map(item => item.processedCoilIds))];

      if (lossIds.length === 0 || outIds.length === 0) {
        this.$message({
          message: '查询结果为空',
          type: 'warning'
        })
        this.loading = false;
        return
      }

      const [lossRes, outRes] = await Promise.all([
        listCoilWithIds({ ...this.queryParams, actionIds: lossActionIds.join(',') || '', startTime: '', endTime: '', selectType: 'raw_material' }),
        listCoilWithIds({ ...this.queryParams, coilIds: outIds.join(',') || '', startTime: '', endTime: '', selectType: 'product' }),
      ]);

      // 根据 reportType 决定填充哪些数据
      if (this.reportType === 'out') {
        // 产出报表模式：只填充产出数据
        this.outList = outRes.rows.map(item => {
          const [thickness, width] = item.specification?.split('*') || []
          return {
            ...item,
            computedThickness: parseFloat(thickness),
            computedWidth: parseFloat(width),
          }
        });
        this.lossList = []; // 清空消耗数据
      } else if (this.reportType === 'loss') {
        // 消耗报表模式：只填充消耗数据
        this.lossList = lossRes.rows.map(item => {
          const [thickness, width] = item.specification?.split('*') || []
          return {
            ...item,
            computedThickness: parseFloat(thickness),
            computedWidth: parseFloat(width),
          }
        });
        this.outList = []; // 清空产出数据
      } else {
        // team/day/month/year/all 类型：填充两者数据
        this.lossList = lossRes.rows.map(item => {
          const [thickness, width] = item.specification?.split('*') || []
          return {
            ...item,
            computedThickness: parseFloat(thickness),
            computedWidth: parseFloat(width),
          }
        });
        this.outList = outRes.rows.map(item => {
          const [thickness, width] = item.specification?.split('*') || []
          return {
            ...item,
            computedThickness: parseFloat(thickness),
            computedWidth: parseFloat(width),
          }
        });
      }

      this.loading = false;
    },
    // 导出
    exportData() {
      if (this.outList.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }
      // 根据 reportType 调整文件名
      let fileName = `materialCoil_${new Date().getTime()}.xlsx`;
      if (['day', 'month', 'year'].includes(this.reportType)) {
        fileName = `materialCoil_${this.queryParams.date || ''}_${new Date().getTime()}.xlsx`;
      }
      this.download('wms/materialCoil/export', {
        coilIds: this.outList.map(item => item.coilId).join(',')
      }, fileName)
    },
    exportLossData() {
      if (this.lossList.length === 0) {
        this.$message.warning('暂无数据可导出')
        return
      }
      // 根据 reportType 调整文件名
      let fileName = `materialCoil_${new Date().getTime()}.xlsx`;
      if (['day', 'month', 'year'].includes(this.reportType)) {
        fileName = `materialCoil_${this.queryParams.date || ''}_${new Date().getTime()}.xlsx`;
      }

      this.download('wms/materialCoil/export', {
        actionIds: this.actionIds
      }, fileName)
    },
    // 保存产出报表
    saveOutputReport() {
      this.loading = true
      // 根据 reportType 调整报表类型
      let reportTypeStr = '产出报表';
      if (this.reportType === 'day') {
        reportTypeStr = '产出报表,日报表';
      } else if (this.reportType === 'month') {
        reportTypeStr = '产出报表,月报表';
      } else if (this.reportType === 'year') {
        reportTypeStr = '产出报表,年报表';
      } else if (this.reportType === 'team') {
        reportTypeStr = '产出报表,班报表';
      }
      saveReportFile(this.outList.map(item => item.coilId).join(','), {
        reportParams: this.queryParams,
        reportType: reportTypeStr,
        productionLine: this.productionLine,
      }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
      }).catch(err => {
        this.$message({
          message: '保存失败',
          type: 'error',
        })
      }).finally(() => {
        this.loading = false
      })
    },
    // 保存消耗报表
    saveLossReport() {
      this.loading = true
      // 根据 reportType 调整报表类型
      let reportTypeStr = '消耗报表';
      if (this.reportType === 'day') {
        reportTypeStr = '消耗报表,日报表';
      } else if (this.reportType === 'month') {
        reportTypeStr = '消耗报表,月报表';
      } else if (this.reportType === 'year') {
        reportTypeStr = '消耗报表,年报表';
      } else if (this.reportType === 'team') {
        reportTypeStr = '消耗报表,班报表';
      }
      saveReportFile(this.lossList.map(item => item.coilId).join(','), {
        reportParams: this.queryParams,
        reportType: reportTypeStr,
        productionLine: this.productionLine,
      }).then(res => {
        this.$message({
          message: '保存成功',
          type: 'success',
        })
      }).catch(err => {
        this.$message({
          message: '保存失败',
          type: 'error',
        })
      }).finally(() => {
        this.loading = false
      })
    },
    // 加载列设置
    loadColumns() {
      this.lossColumns = JSON.parse(localStorage.getItem('preference-tableColumns-coil-report-loss') || '[]') || []
      this.outputColumns = JSON.parse(localStorage.getItem('preference-tableColumns-coil-report-output') || '[]') || []
    }
  }
}
</script>

<style></style>