<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="饲养阶段" prop="feedStage">
        <el-input v-model="queryParams.feedStage" placeholder="请输入饲养阶段" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="批号" prop="batchId">
        <el-input v-model="queryParams.batchId" placeholder="请输入批号" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @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="Plus" @click="handleAddFormulatemplate"
          v-hasPermi="['feed:FormulaManagement:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['feed:FormulaManagement:edit']" v-show="false">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['feed:FormulaManagement:remove']" v-show="false">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['feed:FormulaManagement:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="FormulaManagementList">
      <!-- 表中表展示子配方 -->
      <el-table-column type="expand" @expand-change="handleExpandChange">
        <template #default="props">
          <el-table :data="props.row.subFormulaList" style="width: 100%">
            <el-table-column label="批号" align="center" prop="batchId" />
            <el-table-column label="饲养阶段" align="center" prop="feedStage" />
            <el-table-column label="开始使用时间" align="center" prop="useStartDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.useStartDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束使用时间" align="center" prop="useEndDate" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.useEndDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="使用状态" align="center" prop="useState">
              <template #default="scope">
                <dict-tag :options="pres_status" :value="scope.row.useState" />
              </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 #default="scope">
                <el-button link type="primary" icon="View" @click="handleView(scope.row)">详情</el-button>
                <el-button link type="primary" icon="Edit" @click="handleFormulaDetailUpdate(scope.row)"
                  v-hasPermi="['feed:FormulaManagement:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleFormulaDelete(scope.row)"
                  v-hasPermi="['feed:FormulaManagement:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="配方编号" align="center" prop="formulaId" />
      <el-table-column label="饲养阶段" align="center" prop="feedStage" />
      <el-table-column label="使用状态" align="center" prop="useState">
        <template #default="scope">
          <dict-tag :options="pres_status" :value="scope.row.useState" />
        </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 #default="scope">
          <el-button link type="primary" icon="Plus" @click="handleAddSgFormulaList(scope.row)"
            v-hasPermi="['feed:FormulaManagement:add']">新增</el-button>
          <el-button link type="primary" icon="Edit" @click="handleFormulaTemplateUpdate(scope.row)"
            v-hasPermi="['feed:FormulaManagement:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleFormulaDelete(scope.row)"
            v-hasPermi="['feed:FormulaManagement:remove']">删除</el-button>
        </template>
      </el-table-column>

    </el-table>



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

    <!-- 添加或修改配方管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="FormulaManagementRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="饲养阶段" prop="feedStage">
          <el-input v-model="form.feedStage" placeholder="请输入饲养阶段" />
        </el-form-item>
        <el-form-item label="开始使用时间" prop="useStartDate">
          <el-date-picker clearable v-model="form.useStartDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束使用时间" prop="useEndDate">
          <el-date-picker clearable v-model="form.useEndDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束使用时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 弹框：详情/修改 -->
    <el-dialog :title="title" v-model="formulaListOpen" width="60%" append-to-body s>
      <!-- 详情页：只读展示 -->
      <div v-if="isView" style="padding-bottom:20px ;">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="配方批号">{{ showFormulaManagementList.batchId }}</el-descriptions-item>
          <el-descriptions-item label="饲养阶段">{{ showFormulaManagementList.feedStage }}</el-descriptions-item>
          <el-descriptions-item label="开始使用时间">
            <span>{{ parseTime(showFormulaManagementList.useStartDate, '{y}-{m}-{d}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="结束使用时间">
            <span>{{ parseTime(showFormulaManagementList.useEndDate, '{y}-{m}-{d}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="使用状态">
            <dict-tag :options="pres_status" :value="showFormulaManagementList.useState" />
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ showFormulaManagementList.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left">配方列表</el-divider>

        <el-table :data="showFormulaManagementList.sgFormulaList" stripe border style="width: 100%" max-height="300">
          <el-table-column label="序号" type="index" width="60" align="center" />
          <el-table-column label="原料编号" prop="materialId" align="center" />
          <el-table-column label="原料" align="center">
            <el-table-column label="名称" prop="materialName" align="center"/>
            <el-table-column label="类型" align="center" prop="isGranular">
              <template #default="scope">
                <dict-tag :options="material_type" :value="scope.row.isGranular" />
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="比例" align="center" prop="ratio" sortable/>
          <el-table-column label="类型" prop="isSupplement" align="center">
            <template #default="scope">
              <dict-tag :options="materialType" :value="scope.row.isSupplement" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 修改页：可编辑表单 -->
      <div v-else>
        <el-form ref="FormulaManagementRef" :model="showFormulaManagementList" :rules="rules" label-width="100px">
          <el-row :gutter="20">
            <el-col :span="12" v-if="!isView">
              <el-form-item label="配方编号" prop="formulaId">
                <el-input v-model="showFormulaManagementList.formulaId" placeholder="请输入配方编号"
                  :disabled="!FormulaIdEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="批号" prop="batchId">
                <el-input v-model="showFormulaManagementList.batchId" placeholder="请输入配方批号"
                  :disabled="!BatchIdEditable" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="饲养阶段" prop="feedStage">
                <el-input v-model="showFormulaManagementList.feedStage" placeholder="请输入饲养阶段" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始使用时间" prop="useStartDate">
                <el-date-picker clearable v-model="showFormulaManagementList.useStartDate" type="date"
                  value-format="YYYY-MM-DD" placeholder="请选择开始使用时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束使用时间" prop="useEndDate">
                <el-date-picker clearable v-model="showFormulaManagementList.useEndDate" type="date"
                  value-format="YYYY-MM-DD" placeholder="请选择结束使用时间">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="使用状态" prop="useState">
                <el-select v-model="showFormulaManagementList.useState" placeholder="请选择使用状态">
                  <el-option v-for="item in useStaus" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input type="textarea" :rows="2" v-model="showFormulaManagementList.remark" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">配方详情</el-divider>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="Plus" @click="handleAddSgFormulaListDetail()">添加</el-button>
            </el-col>

          </el-row>

          <el-table :data="showFormulaManagementList.sgFormulaList" :rules="rules"
            :row-class-name="rowSgFormulaListDetailIndex" @selection-change="handleSgFormulaListDetailSelectionChange"
            ref="swPresDetail" border stripe>
            <el-table-column label="序号" align="center" prop="index" width="60" />
            <el-table-column label="原料" prop="materialId" align="center">
              <el-table-column label="名称" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.materialId" filterable placeholder="请选择原料" style="width: 100%"
                    @change="handleMaterialChange(scope.row, $event)">
                    <el-option-group v-for="group in groupedMaterials" :key="group.label" :label="group.label">
                      <el-option v-for="item in group.options" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-option-group>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="类型" align="center" prop="isGranular">
                <template #default="scope">
                  <dict-tag :options="material_type" :value="scope.row.isGranular" />
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="比例" prop="dosage" align="center">
              <template #default="scope">
                <el-input-number v-model="scope.row.ratio" placeholder="请输入比例" :min="0" :precision="1"
                  controls-position="right" />
              </template>
            </el-table-column>
            <el-table-column label="类型" prop="isSupplement" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.isSupplement" placeholder="请选择类型">
                  <el-option v-for="item in materialType" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Delete" @click="deleteFormulaListDetail(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>

      <!-- 底部按钮：仅修改页显示 -->
      <template #footer v-if="!isView">
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitFormulaListForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listFormulaManagement, getFormulaManagement, delFormulaManagement, addFormulaManagement, updateFormulaManagement } from "@/api/feed/FormulaManagement"
import { ref, reactive, toRefs, getCurrentInstance } from 'vue'
import { listFormulaList, getFormulaList, delFormulaList, addFormulaList, updateFormulaList } from "@/api/feed/FormulaList"
import { listMaterial } from "@/api/feed/Material"
import { fa } from "element-plus/es/locales.mjs"
const { proxy } = getCurrentInstance()
const { pres_status } = proxy.useDict('pres_status')
// Data and refs
const FormulaManagementList = ref([])
const showFormulaManagementList = ref([])
const FormulaDetailList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const expandedRows = ref([])  // Track expanded rows
const isView = ref(false)

/**
 * add : 添加配方
 * update : 修改配方
 */
const operationType = ref("") // 操作类型：add 或 update
// 控制批号是否可编辑
const BatchIdEditable = ref(false)
const FormulaIdEditable = ref(false)
// 原料下拉列表
const materials = ref([])
// 原料类型
const materialType = [
  { value: '1', label: '补饲原料' },
  { value: '0', label: '原料' }
]
// 原料类型字典
const { material_type } = proxy.useDict('material_type')
console.log("material_type: ", material_type);
const useStaus = [
  { value: '1', label: '启用' },
  { value: '0', label: '停用' }
]
const checkedSwPresDetail = ref([])       // 子表选中的行序号数组

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    feedStage: null,
    batchId: null,
  },
  rules: {
    formulaId: [
      { required: true, message: "配方编号不能为空", trigger: "blur" }
    ],
    feedStage: [
      { required: true, message: "饲养阶段不能为空", trigger: "blur" }
    ],
    ratio: [
      { required: true, message: "比例不能为空", trigger: "blur" },
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)


const formulaForm = ref({
  materialId: '',
  materialName: '',
  ratio: '',
  isGranular: false
})
const formulaListOpen = ref(false)
/** 查询配方管理列表 */
function getList() {
  loading.value = true
  listFormulaManagement(queryParams.value).then(response => {
    FormulaManagementList.value = response.rows
    total.value = response.total
    loading.value = false
    console.log("配方管理列表数据：", FormulaManagementList.value)
  })
}

// 处理展开行的变化
function handleExpandChange(row, expandedRows) {
  // 收起其他行
  expandedRows.forEach(r => {
    if (r !== row) {
      mainTable.value.toggleRowExpansion(r, false)
    }
  })

  // 如果是展开状态，刷新子表数据
  const isExpanded = expandedRows.includes(row)
  if (isExpanded) {
    loading.value = true
    getList();
  }
}

// 取消按钮
function cancel() {
  open.value = false
  formulaListOpen.value = false
  formulaFormReset()
  reset()
}

// 表单重置
function reset() {
  form.value = {
    formulaId: null,
    feedStage: null,
    batchId: null,
    useStartDate: null,
    useEndDate: null,
    useState: null,
    remark: null
  }
  proxy.resetForm("FormulaManagementRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

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

/** 新增按钮操作 */
function handleAddFormulatemplate() {
  formulaFormReset()
  reset()
  operationType.value = "add"
  // 模板禁用批号编辑
  BatchIdEditable.value = false
  // 添加模板时配方编号可编辑
  FormulaIdEditable.value = true
  isView.value = false
  // 初始化表单
  showFormulaManagementList.value = {
    formulaId: null,
    // 模板批号为 0
    batchId: "0",
    feedStage: null,
    useStartDate: null,
    useEndDate: null,
    useState: '1', // 默认启用
    remark: null,
    sgFormulaList: [{
      materialId: null,
      materialName: null,
      ratio: null,
      isGranular: "0",
      isSupplement: "0"
    }]
  }
  formulaListOpen.value = true
  title.value = "添加配方管理模板"
}

/** 修改按钮操作 */
function handleFormulaTemplateUpdate(row) {
  reset()
  operationType.value = "update"
  const _id = row.formulaId || ids.value
  BatchIdEditable.value = false // 修改时批号不可编辑
  FormulaIdEditable.value = false // 修改时配方编号不可编辑
  const batchId = row.batchId
  const queryParams = {
    formulaId: _id,
    batchId: batchId,
    queryType: "query"
  }
  listFormulaManagement(queryParams).then(response => {
    if (response.rows && response.rows.length > 0) {
      showFormulaManagementList.value = response.rows[0] // 取第一条记录
    } else {
      showFormulaManagementList.value = {}
    }
    formulaListOpen.value = true
    title.value = "修改处方"
    isView.value = false
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["FormulaManagementRef"].validate(valid => {
    if (valid) {
      if (form.value.formulaId != null) {
        updateFormulaManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addFormulaManagement(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _formulaIds = row.formulaId || ids.value
  proxy.$modal.confirm('是否确认删除配方管理编号为"' + _formulaIds + '"的数据项？').then(function () {
    return delFormulaManagement(_formulaIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** ================= 配方列表操作 ================= */
function handleAddSgFormulaList(row) {
  formulaFormReset()
  reset()
  operationType.value = "add"
  BatchIdEditable.value = true
  FormulaIdEditable.value = false
  isView.value = false
  console.log(row.sgFormulaList)
  // 初始化表单
  showFormulaManagementList.value = {
    formulaId: row.formulaId || null,
    batchId: null,
    feedStage: null,
    useStartDate: null,
    useEndDate: null,
    useState: '1', // 默认启用
    remark: null,
    sgFormulaList: row.sgFormulaList || [{
      materialId: null,
      materialName: null,
      ratio: null,
      isGranular: "0",
      isSupplement: "0"
    }]
  }
  formulaListOpen.value = true
  title.value = "添加配方"
}

/** 修改按钮操作 */
function handleFormulaUpdate(row) {
  formulaFormReset()
  const _code = row.code || ids.value
  getFormulaList(_code).then(response => {
    formulaForm.value = response.data
    if (formulaForm.value.isGranular === "1") {
      formulaForm.value.isGranular = true
    } else {
      formulaForm.value.isGranular = false
    }
    console.log("formulaForm: ", formulaForm.value)
    formulaListOpen.value = true
    FormulaIdEditable.value = false
    title.value = "修改配方列表"
  })
}

/** 删除按钮操作 */
function handleFormulaDelete(row) {
  const _codes = row.formulaId + "/" + row.batchId
  proxy.$modal.confirm('是否确认删除配方列表编号为"' + _codes + '"的数据项？').then(function () {
    return delFormulaManagement(_codes)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 提交按钮 */
function submitFormulaListForm() {
  proxy.$refs["FormulaManagementRef"].validate(valid => {
    if (valid) {
      if (showFormulaManagementList.value.formulaId != null && operationType.value === "update") {
        updateFormulaManagement(showFormulaManagementList.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          formulaListOpen.value = false
          getList()
        })
      } else if (operationType.value === "add" && showFormulaManagementList.value.formulaId != null && showFormulaManagementList.value.batchId != null) {
        addFormulaManagement(showFormulaManagementList.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          formulaListOpen.value = false
          getList()
        })
      }
    }
  })
}

// 原料下拉选择变化时，更新对应的原料名称
function handleMaterialChange(row, selectedValue) {
  const selectedItem = this.materials.find(item => item.value === selectedValue);
  if (selectedItem) {
    // materialName 也在 row 中
    row.materialName = selectedItem.label;
    row.isGranular = selectedItem.isGranular; // 更新 isGranular
    row.isSupplement = selectedItem.isSupplement; // 更新 isSupplement
  }
}

/**
 * 查看详情
 * 根据 id 拉取单条记录及子表数据，弹窗只读展示
 */
function handleView(row) {
  reset()
  const _id = row.formulaId || ids.value
  const batchId = row.batchId
  const queryParams = {
    formulaId: _id,
    batchId: batchId,
    queryType: "query"
  }
  listFormulaManagement(queryParams).then(response => {
    if (response.rows && response.rows.length > 0) {
      showFormulaManagementList.value = response.rows[0] // 取第一条记录
    } else {
      showFormulaManagementList.value = {}
    }
    title.value = "配方详情"
    isView.value = true
    formulaListOpen.value = true
    console.log("handleView showFormulaManagementList: ", showFormulaManagementList.value);
    console.log("handleView response: ", response);
  })
}

/**
 * 修改按钮
 * 与查看详情共用接口，但弹窗可编辑
 */
function handleFormulaDetailUpdate(row) {
  reset()
  operationType.value = "update"
  const _id = row.formulaId || ids.value
  BatchIdEditable.value = false // 修改时批号不可编辑
  const batchId = row.batchId
  const queryParams = {
    formulaId: _id,
    batchId: batchId,
    queryType: "query"
  }
  listFormulaManagement(queryParams).then(response => {
    if (response.rows && response.rows.length > 0) {
      showFormulaManagementList.value = response.rows[0] // 取第一条记录
    } else {
      showFormulaManagementList.value = {}
    }
    formulaListOpen.value = true
    title.value = "修改配方"
    isView.value = false
  })
}

// 添加项
function handleAddSgFormulaListDetail() {
  showFormulaManagementList.value.sgFormulaList.push({
    materialId: null,
    materialName: null,
    ratio: null,
    isGranular: "0",
    isSupplement: "0"
  })
}
// 删除项
function deleteFormulaListDetail(row) {
  const index = showFormulaManagementList.value.sgFormulaList.findIndex(item => item.index === row.index)
  if (index !== -1) {
    showFormulaManagementList.value.sgFormulaList.splice(index, 1)
  }
}
// 表单重置
function formulaFormReset() {
  form.value = {
    code: null,
    formulaId: null,
    materialId: null,
    materialName: null,
    ratio: null,
    isGranular: null,
    isSupplement: null
  }
  proxy.resetForm("FormulaListRef")
}

// 原料列表查询参数
const materialQueryParams = ref({
  materialId: null,
  materialName: null,
  isGranular: null
})
function getMaterials() {
  listMaterial(materialQueryParams).then(response => {
    console.log("获取原料列表：", response)
    materials.value = response.rows.map(item => ({
      value: item.materialId,
      label: item.materialName,
      isGranular: item.isGranular,
      isSupplement: "0" // 默认补饲原料为 0
    }))
    console.log("原料列表：", materials.value)
  })
}

/** ================== 分组下拉列表部分 ======================== */
const groupedMaterials = ref([])  // 存储分组后的原料数据

// 从后端获取数据并按isGranular分组
function getGroupMaterials() {
  listMaterial(materialQueryParams).then(response => {
    console.log("获取原料列表：", response)

    // 根据material_type分组数据
    const groups = material_type.value.map(type => ({
      label: type.label,
      options: []
    }))

    // 遍历原料数据，根据isGranular字段分组
    response.rows.forEach(item => {
      const group = groups.find(group => group.label === material_type.value.find(type => type.value === item.isGranular).label)
      group.options.push({
        value: item.materialId,
        label: item.materialName
      })
    })

    // 将分组后的数据赋值给groupedMaterials
    groupedMaterials.value = groups
    console.log("分组后的原料列表：", groupedMaterials.value)
  })
}

/**
 * 子表多选回调
 * 记录被选中的行序号数组
 */
function handleSgFormulaListDetailSelectionChange(selection) {
  checkedSwPresDetail.value = selection.map(item => item.index)
}
/**
 * 子表行序号计算
 * 通过 el-table 的 row-class-name 钩子给每一行写入 index（从 1 开始）
 */
function rowSgFormulaListDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** ================================= */
/** 导出按钮操作 */
function handleExport() {
  proxy.download('feed/FormulaManagement/export', {
    ...queryParams.value
  }, `FormulaManagement_${new Date().getTime()}.xlsx`)
}

// 初始化加载数据
getList()
// 加载原料列表
getMaterials()
// 加载分组原料列表
getGroupMaterials()
</script>
