<template>
  <div class="app-container">
    <PageTitle>
      <template #buttons>
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="medium"
          @click="handleAdd"
          v-hasPermi="['inventory:materials:add']"
        >新增</el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="medium"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:materials:edit']"
        >修改</el-button>

        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="medium"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:materials:remove']"
        >删除</el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-upload2"
          size="medium"
          @click="handleImport"
          v-hasPermi="['inventory:materials:import']"
        >导入</el-button>

        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="medium"
          @click="handleExport"
          v-hasPermi="['inventory:materials:export']"
        >导出</el-button>

      </template>
    </PageTitle>


    <div class="page-container-noback flex1">
      <div class="flex-container flex1" style="min-height: 200px;overflow: hidden;">
        <div class="card-container shadow" style="overflow: auto;min-width: 16%;">
          <TreeComponent
            ref="treeComponent"
            :tree-data="categoryTreeData"
            :tree-props="treeProps"
            :node-key="nodeKey"
            :show-search="true"
            search-placeholder="请输入分类名称"
            :default-expand-all="true"
            :highlight-current="true"
            :loading="loadingTree"
            @node-click="handleTreeClick"
          >
            <!-- 自定义节点内容插槽 -->
            <template #node-content="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </TreeComponent>
        </div>
        <div class="card-container shadow flex1 right-card flex-container" style="flex-direction: column;padding: 20px;min-height: 200px;">

          <page-wrapper-search
            :model="queryParams"
            ref="queryForm"
            size="small"
            @search="handleQuery"
            @reset="resetQuery"
          >
            <!-- <el-form-item label="物料编码" prop="materialCode">
              <el-input
                v-model="queryParams.materialCode"
                placeholder="请输入物料编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <el-form-item label="SAP物料号" prop="sapNo">
              <el-input
                v-model="queryParams.sapNo"
                placeholder="请输入SAP物料号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料名称" prop="materialName">
              <el-input
                v-model="queryParams.materialName"
                placeholder="请输入物料名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="TS Code" prop="tsCode">
              <el-input
                v-model="queryParams.tsCode"
                placeholder="请输入TS Code"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="物料分类" prop="categoryNameInput">
              <el-input
                v-model="queryParams.categoryNameInput"
                placeholder="请输入物料分类"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="规格型号" prop="specification">
              <el-input
                v-model="queryParams.specification"
                placeholder="请输入规格型号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </page-wrapper-search>

          <!-- 树形数据表格 -->
          <div style="flex: 1;min-height: 200px;">
            <el-table v-loading="loading" height="100%" :data="materialsList" @selection-change="handleSelectionChange" :scroll-x="true">
              <!-- 表格列保持不变 -->
              <el-table-column type="selection" width="55" align="center" fixed/>
              <el-table-column type="index" label="序号" align="center"/>
              <el-table-column label="SAP物料号" align="center" prop="sapNo"  width="150"/>
              <!-- <el-table-column label="物料编码" align="center" prop="materialCode" width="120"/> -->
              <el-table-column label="物料名称" align="center" prop="materialName"  width="150"/>
              <el-table-column label="TS Code" align="center" prop="tsCode"  width="150"/>
              <el-table-column label="物料分类" align="center" prop="categoryCode" >
                <template slot-scope="scope">
                  {{ scope.row.displayCategory || categoryMap[scope.row.categoryCode] || scope.row.categoryCode }}
                </template>
              </el-table-column>
              <el-table-column label="危险类别" align="center" prop="hazardId"  width="150">
                <template slot-scope="scope">
                  <el-tag 
                    :type="getDictListClass('danger_type',scope.row.hazardId)"
                    size="small">
                    {{ getDictLabel('danger_type',scope.row.hazardId) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="规格型号" align="center" prop="specification" />
              <el-table-column label="计量单位" align="center" prop="materialUnit" />
              <el-table-column label="净重量" align="center" prop="unitWeight" />
              <el-table-column label="包装重量" align="center" prop="packageWeight" />
              <el-table-column label="总重量" align="center" prop="totalWeight" />
              <el-table-column label="体积" align="center" prop="volume" />
              <el-table-column label="保质期天数" align="center" prop="shelfLifeDays"  width="120"/>
              <el-table-column label="存储温度要求" align="center" prop="storageTemperature" width="120"/>
              <el-table-column label="特殊存储要求" align="center" prop="specialRequirements" width="120"/>
              <el-table-column label="是否批次管理" align="center" prop="isBatchManaged" width="120">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isBatchManaged === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isBatchManaged === 1 ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="是否序列号管理" align="center" prop="isSerialManaged" width="120">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isSerialManaged === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isSerialManaged === 1 ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="最低库存" align="center" prop="minStockLevel" />
              <el-table-column label="最高库存" align="center" prop="maxStockLevel" />
              <el-table-column label="是否激活" align="center" prop="isActive">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'" size="mini">{{ scope.row.isActive === 1 ? '是' : '否' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="风险等级" align="center" prop="riskLevel" >
                <template slot-scope="scope">
                  <el-tag 
                    :type="getDictListClass('risk_level',scope.row.riskLevel)"
                    size="small">
                    {{ getDictLabel('risk_level',scope.row.riskLevel) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="排序" align="center" prop="sortNo" />
              <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.updateTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding" fixed="right" width="200">
                <template v-slot="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['inventory:materials:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['inventory:materials:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>


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

    <!-- 添加或修改物料对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <!-- <el-form-item label="物料编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
            </el-form-item> -->
            <el-form-item label="SAP物料号" prop="sapNo">
              <el-input v-model="form.sapNo" placeholder="请输入SAP物料号" />
            </el-form-item>
            <el-form-item label="TS Code" prop="tsCode">
              <el-input v-model="form.tsCode" placeholder="请输入TS Code" />
            </el-form-item>
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" />
            </el-form-item>
            <el-form-item label="单位重量" prop="unitWeight">
              <el-input v-model="form.unitWeight" placeholder="请输入单位重量" />
            </el-form-item>
            <el-form-item label="总重量" prop="totalWeight">
              <el-input v-model="form.totalWeight" placeholder="请输入总重量" />
            </el-form-item>
            <el-form-item label="保质期天数" prop="shelfLifeDays">
              <el-input v-model="form.shelfLifeDays" placeholder="请输入保质期天数" />
            </el-form-item>
            <el-form-item label="特殊存储要求" prop="specialRequirements">
              <el-input v-model="form.specialRequirements" placeholder="请输入特殊存储要求" />
            </el-form-item>
            <el-form-item label="最高库存" prop="maxStockLevel">
              <el-input v-model="form.maxStockLevel" placeholder="请输入最高库存" />
            </el-form-item>
            <el-form-item label="风险等级" prop="riskLevel">
              <el-select v-model="form.riskLevel" placeholder="请选择风险等级" clearable>
                <el-option
                  v-for="dict in dict.type.risk_level"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否序列号管理" prop="isSerialManaged">
              <el-radio-group v-model="form.isSerialManaged">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="是否批次管理" prop="isBatchManaged">
              <el-radio-group v-model="form.isBatchManaged">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物料名称" />
            </el-form-item>
            <el-form-item label="物料分类" prop="categoryCode">
              <el-select v-model="form.categoryCode" placeholder="请选择物料分类" clearable>
                <el-option
                  v-for="item in categoryTreeOptions"
                  :key="item.categoryCode"
                  :label="item.categoryName"
                  :value="item.categoryCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="危险类别" prop="hazardId">
              <el-select v-model="form.hazardId" placeholder="请选择危险类别" clearable>
                <el-option
                  v-for="dict in dict.type.danger_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
             <el-form-item label="包装重量" prop="packageWeight">
              <el-input v-model="form.packageWeight" placeholder="请输入包装重量" />
            </el-form-item>
            <el-form-item label="计量单位" prop="materialUnit">
              <el-input v-model="form.materialUnit" placeholder="请输入计量单位" />
            </el-form-item>
            <el-form-item label="体积" prop="volume">
              <el-input v-model="form.volume" placeholder="请输入体积" />
            </el-form-item>
            <el-form-item label="存储温度要求" prop="storageTemperature">
              <el-input v-model="form.storageTemperature" placeholder="请输入存储温度要求" />
            </el-form-item>
            <el-form-item label="最低库存" prop="minStockLevel">
              <el-input v-model="form.minStockLevel" placeholder="请输入最低库存" />
            </el-form-item>
            <el-form-item label="排序" prop="sortNo">
              <el-input v-model="form.sortNo" placeholder="请输入排序" />
            </el-form-item>
            <el-form-item label="是否激活" prop="isActive">
              <el-radio-group v-model="form.isActive">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>

          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <import-excel
      ref="import"
      title="导入"
      import-url="/inventory/materials/import"
      template-url="inventory/materials/importTemplate"
      template-name="materials_importTemplate"
      @success="getList"
    />
  </div>
</template>

<script>
import { listMaterials, getMaterials, delMaterials, addMaterials, updateMaterials } from "@/api/inventory/materials"
import { listMaterials_category } from "@/api/inventory/materials_category"
import TreeComponent from '@/views/inventory/materials_category/treeComponent.vue'
import { Splitpanes, Pane } from 'splitpanes'
import 'splitpanes/dist/splitpanes.css'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import ImportExcel from "@/components/ImportExcel/index"
import request from '@/utils/request'

export default {
  name: "Materials",
  dicts: ['danger_type','risk_level'],
  components: {
    TreeComponent,
    Splitpanes,
    Pane,
    Treeselect,
    ImportExcel
  },
  data() {
    return {
      // 树相关数据
      categoryTreeData: [],
      treeProps: {
        children: 'children',
        label: 'label',
        value: 'sid'
      },
      nodeKey: 'sid',
      loadingTree: false,

      // 分类映射和选项
      categoryMap: {},
      categoryNameToCodeMap: {},
      categoryTreeOptions: [],
      // 选中数组
      ids: [],
      single: true,
      multiple: true,

      // 显示搜索条件
      showSearch: true,

      // 总条数
      total: 0,

      // 物料表格数据
      materialsList: [],

      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,

      // 当前选中的分类列表
      selectedCategories: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
        categoryCodes: []
      },

      // 表单参数
      form: {
        id: null,
        materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        hazardId: null,
        specification: null,
        materialUnit: null,
        unitWeight: null,
        packageWeight: null,
        totalWeight: null,
        volume: null,
        shelfLifeDays: null,
        storageTemperature: null,
        specialRequirements: null,
        isBatchManaged: 1,
        isSerialManaged: 1,
        minStockLevel: null,
        maxStockLevel: null,
        isUsed: 1,
        isActive: 1,
        riskLevel: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      },

      // 表单校验
      rules: {
        // materialCode: [{ required: true, message: '请输入物料编码', trigger: 'blur' }],
        materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
        sapNo: [{ required: true, message: '请输入SAP物料号', trigger: 'blur' }],
        tsCode: [{ required: true, message: '请输入TS Code', trigger: 'blur' }]
      },

      loading: true
    }
  },

  async created() {
    await Promise.all([
      this.getCategoryTreeData(),
      this.getCategoryList()
    ]);
    this.getList()
  },
  methods: {
     getDictLabel(dictType, value) {
      // 1. 空值/字典不存在时返回默认值
      if (!value || !this.dict?.type?.[dictType]) return '-';
      // 2. 从字典数组中匹配 value 对应的 label
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.label || '-';
    },
    getDictListClass(dictType, value){
      // 1. 空值/字典不存在时返回默认值
      if (!value || !this.dict?.type?.[dictType]) return '-';
      // 2. 从字典数组中匹配 value 对应的 label
      const dictItem = this.dict.type[dictType].find(item => item.value === value);
      return dictItem?.raw?.listClass || '';
    },
    async getCategoryList() {
      try {
        const response = await listMaterials_category({
          pageNum: 1,
          pageSize: 1000
        });

        if (response.rows && response.rows.length > 0) {
          // 正向映射：code → name
              this.categoryMap = {};
          // 反向映射：name → code（支持模糊匹配时用数组存储）
          this.categoryNameToCodeMap = {};

          response.rows.forEach(item => {
            if (item.isUsed !== 0 && item.isUsed !== '0') {
              this.categoryMap[item.categoryCode] = item.categoryName;
              // 反向映射：名称作为key，编码作为value（若名称重复可存数组）
            if (!this.categoryNameToCodeMap[item.categoryName]) {
                this.categoryNameToCodeMap[item.categoryName] = item.categoryCode;
              } else {
                // 处理名称重复的情况（可选）
               if (Array.isArray(this.categoryNameToCodeMap[item.categoryName])) {
                 this.categoryNameToCodeMap[item.categoryName].push(item.categoryCode);
              } else {
                  this.categoryNameToCodeMap[item.categoryName] = [this.categoryNameToCodeMap[item.categoryName], item.categoryCode];
                }
              }
            }
          });

          this.categoryTreeOptions = response.rows
            .filter(item => item.isUsed !== 0 && item.isUsed !== '0')
            .map(item => ({
              categoryCode: item.categoryCode,
              categoryName: item.categoryName
            }));
        }
      } catch (error) {
        console.error('获取分类列表失败:', error);
      }
    },
    /** 获取分类树数据 */
    async getCategoryTreeData() {
      this.loadingTree = true
      try {
        // 调用物料分类列表API获取所有分类
        const response = await listMaterials_category({
          pageNum: 1,
          pageSize: 1000 // 获取足够多的数据
        })

        if (response.rows && response.rows.length > 0) {
          // 过滤掉已禁用的分类
          const activeCategories = response.rows.filter(item =>
            item.isUsed !== 0 && item.isUsed !== '0'
          )

          // 构建树形结构
          this.categoryTreeData = this.buildTreeData(activeCategories)
          console.log('分类树数据:', this.categoryTreeData)
        }
      } catch (error) {
        console.error('获取分类树数据失败:', error)
      } finally {
        this.loadingTree = false
      }
    },

    /** 构建树形结构 */
    buildTreeData(list, parentId = null) {
      const result = list
        .filter(item => {
          if (parentId === null) {
            // 根节点：parentId为null、0或空
            return !item.parentId || item.parentId === 0 || item.parentId === '0'
          } else {
            // 子节点：parentId匹配
            return item.parentId == parentId
          }
        })
        .map(item => {
          const children = this.buildTreeData(list, item.id)
          return {
            ...item,
            sid: String(item.id),
            label: item.categoryName,
            children: children.length > 0 ? children : undefined
          }
        })

      return result
    },

    /** 处理树节点点击 */
    handleTreeClick(data) {
      console.log('点击树节点:', data)
      this.currentNodeId = data.sid

      // 更新查询参数，按选中的分类筛选物料
      this.queryParams.categoryCode = data.categoryCode
      this.queryParams.categoryNameInput = null // 清空名称输入
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 查询物料列表 */
    async getList() {
      this.loading = true
      try {
        let materialsList = [];
        let total = 0;

        // 检查是否有多个分类编码
        if (this.queryParams.categoryCodes && this.queryParams.categoryCodes.length > 0) {
          // 使用getMaterial接口并行获取每个分类的物料
          const promises = this.queryParams.categoryCodes.map(categoryCode =>
            request({
              url: `/inventory/materials/getMaterial/${categoryCode}`,
              method: 'get'
            })
          );

          const results = await Promise.all(promises);

          // 合并所有物料并去重
          const materialMap = new Map();
          results.forEach(result => {
            if (result && result.data) {
              const materials = Array.isArray(result.data) ? result.data : [result.data];
              materials.forEach(material => {
                if (!materialMap.has(material.id)) {
                  materialMap.set(material.id, material);
                  materialsList.push(material);
                }
              });
            }
          });

          total = materialsList.length;
        } else {
          // 单分类或无分类查询，使用原接口
          const response = await listMaterials(this.queryParams);
          materialsList = response.rows;
          total = response.total;
        }

        // 对物料列表中的分类字段做映射处理
        this.materialsList = materialsList
          .filter(item => item.isUsed !== 0 && item.isUsed !== '0')
          .map(item => ({
            ...item,
            // 兜底：如果映射表中没有，显示原始code并标注
            displayCategory: this.categoryMap[item.categoryCode] || `${item.categoryCode}（未匹配分类）`
          }));
        this.total = total;
      } catch (error) {
        console.error('获取物料列表失败:', error);
        this.materialsList = [];
        this.total = 0;
      } finally {
        this.loading = false;
      }
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        hazardId: null,
        specification: null,
        materialUnit: null,
        unitWeight: null,
        packageWeight: null,
        totalWeight: null,
        volume: null,
        shelfLifeDays: null,
        storageTemperature: null,
        specialRequirements: null,
        isBatchManaged: 1,
        isSerialManaged: 1,
        minStockLevel: null,
        maxStockLevel: null,
        isUsed: 1,
        isActive: 1,
        riskLevel: null,
        sortNo: null,
        createUserCode: null,
        updateUserCode: null
      }
      this.$refs.form && this.$refs.form.resetFields()
    },

    /** 搜索按钮操作 */
    handleQuery() {
      // 清空原有分类编码
      this.queryParams.categoryCode = null;

          // 获取用户输入的分类名称
      const inputName = this.queryParams.categoryNameInput;
      if (inputName) {
        // 1. 精确匹配名称 → 编码
        const matchedCode = this.categoryNameToCodeMap[inputName];
        if (matchedCode) {
          // 若有多个编码（名称重复），取第一个
          this.queryParams.categoryCode = Array.isArray(matchedCode) ? matchedCode[0] : matchedCode;
        } else {
          // 2. 模糊匹配名称 → 编码（可选）
          const matchedCodes = Object.entries(this.categoryMap)
            .filter(([code, name]) => name.includes(inputName))
            .map(([code]) => code);
          if (matchedCodes.length > 0) {
            this.queryParams.categoryCode = matchedCodes[0]; // 或传多个（需后端支持）
          }
        }
      }

      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        materialName: null,
        sapNo: null,
        tsCode: null,
        categoryCode: null,
        categoryNameInput: null,
        specification: null,
        categoryCodes: []
      };
      this.selectedCategories = [];

      // 修复树形高亮重置：直接操作 TreeComponent 内部的 el-tree
      if (this.$refs.treeComponent && this.$refs.treeComponent.$refs.tree) {
        this.$refs.treeComponent.$refs.tree.setCurrentKey(null); // 清空选中
        this.$refs.treeComponent.$refs.tree.setCheckedKeys([]); // 清空勾选
      } else if (this.$refs.treeComponent) {
        // 如果 TreeComponent 有自定义重置方法
        this.$refs.treeComponent.resetTree();
      }

      this.getList();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物料"
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getMaterials(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物料"
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const promise = this.form.id
            ? updateMaterials(this.form)
            : addMaterials(this.form)

          promise.then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功")
            this.open = false
            this.getList()
          }).catch(error => {
            console.error('提交失败:', error)
          })
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm(row.id ? '是否确认删除物料号为"' + row.sapNo + '"的数据项？' : '是否确认删除选中数量为"' + ids.length + '"的数据项？' ).then(() => {
        return delMaterials(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },

    /** 导入按钮操作 */
    handleImport() {
      this.$refs.import.show()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/materials/export', {
        ...this.queryParams
      }, `materials_${new Date().getTime()}.xlsx`)
    },

    /** 表单重置方法 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.right-card {
  margin-left: var(--container-pd);
}
</style>
