<template>
  <div>
    <el-dialog v-model="state.showDialog" destroy-on-close :title="title" draggable :close-on-click-modal="false"
      :close-on-press-escape="false" width="75%" append-to-body>
      <el-form :model="form" ref="formRef" size="default" label-width="130px">
        <el-tabs @tab-click="handleTabClick" v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <div class="form-section">
              <el-row :gutter="25">
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="模板名称" prop="cultureProtocolName"
                    :rules="[{ required: true, message: '请输入模板名称', trigger: ['blur', 'change'] }]">
                    <el-input v-model="form.cultureProtocolName" clearable placeholder="请输入模板名称" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="反应器" prop="equReactorId"
                    :rules="[{ required: true, message: '请选择反应器', trigger: ['blur', 'change'] }]">
                    <el-select v-model="form.equReactorId" filterable placeholder="请选择反应器" style="width: 100%">
                      <el-option v-for="item in state.reactorOptions" :key="item.id"
                        :label="item.name + ' (' + item.spec + ')'" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="培养天数" prop="days"
                    :rules="[{ required: true, message: '请输入培养天数', trigger: ['blur', 'change'] }]">
                    <el-input-number v-model="form.days" :min="1" style="width: 100%" placeholder="请输入培养天数" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                  <el-form-item label="补糖时计算补料引起的糖浓度变化">
                    <el-switch v-model="form.glucoseFeedingVerification" active-text="是" inactive-text="否" />
                  </el-form-item>
                </el-col>
                <el-col :xs="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-tab-pane>

          <!-- 固定补料泵 -->
          <el-tab-pane label="固定补料泵" name="pumps">
            <div class="form-section">
              <el-table :data="form.fixedFeedingPumps" border style="width: 100%">
                <el-table-column label="序号" prop="feedingPumpNo" width="70">
                  <template #default="scope">
                    <el-input v-model="scope.row.feedingPumpNo" disabled />
                  </template>
                </el-table-column>

                <el-table-column label="泵名称" prop="feedingPumpName" width="150">
                  <template #default="scope">
                    <el-input v-model="scope.row.feedingPumpName" disabled />
                  </template>
                </el-table-column>
                <el-table-column
                  v-if="state.form.equReactorId && state.reactorOptions.find(r => r.id === state.form.equReactorId)?.needExternalPump === true"
                  label="外置泵" prop="equPumpId" min-width="100">
                  <template #default="scope">
                    <el-select v-model="scope.row.equPumpId" placeholder="请选择外置泵" style="width: 100%" filterable
                      @change="() => handlePumpChange(scope.$index)">
                      <el-option v-for="item in state.pumpOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="量程(g/min)" prop="pumpSpeed" width="120">
                  <template #default="scope">
                    <el-input v-model="scope.row.pumpSpeed" disabled />
                  </template>
                </el-table-column>

                <el-table-column label="补料培养基" prop="itemDefFeedingMediumID" min-width="200">
                  <template #default="scope">
                    <el-select v-model="scope.row.itemDefFeedingMediumID" placeholder="请选择补料培养基" filterable
                      @change="() => handleMediumChange(scope.$index)" style="width: 100%">
                      <el-option v-for="item in state.mediumOptions" :key="item.id"
                        :label="item.name + ' (' + item.glucoseConc + 'g/L)' + (item.isGlucose ? ' (糖补料)' : '')"
                        :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="耗材" prop="itemDefBagID" min-width="200">
                  <template #default="scope">
                    <el-select v-model="scope.row.itemDefBagID" placeholder="请选择耗材" style="width: 100%">
                      <el-option v-for="item in state.bagOptions" :key="item.id"
                        :label="item.name + ' (下限体积: ' + item.lowerLimitVolume + 'g)'" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>

                <el-table-column label="泵速策略" prop="configId" min-width="200">
                  <template #default="scope">
                    <el-select v-model="scope.row.configId" placeholder="请选择泵速策略" style="width: 100%">
                      <el-option v-for="item in state.configOptions" :key="item.id"
                        :label="item.name + (item.isTwo === 1 ? ' (二段式)' : ' (三段式)')" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>

              </el-table>
            </div>
          </el-tab-pane>

          <!-- 补料任务 -->
          <el-tab-pane label="补料任务" name="tasks">
            <div class="form-section">
              <div v-for="(task, index) in form.feedingTasks" :key="index" class="task-item">
                <el-row :gutter="25">
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '补料泵编号' : ''"
                      :prop="'feedingTasks.' + index + '.feedingPumpNo'">
                      <el-input-number v-model="task.feedingPumpNo" :min="1" style="width: 100%" placeholder="泵编号" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '培养天数' : ''" :prop="'feedingTasks.' + index + '.day'">
                      <el-input-number v-model="task.day" :min="1" style="width: 100%" placeholder="天数" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '补料时间' : ''" :prop="'feedingTasks.' + index + '.feedingTime'">
                      <el-time-picker v-model="task.feedingTime" format="HH:mm" style="width: 100%"
                        placeholder="补料时间" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '补料体积' : ''" :prop="'feedingTasks.' + index + '.feedingVolume'">
                      <el-input-number v-model="task.feedingVolume" :min="0" :precision="2" style="width: 100%"
                        placeholder="补料体积" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-button type="danger" icon="ele-Delete" circle @click="removeTask(index)"
                  v-if="form.feedingTasks.length > 1" />
              </div>
              <el-button type="primary" icon="ele-Plus" @click="addTask">添加任务</el-button>
            </div>
          </el-tab-pane>

          <!-- 自动葡萄糖补料规则 -->
          <el-tab-pane label="自动葡萄糖补料规则" name="glucose">
            <div class="form-section">
              <div v-for="(rule, index) in form.autoGlucoseFeedingRules" :key="index" class="rule-item">
                <el-row :gutter="25">
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '培养开始天数' : ''"
                      :prop="'autoGlucoseFeedingRules.' + index + '.cultureDayStarting'">
                      <el-input-number v-model="rule.cultureDayStarting" :min="0" style="width: 100%"
                        placeholder="开始天数" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '培养结束天数' : ''"
                      :prop="'autoGlucoseFeedingRules.' + index + '.cultureDayEnding'">
                      <el-input-number v-model="rule.cultureDayEnding" :min="0" style="width: 100%"
                        placeholder="结束天数" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '下限值' : ''"
                      :prop="'autoGlucoseFeedingRules.' + index + '.lowerLimit'">
                      <el-input-number v-model="rule.lowerLimit" :min="0" :precision="2" style="width: 100%"
                        placeholder="下限值" />
                    </el-form-item>
                  </el-col>
                  <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
                    <el-form-item :label="index === 0 ? '补料目标值' : ''"
                      :prop="'autoGlucoseFeedingRules.' + index + '.feedingTo'">
                      <el-input-number v-model="rule.feedingTo" :min="0" :precision="2" style="width: 100%"
                        placeholder="目标值" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-button type="danger" icon="ele-Delete" circle @click="removeRule(index)"
                  v-if="form.autoGlucoseFeedingRules.length > 1" />
              </div>
              <el-button type="primary" icon="ele-Plus" @click="addRule">添加规则</el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button type="primary" @click="onSure" size="default" :loading="state.sureLoading">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="admin/culture-protocol/form">
import { reactive, toRefs, ref, getCurrentInstance, onMounted, watch, computed, nextTick } from 'vue'
import { CultureProtocolApi } from '/@/api/admin/CultureProtocolApi'
import { ReactorApi } from '/@/api/admin/ReactorApi'
import { UspscaleApi } from '/@/api/admin/UspscaleApi'
import { ItemDefFeedingMediumApi } from '/@/api/admin/item-def-feeding-medium'
import { ItemDefBagApi } from '/@/api/admin/item-def-bag'
import { PumpApi } from '/@/api/admin/PumpApi'
import { UspFeedingConfigApi } from '/@/api/admin/UspFeedingConfigApi'
import type { CultureProtocolDto } from '/@/api/types/cultureprotocol'
import { ElMessageBox, ElMessage } from 'element-plus'
const { proxy } = getCurrentInstance() as any

defineProps({
  title: {
    type: String,
    default: '',
  },
})

const emit = defineEmits<{
  (e: 'ok'): void
}>()

const formRef = ref()
const state = reactive({
  showDialog: false,
  sureLoading: false,
  form: {
    id: 0,
    cultureProtocolName: '',
    equReactorId: undefined,
    equFeedingScaleId: undefined,
    days: 0,
    initialWorkingVolume: 0,
    initialWorkingMediumId: 0,
    transferCellVolume: 0,
    transferCellTypeId: 0,
    glucoseFeedingVerification: true,
    enabled: true,
    remark: '',
    autoGlucoseFeedingRules: [],
    feedingTasks: [],
    fixedFeedingPumps: []
  } as CultureProtocolDto,
  reactorOptions: [] as Array<{ id: number; name: string; needExternalPump: boolean; spec: string; pumpSpeed1: number; pumpSpeed2: number; pumpSpeed3: number; pumpSpeed4: number; pumpSpeed5: number; pumpSpeed6: number; pumpSpeed7: number; pumpSpeed8: number; pump1ConfigId: number; pump2ConfigId: number; pump3ConfigId: number; pump4ConfigId: number; pump5ConfigId: number; pump6ConfigId: number; pump7ConfigId: number; pump8ConfigId: number }>,
  scaleOptions: [] as Array<{ id: number; name: string }>,
  mediumOptions: [] as Array<{ id: number; name: string; glucoseConc: number; isGlucose: boolean; }>,
  bagOptions: [] as Array<{ id: number; name: string; lowerLimitVolume: number; }>,
  pumpOptions: [] as Array<{ id: number; name: string }>,
  cellTypeOptions: [],
  configOptions: [] as Array<{ id: number; name: string; isTwo: number; }>,
  selectedReactor: null as any,
})

const { form } = toRefs(state)
const activeTab = ref('basic')
const lastActiveTab = ref('basic')

// 监听反应器选择变化
watch(() => state.form.equReactorId, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    // 获取选中反应器的信息
    state.selectedReactor = state.reactorOptions.find(r => r.id === newVal)
    if (state.selectedReactor) {
      state.form.fixedFeedingPumps.forEach(pump => {
        pump.feedingPumpName = state.selectedReactor.name + ' - PUMP' + pump.feedingPumpNo

        // 设置泵速和配置ID
        if (pump.feedingPumpNo == 1) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed1
          pump.configId = state.selectedReactor.pump1ConfigId
        } else if (pump.feedingPumpNo == 2) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed2
          pump.configId = state.selectedReactor.pump2ConfigId
        } else if (pump.feedingPumpNo == 3) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed3
          pump.configId = state.selectedReactor.pump3ConfigId
        } else if (pump.feedingPumpNo == 4) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed4
          pump.configId = state.selectedReactor.pump4ConfigId
        } else if (pump.feedingPumpNo == 5) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed5
          pump.configId = state.selectedReactor.pump5ConfigId
        } else if (pump.feedingPumpNo == 6) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed6
          pump.configId = state.selectedReactor.pump6ConfigId
        } else if (pump.feedingPumpNo == 7) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed7
          pump.configId = state.selectedReactor.pump7ConfigId
        } else if (pump.feedingPumpNo == 8) {
          pump.pumpSpeed = state.selectedReactor.pumpSpeed8
          pump.configId = state.selectedReactor.pump8ConfigId
        }

        // 如果不是外置泵，清空外置泵ID
        if (!state.selectedReactor.needExternalPump) {
          pump.equPumpId = undefined
        }
      })

      // 如果是外置泵，获取泵列表
      if (state.selectedReactor.needExternalPump) {
        getPumpOptions()
      }
    }
  }
}, { immediate: true })

onMounted(() => {
  getReactorOptions()
  getScaleOptions()
  getMediumOptions()
  getBagOptions()
  getConfigOptions()
})

// 打开对话框
const open = async (row: any = {}, isCopy = false) => {
  proxy.$modal.loading()

  if (row.id > 0) {
    const res = await new CultureProtocolApi().get({ id: row.id }, { loading: true })
    if (res?.success) {
      let formData = res.data as CultureProtocolDto
      if (isCopy) {
        formData.id = 0
        formData.cultureProtocolName = formData.cultureProtocolName + ' - 副本'
      }
      state.form = formData
    }
  } else {
    state.form = {
      id: 0,
      cultureProtocolName: '',
      equReactorId: undefined,
      equFeedingScaleId: undefined,
      days: 0,
      initialWorkingVolume: 0,
      initialWorkingMediumId: 0,
      transferCellVolume: 0,
      transferCellTypeId: 0,
      glucoseFeedingVerification: true,
      remark: '',
      autoGlucoseFeedingRules: [],
      feedingTasks: [],
      fixedFeedingPumps: defaultPumps
    }
  }

  state.showDialog = true
  proxy.$modal.closeLoading()
}

const defaultPumps = [
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 1, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 2, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 3, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 4, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 5, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 6, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 7, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', cultureProtocolId: undefined, configId: undefined, feedingPumpNo: 8, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false }
]

// 添加规则
const addRule = () => {
  state.form.autoGlucoseFeedingRules.push({
    id: 0,
    cultureProtocolId: 0,
    cultureDayStarting: 0,
    cultureDayEnding: 0,
    lowerLimit: 0,
    feedingTo: 0,
    lowerLimitOperator: '',
    calculationMode: 0
  })
}

// 移除规则
const removeRule = (index: number) => {
  state.form.autoGlucoseFeedingRules.splice(index, 1)
}

// 添加任务
const addTask = () => {
  state.form.feedingTasks.push({
    id: 0,
    cultureProtocolId: 0,
    feedingPumpNo: 0,
    day: 0,
    feedingTime: '',
    feedingType: 0,
    feedingVolumePercent: 0,
    feedingVolume: 0
  })
}

// 移除任务
const removeTask = (index: number) => {
  state.form.feedingTasks.splice(index, 1)
}

const handleTabClick = async (tab: any, event: any) => {
  if (lastActiveTab.value == 'pumps') {

    // 检查泵选项是否选择
    if (!checkPumps()) {
      await nextTick()
      activeTab.value = lastActiveTab.value
      return
    }

    // 检查液体选择是否正确

    lastActiveTab.value = tab.paneName

  }
  else {
    lastActiveTab.value = tab.paneName
  }
}

const checkPumps = () => {
  let valid = true
  state.form.fixedFeedingPumps.forEach(pump => {
    if (pump.equPumpId != undefined || pump.itemDefBagID != undefined || pump.itemDefFeedingMediumID != undefined) {
      let msg = ''
      if (pump.equPumpId == undefined && state.selectedReactor?.needExternalPump) {
        msg += '外置泵 '
      }
      if (pump.itemDefBagID == undefined) {
        msg += '耗材 '
      }
      if (pump.itemDefFeedingMediumID == undefined) {
        msg += '补料培养基 '
      }
      if (pump.configId == undefined) {
        msg += '泵速策略 '
      }

      if (msg != '') {
        msg = pump.feedingPumpName + ': 请选择' + msg
        valid = false
        proxy.$modal.msgError(msg)
      }
    }
  })

  return valid
}

// 提交表单
const onSure = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      state.sureLoading = true
      try {
        const api = new CultureProtocolApi()
        const res = state.form.id
          ? await api.update(state.form)
          : await api.add(state.form)
        if (res.success) {
          proxy.$modal.msgSuccess(state.form.id ? '修改成功' : '新增成功')
          state.showDialog = false
          emit('ok')
        }
      } catch (error) {
        console.error(state.form.id ? '修改失败:' : '新增失败:', error)
      } finally {
        state.sureLoading = false
      }
    }
  })
}

// 取消按钮
const onCancel = () => {
  state.showDialog = false
  reset()
}

// 重置表单
const reset = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  state.form = {
    id: 0,
    cultureProtocolName: '',
    equReactorId: undefined,
    equFeedingScaleId: undefined,
    days: 0,
    initialWorkingVolume: 0,
    initialWorkingMediumId: 0,
    transferCellVolume: 0,
    transferCellTypeId: 0,
    glucoseFeedingVerification: true,
    remark: '',
    autoGlucoseFeedingRules: [],
    feedingTasks: [],
    fixedFeedingPumps: defaultPumps
  }
}

const getReactorOptions = async () => {
  try {
    const res = await new ReactorApi().getList()

    if (res?.success) {
      state.reactorOptions = res.data?.map(item => ({
        id: item.id ?? 0,
        name: item.productID ?? '',
        needExternalPump: item.isExternalPump === true,
        spec: item.specification ?? '',
        pumpSpeed1: item.pump1Speed ?? 0,
        pumpSpeed2: item.pump2Speed ?? 0,
        pumpSpeed3: item.pump3Speed ?? 0,
        pumpSpeed4: item.pump4Speed ?? 0,
        pumpSpeed5: item.pump5Speed ?? 0,
        pumpSpeed6: item.pump6Speed ?? 0,
        pumpSpeed7: item.pump7Speed ?? 0,
        pumpSpeed8: item.pump8Speed ?? 0,
        pump1ConfigId: item.pump1ConfigId ?? 0,
        pump2ConfigId: item.pump2ConfigId ?? 0,
        pump3ConfigId: item.pump3ConfigId ?? 0,
        pump4ConfigId: item.pump4ConfigId ?? 0,
        pump5ConfigId: item.pump5ConfigId ?? 0,
        pump6ConfigId: item.pump6ConfigId ?? 0,
        pump7ConfigId: item.pump7ConfigId ?? 0,
        pump8ConfigId: item.pump8ConfigId ?? 0
      })) ?? []
    }
  } catch (error) {
    console.error('获取反应器列表失败:', error)
  }
}

const getScaleOptions = async () => {
  const res = await new UspscaleApi().getPage({
    currentPage: 1,
    pageSize: 10000
  })

  if (res?.success) {
    state.scaleOptions = res.data?.list?.filter(item => item.isFeedingScale === true).map(item => ({
      id: item.id ?? 0,
      name: item.deviceNo ?? ''
    })) ?? []
  }
}

// 获取补料培养基列表
const getMediumOptions = async () => {
  const res = await new ItemDefFeedingMediumApi().getPage({
    currentPage: 1,
    pageSize: 10000
  })

  if (res?.success) {
    state.mediumOptions = res.data?.list?.map(item => ({
      id: item.id ?? 0,
      name: item.mediumName ?? '',
      glucoseConc: item.glucoseConc ?? 0,
      isGlucose: item.isGlucose ?? false
    })) ?? []
  }
}

// 获取物料定义袋列表
const getBagOptions = async () => {
  const res = await new ItemDefBagApi().getPage({
    currentPage: 1,
    pageSize: 10000
  })

  if (res?.success) {
    state.bagOptions = res.data?.list?.map(item => ({
      id: item.id ?? 0,
      name: item.itemDescription ?? '',
      lowerLimitVolume: item.lowerLimitVolume ?? 0,
    })) ?? []
  }
}

const getPumpOptions = async () => {
  const res = await new PumpApi().getPage({
    currentPage: 1,
    pageSize: 10000,
    filter: {
      isAirPump: false
    }
  })
  if (res?.success) {
    state.pumpOptions = res.data?.list?.map((item: { id: number; deviceNo: string }) => ({
      id: item.id ?? 0,
      name: item.deviceNo ?? ''
    })) ?? []
  }
}

const getConfigOptions = async () => {
  const res = await new UspFeedingConfigApi().getPage({
    currentPage: 1,
    pageSize: 10000
  })

  if (res?.success) {
    state.configOptions = res.data?.list?.map((item) => ({
      id: item.id ?? 0,
      name: item.configName ?? '',
      isTwo: item.isTwoStep ?? 0
    })) ?? []
  }
}

// 处理泵选择变化
const handlePumpChange = async (index: number) => {
  const row = state.form.fixedFeedingPumps[index]
  if (!row) return

  const pumpId = row.equPumpId
  if (!pumpId) {
    // 如果清空选择，重置相关值
    row.pumpSpeed = 0
    row.configId = undefined
    return
  }

  try {
    // 获取选中的泵信息
    const res = await new PumpApi().get({ id: pumpId })
    if (res?.success && res.data) {
      // 更新泵速
      row.pumpSpeed = res.data.pumpSpeed || 0
      // 更新泵速策略
      row.configId = res.data.configId
    }
  } catch (error) {
    console.error('获取泵信息失败:', error)
    proxy.$modal.msgError('获取泵信息失败')
  }
}

const handleMediumChange = (index: number) => {
  const row = state.form.fixedFeedingPumps[index]
  if (!row) return

  row.isGlucose = state.mediumOptions.find(item => item.id == row.itemDefFeedingMediumID)?.isGlucose ?? false

  // 校验重复的糖补料
  if (row.isGlucose) {
    const glucose = state.form.fixedFeedingPumps.find(item => item.isGlucose == true && item.feedingPumpNo != row.feedingPumpNo)
    if (glucose) {
      ElMessageBox.confirm('糖补料不能重复，请检查', '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      }).then(() => {
        row.itemDefFeedingMediumID = undefined
        row.isGlucose = false
        return
      }).catch(() => {
        return
      })
    }
  }

  // 校验重复的补料培养基
  const medium = state.form.fixedFeedingPumps.find(item => item.itemDefFeedingMediumID == row.itemDefFeedingMediumID && item.feedingPumpNo != row.feedingPumpNo)
  if (medium) {
    proxy.$modal.msgWarning('补料培养基存在重复')
  }
}

defineExpose({
  open
})
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 20px;
    color: #303133;
  }
}

.rule-item,
.task-item,
.pump-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;

  .el-button {
    margin-left: 10px;
    margin-top: 32px;
  }
}

.dialog-footer {
  text-align: right;
}

.mt-2 {
  margin-top: 8px;
}
</style>