<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="入场钢卷号" prop="enterCoilNo">
        <el-input v-model="queryParams.enterCoilNo" placeholder="请输入入场钢卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="当前钢卷号" prop="currentCoilNo">
        <el-input v-model="queryParams.currentCoilNo" placeholder="请输入当前钢卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="数据状态">
        <el-select v-model="queryParams.dataType" placeholder="请选择数据状态" clearable>
          <el-option :value="0" label="历史数据">历史数据</el-option>
          <el-option :value="1" label="当前数据">当前数据</el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="所在库位" prop="warehouseId" v-if="!hideWarehouseQuery">
        <warehouse-select v-model="queryParams.warehouseId" placeholder="请选择仓库/库区/库位"
          style="width: 100%; display: inline-block;" clearable />
      </el-form-item>
      <el-form-item label="实际库区" prop="actualWarehouseId" v-if="!hideWarehouseQuery">
        <actual-warehouse-select v-model="queryParams.actualWarehouseId" placeholder="请选择实际库位"
          style="width: 100%; display: inline-block;" clearable />
      </el-form-item>
      <el-form-item label="厂家卷号" prop="supplierCoilNo">
        <el-input v-model="queryParams.supplierCoilNo" placeholder="请输入厂家原料卷号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in dict.type.product_coil_status" :key="item.value" :value="parseInt(item.value)"
            :label="item.label" />
        </el-select>
      </el-form-item>

      <MaterialSelect :hideType="hideType" :itemId.sync="queryParams.itemIds" :itemType.sync="queryParams.itemType"
        :multiple="true" />

      <el-form-item label="班组" prop="team">
        <el-input v-model="queryParams.team" placeholder="请输入班组" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker size="mini" v-model="queryParams.updateTime" type="daterange" value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleCheck">修正</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
          @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialCoilList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入场钢卷号" align="center" prop="enterCoilNo" />
      <el-table-column label="当前钢卷号" align="center" prop="currentCoilNo" />
      <el-table-column label="厂家卷号" align="center" prop="supplierCoilNo" />
      <el-table-column label="逻辑库位" align="center" prop="warehouseName" v-if="!hideWarehouseQuery" />
      <el-table-column label="实际库区" align="center" prop="actualWarehouseName" v-if="!hideWarehouseQuery" />
      <!-- <el-table-column label="物料类型" align="center" prop="itemType">
        <template slot-scope="scope">
          {{ scope.row.itemType  == 'raw_material' ? '原料' : '产品' }}
        </template>
</el-table-column> -->
      <el-table-column label="物料类型" align="center" prop="materialType" />
      <el-table-column label="产品类型" align="center" prop="itemName">
        <template slot-scope="scope">
          <ProductInfo v-if="scope.row.itemType == 'product'" :productId="scope.row.itemId">
            <template slot-scope="{ product }">
              {{ product.productName }}[{{ product.specification }}]
            </template>
          </ProductInfo>
          <RawMaterialInfo v-else-if="scope.row.itemType === 'raw_material'" :materialId="scope.row.itemId">
            <template slot-scope="{ material }">
              {{ material.rawMaterialName }}[{{ material.specification }}]
            </template>
          </RawMaterialInfo>
        </template>
      </el-table-column>
      <!-- <el-table-column label="数据类型" align="center" prop="dataType">
        <template slot-scope="scope">
          {{ scope.row.dataType == 0 ? '历史数据' : '当前数据' }}
        </template>
      </el-table-column> -->
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column label="更新人" align="center" prop="updateBy" />

      <el-table-column label="二维码" v-if="qrcode">
        <template slot-scope="scope">
          <QRCode :content="scope.row.qrcodeRecordId" :size="50" />
        </template>
      </el-table-column>
      <el-table-column label="状态" v-if="showStatus" align="center" prop="status">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" placeholder="请选择状态" @change="handleStatusChange(scope.row)">
            <el-option v-for="item in dict.type.product_coil_status" :key="item.value" :value="parseInt(item.value)"
              :label="item.label" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="班组" align="center" prop="team" />
      <el-table-column label="毛重" align="center" prop="grossWeight" />
      <el-table-column label="净重" align="center" prop="netWeight" />
      <el-table-column v-if="querys.materialType === '成品'" label="质量状态" align="center" prop="qualityStatus" />
      <el-table-column v-if="querys.materialType === '成品'" label="切边要求" align="center" prop="trimmingRequirement" />
      <el-table-column v-if="querys.materialType === '成品'" label="打包状态" align="center" prop="packingStatus" />
      <el-table-column v-if="querys.materialType === '成品'" label="包装要求" align="center" prop="packagingRequirement" />
       <!-- <el-form-item v-if="form.materialType === '成品'" label="质量状态" prop="qualityStatus">
          <el-input v-model="form.qualityStatus" placeholder="请输入质量状态"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="切边要求" prop="trimmingRequirement">
          <el-input v-model="form.trimmingRequirement" placeholder="请输入切边要求"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="打包状态" prop="packingStatus">
          <el-input v-model="form.packingStatus" placeholder="请输入打包状态"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="包装要求" prop="packagingRequirement">
          <el-input v-model="form.packagingRequirement" placeholder="请输入包装要求"
            :disabled="readonly">
          </el-input>
        </el-form-item> -->
      <el-table-column label="关联信息" align="center" prop="parentCoilNos" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.parentCoilNos && scope.row.hasMergeSplit === 1 && scope.row.dataType === 1">
            <el-tag type="warning" size="mini">来自母卷：{{ scope.row.parentCoilNos }}</el-tag>
          </span>
          <span v-else-if="scope.row.parentCoilNos && scope.row.dataType === 0">
            <el-tag type="info" size="mini">分为子卷：{{ scope.row.parentCoilNos }}</el-tag>
          </span>
          <span v-else-if="scope.row.parentCoilNos && scope.row.hasMergeSplit === 2">
            <el-tag type="success" size="mini">合并自：{{ scope.row.parentCoilNos }}</el-tag>
          </span>
          <span v-else>—</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handlePreviewLabel(scope.row)">
            导出标签
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCheck(scope.row)">修正</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-search" @click="handleTrace(scope.row)">追溯</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改钢卷物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="入场钢卷号" prop="enterCoilNo">
          <el-input v-model="form.enterCoilNo" placeholder="请输入入场钢卷号" :disabled="form.coilId" />
        </el-form-item>
        <el-form-item label="当前钢卷号" prop="currentCoilNo">
          <el-input v-model="form.currentCoilNo" placeholder="请输入当前钢卷号" />
        </el-form-item>
        <el-form-item v-if="!form.coilId" label="厂家原料卷号" prop="supplierCoilNo">
          <el-input v-model="form.supplierCoilNo" placeholder="请输入厂家原料卷号" />
        </el-form-item>
        <el-form-item label="所在库位" prop="warehouseId">
          <warehouse-select v-model="form.warehouseId" placeholder="请选择仓库/库区/库位" style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="实际库区" prop="actualWarehouseId">
          <actual-warehouse-select v-model="form.actualWarehouseId" placeholder="请选择实际库区" style="width: 100%;"
            clearable />
        </el-form-item>
        <el-form-item label="班组" prop="team">
          <el-input v-model="form.team" placeholder="请输入班组" />
        </el-form-item>
        <el-form-item label="材料类型" prop="materialType" v-if="!form.coilId">
          <el-select v-model="form.materialType" placeholder="请选择材料类型" @change="handleMaterialTypeChange">
            <el-option label="成品" value="成品" />
            <el-option label="原料" value="原料" />
            <el-option label="废品" value="废品" />
          </el-select>
        </el-form-item>
        <el-form-item :label="getItemLabel" prop="itemId" v-if="!form.coilId">
          <product-select v-if="form.itemType == 'product'" v-model="form.itemId" placeholder="请选择成品"
            style="width: 100%;" clearable />
          <raw-material-select v-else-if="form.itemType == 'raw_material'" v-model="form.itemId" placeholder="请选择原料"
            style="width: 100%;" clearable />
          <div v-else>请先选择材料类型</div>
        </el-form-item>
        <el-form-item v-if="form.materialType === '成品'" label="质量状态" prop="qualityStatus">
          <el-input v-model="form.qualityStatus" placeholder="请输入质量状态"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="切边要求" prop="trimmingRequirement">
          <el-input v-model="form.trimmingRequirement" placeholder="请输入切边要求"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="打包状态" prop="packingStatus">
          <el-input v-model="form.packingStatus" placeholder="请输入打包状态"
            :disabled="readonly">
          </el-input>
        </el-form-item>

        <el-form-item v-if="form.materialType === '成品'" label="包装要求" prop="packagingRequirement">
          <el-input v-model="form.packagingRequirement" placeholder="请输入包装要求"
            :disabled="readonly">
          </el-input>
        </el-form-item>
        <el-form-item label="毛重" prop="grossWeight">
          <el-input v-model="form.grossWeight" placeholder="请输入毛重" />
        </el-form-item>
        <el-form-item label="净重" prop="netWeight">
          <el-input v-model="form.netWeight" placeholder="请输入净重" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 钢卷追溯对话框（使用封装的组件） -->
    <el-dialog title="钢卷追溯" :visible.sync="traceOpen" width="90%" append-to-body>
      <coil-trace-result :trace-result="traceResult"></coil-trace-result>
    </el-dialog>

    <!-- 标签预览弹窗 -->
    <el-dialog title="标签预览" :visible.sync="labelRender.visible" append-to-body>
      <label-render :content="labelRender.data" :labelType="labelType" />
    </el-dialog>
  </div>
</template>

<script>
import { listMaterialCoil, getMaterialCoil, delMaterialCoil, addMaterialCoil, updateMaterialCoilSimple, getMaterialCoilTrace } from "@/api/wms/coil";
import WarehouseSelect from "@/components/KLPService/WarehouseSelect";
import QRCode from "../../print/components/QRCode.vue";
import * as XLSX from 'xlsx'
import { saveAsImage } from '@/utils/klp';
import ProductSelect from "@/components/KLPService/ProductSelect";
import RawMaterialSelect from "@/components/KLPService/RawMaterialSelect";
// import MaterialSelect from "@/components/KLPService/ProductSelect";
import ProductInfo from "@/components/KLPService/Renderer/ProductInfo";
import BomInfoMini from "@/components/KLPService/Renderer/BomInfoMini";
import RawMaterialInfo from "@/components/KLPService/Renderer/RawMaterialInfo";
// 引入封装的追溯结果组件
import CoilTraceResult from "./CoilTraceResult.vue"; // 路径根据实际存放位置调整
import LabelRender from './LabelRender/index.vue'
import MaterialSelect from "@/components/KLPService/MaterialSelect";
import ActualWarehouseSelect from "@/components/KLPService/ActualWarehouseSelect";
import { findItemWithBom } from "@/store/modules/category";

export default {
  name: "MaterialCoil",
  components: {
    WarehouseSelect,
    QRCode,
    MaterialSelect,
    ProductSelect,
    RawMaterialSelect,
    ProductInfo,
    RawMaterialInfo,
    BomInfoMini,
    CoilTraceResult,
    LabelRender,
    ActualWarehouseSelect
  },
  dicts: ['product_coil_status'],
  props: {
    qrcode: {
      type: Boolean,
      default: false,
    },
    querys: {
      type: Object,
      default: () => { },
    },
    labelType: {
      type: String,
      default: '2'
    },
    hideWarehouseQuery: {
      type: Boolean,
      default: false,
    },
    showStatus: {
      type: Boolean,
      default: false,
    },
    hideType: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 钢卷物料表格数据
      materialCoilList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 追溯对话框显示
      traceOpen: false,
      // 追溯结果数据（传递给组件）
      traceResult: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enterCoilNo: undefined,
        currentCoilNo: undefined,
        supplierCoilNo: undefined,
        warehouseId: undefined,
        nextWarehouseId: undefined,
        actualWarehouseId: undefined,
        qrcodeRecordId: undefined,
        team: undefined,
        hasMergeSplit: undefined,
        parentCoilNos: undefined,
        itemId: undefined,
        itemIds: undefined,
        status: undefined,
        updateTime: undefined,
        ...this.querys,
      },
      // 表单参数
      form: {},
      transferCoilForm: {},
      // 表单校验
      rules: {
        enterCoilNo: [
          { required: true, message: "入场钢卷号不能为空", trigger: "blur" }
        ],
        currentCoilNo: [
          { required: true, message: "当前钢卷号不能为空", trigger: "blur" }
        ],
        itemId: [
          { required: true, message: "物品ID不能为空", trigger: "blur" }
        ],
        itemType: [
          { required: true, message: "物品类型不能为空", trigger: "change" }
        ],
        // 净重和毛重
        netWeight: [
          { required: true, message: "净重不能为空", trigger: "blur" }
        ],
        grossWeight: [
          { required: true, message: "毛重不能为空", trigger: "blur" }
        ],
      },
      labelRender: {
        visible: false,
        data: {},
        type: '2'
      }
    };
  },
  computed: {
    // 动态显示标签
    getItemLabel() {
      if (this.form.materialType === '成品') {
        return '产品类型';
      } else if (this.form.materialType === '原料' || this.form.materialType === '废品') {
        return '原料类型';
      }
      return '物品类型';
    },
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理材料类型变化
    handleMaterialTypeChange(value) {
      // 清空物品选择
      this.form.itemId = null;

      // 根据材料类型设置物品类型
      if (value === '成品') {
        this.form.itemType = 'product';
      } else if (value === '原料' || value === '废品') {
        this.form.itemType = 'raw_material';
      }
    },
    /** 查询钢卷物料列表 */
    getList() {
      this.loading = true;
      const { updateTime, ...query } = {
        ...this.queryParams,
        startTime: this.queryParams.updateTime?.[0],
        endTime: this.queryParams.updateTime?.[1],
      }
      listMaterialCoil(query).then(response => {
        if (this.querys.warehouseId != 111) {
          // 排除掉111仓库的
          this.materialCoilList = response.rows.filter(item => item.warehouseId != 111)
        } else {
          this.materialCoilList = response.rows;
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 状态改变时触发 */
    handleStatusChange(row) {
      updateMaterialCoilSimple(row).then(res => {
        this.$message.success('状态更新成功');
        this.getList(); // 刷新列表
      }).catch(err => {
        console.error('状态更新失败：', err);
        this.$message.error('状态更新失败，请重试');
      });
    },
    /** 追溯按钮操作 */
    handleTrace(row) {
      this.traceOpen = true;
      this.traceResult = null; // 清空历史数据
      getMaterialCoilTrace({
        enterCoilNo: row.enterCoilNo,
        currentCoilNo: row.currentCoilNo,
      }).then(res => {
        this.traceResult = res.data; // 将结果传递给组件
      }).catch(err => {
        console.error('溯源查询失败：', err);
        this.$message.error('溯源查询失败，请重试');
      });
    },
    /** 预览标签 */
    handlePreviewLabel(row) {
      this.labelRender.visible = true;
      const item = findItemWithBom(row.itemType, row.itemId)
      // 寻找boms中bom键名为'材质'的
      const material = item?.boms?.find(bom => bom.attrKey === '材质')

      console.log('规格', item)
      this.labelRender.data = {
        ...row,
        itemName: item?.itemName || '',
        material: material?.attrValue || '',
        specification: item?.specification || '',
        
      };
    },
    /** 下载二维码 */
    handleDownloadQRCode(row) {
      try {
        saveAsImage(
          row.qrcodeRecordId,
          '',
          1,
          {
            barcodeWidth: 200,
            barcodeHeight: 200
          }
        );
        this.$message.success('图片保存成功');
      } catch (error) {
        console.error('保存图片失败', error);
        this.$message.error('保存图片失败，请稍后重试');
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        coilId: undefined,
        enterCoilNo: undefined,
        currentCoilNo: undefined,
        supplierCoilNo: undefined,
        dataType: undefined,
        warehouseId: undefined,
        nextWarehouseId: undefined,
        qrcodeRecordId: undefined,
        actualWarehouseId: undefined,
        team: undefined,
        hasMergeSplit: undefined,
        parentCoilNos: undefined,
        itemId: undefined,
        itemType: undefined,
        status: undefined,
        remark: undefined,
        delFlag: undefined,
        createTime: undefined,
        createBy: undefined,
        updateTime: undefined,
        updateBy: undefined,
        materialType: '原料',
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.coilId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isCheck = false;
      this.reset();

      // 如果父组件传入了 materialType，使用它作为默认值
      if (this.querys.materialType) {
        this.form.materialType = this.querys.materialType;
        // 同时设置对应的 itemType
        if (this.querys.materialType === '成品') {
          this.form.itemType = 'product';
        } else if (this.querys.materialType === '原料' || this.querys.materialType === '废品') {
          this.form.itemType = 'raw_material';
        }
      }

      this.open = true;
      this.title = "添加钢卷物料";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isCheck = false;
      this.loading = true;
      this.reset();
      const coilId = row.coilId || this.ids
      getMaterialCoil(coilId).then(response => {
        this.loading = false;
        this.form = response.data;

        // 设置 materialType（优先级：后端返回 > itemType推断 > 父组件传入）
        if (!this.form.materialType) {
          if (this.form.itemType) {
            // 根据 itemType 推断
            if (this.form.itemType === 'product') {
              this.form.materialType = '成品';
            } else if (this.form.itemType === 'raw_material') {
              this.form.materialType = '原料';
            }
          } else if (this.querys.materialType) {
            // 使用父组件传入的默认值
            this.form.materialType = this.querys.materialType;
            // 同时设置对应的 itemType
            if (this.querys.materialType === '成品') {
              this.form.itemType = 'product';
            } else if (this.querys.materialType === '原料' || this.querys.materialType === '废品') {
              this.form.itemType = 'raw_material';
            }
          }
        }

        this.open = true;
        this.title = "修改钢卷物料";
      });
    },
    handleCheck(row) {
      this.isCheck = true;
      this.loading = true;
      this.reset();
      const coilId = row.coilId || this.ids
      getMaterialCoil(coilId).then(response => {
        this.loading = false;
        this.form = response.data;

        // 设置 materialType（优先级：后端返回 > itemType推断 > 父组件传入）
        if (!this.form.materialType) {
          if (this.form.itemType) {
            // 根据 itemType 推断
            if (this.form.itemType === 'product') {
              this.form.materialType = '成品';
            } else if (this.form.itemType === 'raw_material') {
              this.form.materialType = '原料';
            }
          } else if (this.querys.materialType) {
            // 使用父组件传入的默认值
            this.form.materialType = this.querys.materialType;
            // 同时设置对应的 itemType
            if (this.querys.materialType === '成品') {
              this.form.itemType = 'product';
            } else if (this.querys.materialType === '原料' || this.querys.materialType === '废品') {
              this.form.itemType = 'raw_material';
            }
          }
        }

        this.open = true;
        this.title = "修改钢卷物料";
      });
    },
    transferCoil() { },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.coilId != null) {
            updateMaterialCoilSimple(this.form).then(_ => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterialCoil(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const coilIds = row.coilId || this.ids;
      this.$modal.confirm('是否确认删除钢卷物料编号为"' + coilIds + '"的数据项？').then(() => {
        this.loading = true;
        return delMaterialCoil(coilIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出选中数据操作 */
    handleExport() {
      // 1. 判断是否有选中数据
      if (this.ids.length === 0) {
        this.$message.warning('请先选中要导出的数据');
        return;
      }

      // 2. 筛选选中的数据（通过ids匹配表格数据）
      const selectedData = this.materialCoilList.filter(item =>
        this.ids.includes(item.coilId) // 用选中的coilId匹配表格数据
      );

      // 3. 处理导出数据格式（和之前一致，转换枚举值）
      const exportData = selectedData.map(item => {
        return {
          '入场钢卷号': item.enterCoilNo || '',
          '当前钢卷号': item.currentCoilNo || '',
          '厂家原料卷号': item.supplierCoilNo || '',
          '物料类型': item.itemType === 'product' ? '成品' : '原料',
          '仓区': item.warehouseName || '',
          '实际库区': item.actualWarehouseName || '',
          '物品': findItemWithBom(item.itemType, item.itemId)?.itemName || '',
          '数据类型': item.dataType === 0 ? '历史数据' : '当前数据',
          '班组': item.team || '',
          '毛重': item.grossWeight || '',
          '净重': item.netWeight || '',
          '备注': item.remark || ''
        };
      });

      // 4. 生成Excel并下载（复用之前的逻辑）
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      const workbook = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(workbook, worksheet, '选中钢卷物料');

      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
      this.saveExcelFile(excelBuffer, '选中钢卷物料数据');
    },

    /** 保存Excel文件到本地 */
    saveExcelFile(buffer, fileName) {
      const blob = new Blob([buffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${fileName}_${new Date().getTime()}.xlsx`; // 文件名带时间戳
      document.body.appendChild(a);
      a.click(); // 触发下载
      document.body.removeChild(a); // 清理DOM
      URL.revokeObjectURL(url); // 释放URL对象
    }
  }
};
</script>