<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="protocolName"
                    :rules="[{ required: true, message: '请输入模板名称', trigger: ['blur', 'change'] }]">
                    <el-input v-model="form.protocolName" 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%" clearable
                      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="请选择补料培养基" clearable 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="请选择耗材" clearable 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="请选择泵速策略" clearable 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">
              <el-tabs v-model="feedingTaskActiveTab" type="border-card" class="feeding-task-tabs"
                v-if="feedingPumpTabs.length">
                <el-tab-pane v-for="pump in feedingPumpTabs" :key="pump.feedingPumpNo"
                  :label="`${pump.feedingPumpName}${pump.mediumName ? ' / ' + pump.mediumName : ''}`"
                  :name="String(pump.feedingPumpNo)">
                  <div style="text-align: left; margin-bottom: 6px;">
                    <el-button type="primary" icon="ele-Plus"
                      @click="addTaskByPump(pump.feedingPumpNo)">添加任务</el-button>
                  </div>
                  <el-table :data="getTasksByPumpNo(pump.feedingPumpNo)" border stripe size="small"
                    style="width: 100%; margin-bottom: 10px; border-radius: 8px; box-shadow: 0 2px 8px #e0e7ef; overflow: hidden; max-height: 400px;"
                    class="pretty-table" :height="400">
                    <el-table-column label="天数" prop="day" width="200" align="center" header-align="center">
                      <template #default="scope">
                        <div
                          style="display: flex; align-items: center; justify-content: center; gap: 6px; height: 32px;">
                          <el-input-number v-model="scope.row.day" :min="1" style="width: 190px; height: 28px;"
                            placeholder="天数" />
                          <el-button size="small" type="primary"
                            style="padding: 0 8px; height: 28px; display: flex; align-items: center; justify-content: center; font-size: 13px;"
                            @click="addDayCopy(scope.row, pump.feedingPumpNo)">
                            <el-icon style="margin-right:2px;">
                              <Plus />
                            </el-icon>
                          </el-button>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="补料时间" prop="feedingTime" min-width="100" align="center"
                      header-align="center">
                      <template #default="scope">
                        <div style="display: flex; align-items: center; gap: 4px; justify-content: center;">
                          <el-time-picker v-model="scope.row.feedingTime" format="HH:mm:ss" style="width: 100%;"
                            placeholder="补料时间" editable />
                          <el-tooltip content="将当前时间批量赋值给本泵所有任务" placement="top">
                            <el-button size="small"
                              style="padding: 0 6px; height: 28px; display: flex; align-items: center; justify-content: center;"
                              @click="pasteFeedingTime(scope.row, pump.feedingPumpNo)">
                              <el-icon>
                                <DocumentCopy />
                              </el-icon>
                            </el-button>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column label="补料类型" prop="feedingType" min-width="100">
                      <template #default="scope">
                        <div style="display: flex; align-items: center; gap: 4px; justify-content: center;">
                          <el-select v-model="scope.row.feedingType" placeholder="请选择补料类型" clearable style="width: 100%"
                            @change="handleFeedingTypeChange(scope.row, $event)">
                            <el-option v-for="item in state.feedingTypeOptions" :key="item.value" :label="item.label"
                              :value="item.value" />
                          </el-select>
                          <el-tooltip content="将当前类型批量赋值给本泵所有任务" placement="top">
                            <el-button size="small"
                              style="padding: 0 6px; height: 28px; display: flex; align-items: center;"
                              @click="pasteFeedingType(scope.row, pump.feedingPumpNo)">
                              <el-icon>
                                <DocumentCopy />
                              </el-icon>
                            </el-button>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-table-column>

                    <el-table-column label="补料体积" prop="feedingVolume" min-width="100" align="center"
                      header-align="center">
                      <template #default="scope">
                        <div style="display: flex; align-items: center; gap: 4px; justify-content: center;">
                          <el-input-number v-model="scope.row.feedingVolume" v-bind="getFeedingVolumeProps(scope.row)"
                            style="width: 100%" placeholder="补料体积" />
                          <el-tooltip content="将当前体积批量赋值给本泵所有任务" placement="top">
                            <el-button size="small"
                              style="padding: 0 6px; height: 28px; display: flex; align-items: center;"
                              @click="pasteFeedingVolume(scope.row, pump.feedingPumpNo)">
                              <el-icon>
                                <DocumentCopy />
                              </el-icon>
                            </el-button>
                          </el-tooltip>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="right" header-align="center">
                      <template #default="scope">
                        <el-button type="danger" icon="ele-Delete" circle size="small"
                          @click="removeTaskByPump(pump.feedingPumpNo, scope.$index)"
                          v-if="getTasksByPumpNo(pump.feedingPumpNo).length > 1" class="pretty-delete-btn" />
                      </template>
                    </el-table-column>
                    <template #empty>
                      <div style="text-align:center;color:#bbb;padding:20px 0;">暂无任务</div>
                    </template>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
              <div v-else style="color:#bbb;text-align:center;padding:30px 0;">请先在"固定补料泵"选择补料培养基</div>
            </div>
          </el-tab-pane>

          <!-- 自动葡萄糖补料规则 -->
          <el-tab-pane label="自动葡萄糖补料规则" name="glucose">
            <div class="form-section">
              <template v-if="hasGlucosePump">
                <div style="text-align: left; margin-bottom: 6px;">
                  <el-button type="primary" icon="ele-Plus" @click="addRule">添加规则</el-button>
                </div>
                <el-table :data="form.autoGlucoseFeedingRules" border stripe size="small"
                  style="width: 100%; margin-bottom: 10px; border-radius: 8px; box-shadow: 0 2px 8px #e0e7ef; overflow: hidden;"
                  class="pretty-table">
                  <el-table-column label="培养天数(开始)" prop="cultureDayStarting" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.cultureDayStarting" :min="0" style="width: 100%"
                        placeholder="开始天数" />
                    </template>
                  </el-table-column>
                  <el-table-column label="培养天数(结束)" prop="cultureDayEnding" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.cultureDayEnding" :min="0" style="width: 100%"
                        placeholder="结束天数" />
                    </template>
                  </el-table-column>
                  <el-table-column label="下限操作符" prop="lowerLimitOperator" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-select v-model="scope.row.lowerLimitOperator" placeholder="请选择下限操作符" clearable
                        style="width: 100%">
                        <el-option v-for="item in state.feedingOperatorOptions" :key="item.value" :label="item.label"
                          :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="糖下限 (g/L)" prop="lowerLimit" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.lowerLimit" :min="0" :precision="2" style="width: 100%"
                        placeholder="下限值" />
                    </template>
                  </el-table-column>
                  <el-table-column label="糖补料至 (g/L)" prop="feedingTo" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.feedingTo" :min="0" :precision="2" style="width: 100%"
                        placeholder="目标值" />
                    </template>
                  </el-table-column>
                  <el-table-column label="计算模式" prop="calculationMode" min-width="120" align="center"
                    header-align="center">
                    <template #default="scope">
                      <el-select v-model="scope.row.calculationMode" placeholder="请选择计算模式" clearable
                        style="width: 100%">
                        <el-option v-for="item in state.feedingCalculationModeOptions" :key="item.value"
                          :label="item.label" :value="item.value" />
                      </el-select>
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" width="80" align="center" header-align="center">
                    <template #default="scope">
                      <el-button type="danger" icon="ele-Delete" circle size="small" @click="removeRule(scope.$index)"
                        v-if="form.autoGlucoseFeedingRules.length > 1" class="pretty-delete-btn" />
                    </template>
                  </el-table-column>
                  <template #empty>
                    <div style="text-align:center;color:#bbb;padding:20px 0;">暂无规则</div>
                  </template>
                </el-table>
              </template>
              <div v-else style="color:#bbb;text-align:center;padding:30px 0;">请先在"固定补料泵"选择糖补料培养基</div>
            </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/protocol/form">
import { reactive, toRefs, ref, getCurrentInstance, onMounted, watch, computed, nextTick } from 'vue'
import { ProtocolApi } from '/@/api/admin/ProtocolApi'
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 { ProtocolDto } from '/@/api/types/protocolType'
import { ElMessageBox, ElMessage } from 'element-plus'
import { toOptionsByValue } from '/@/utils/enum'
import { EnumFeedingType, EnumFeedingOperator, EnumFeedingCalculationMode } from '/@/api/admin/enum-contracts'
import { DocumentCopy, Plus } from '@element-plus/icons-vue'
import { c } from 'vite/dist/node/moduleRunnerTransport.d-DJ_mE5sf'
import { setAddRoute } from '/@/router/backEnd'

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,
  id: 0,
  form: {
    id: 0,
    protocolName: '',
    equReactorId: undefined,
    equFeedingScaleId: undefined,
    days: 0,
    initialWorkingVolume: 0,
    initialWorkingMediumId: 0,
    transferCellVolume: 0,
    transferCellTypeId: 0,
    glucoseFeedingVerification: true,
    enabled: true,
    remark: '',
    autoGlucoseFeedingRules: [],
    feedingTasks: [],
    fixedFeedingPumps: []
  } as ProtocolDto,
  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; pumpSpeed: number; configId: number }>,
  cellTypeOptions: [],
  configOptions: [] as Array<{ id: number; name: string; isTwo: number; }>,
  selectedReactor: null as any,
  feedingTypeOptions: toOptionsByValue(EnumFeedingType),
  feedingOperatorOptions: toOptionsByValue(EnumFeedingOperator),
  feedingCalculationModeOptions: toOptionsByValue(EnumFeedingCalculationMode),
  Protocol: null as any
})

const { form } = toRefs(state)
const activeTab = ref('basic')
const lastActiveTab = ref('basic')
const feedingTaskActiveTab = ref('')
const defaultPumps = [
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 1, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 2, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 3, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 4, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 5, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 6, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 7, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false },
  { id: 0, feedingPumpName: '', ProtocolId: undefined, configId: undefined, feedingPumpNo: 8, itemDefBagID: undefined, itemDefFeedingMediumID: undefined, equPumpId: undefined, isGlucose: false }
]

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

// 打开对话框
const open = async (id?: number) => {
  state.id = id ?? 0
  // 重置对话框状态
  state.showDialog = true
  activeTab.value = 'basic'
  lastActiveTab.value = 'basic'
  feedingTaskActiveTab.value = 'fixed'
  
  // 重置表单数据
  reset()
  
  // 获取数据
  if (id) {
    const res = await new ProtocolApi().get({ id: id }, { loading: true })
    if (res?.success) {
      const formData = { ...res.data } as ProtocolDto
      formData.feedingTasks = formData.feedingTasks || []
      formData.autoGlucoseFeedingRules = formData.autoGlucoseFeedingRules || []
      formData.fixedFeedingPumps = formData.fixedFeedingPumps || []

      // 推荐用 Object.assign 保持响应式
      Object.assign(state.form, formData)
    } else {
      console.warn('【编辑获取数据失败】', res)
    }
  } else {
    // 设置默认值
    state.form = {
      id: 0,
      protocolName: '',
      equReactorId: undefined,
      equFeedingScaleId: undefined,
      days: 0,
      initialWorkingVolume: 0,
      initialWorkingMediumId: 0,
      transferCellVolume: 0,
      transferCellTypeId: 0,
      glucoseFeedingVerification: true,
      remark: '',
      autoGlucoseFeedingRules: [],
      feedingTasks: [],
      fixedFeedingPumps: defaultPumps
    }
  }
  
  // 等待 DOM 更新
  await nextTick()
  // tab渲染条件日志
  console.log('【hasGlucosePump】', hasGlucosePump.value)
  console.log('【activeTab】', activeTab.value)
}

// 提交表单
const onSure = async () => {
  if (!formRef.value) return

  // 处理补料时间格式
  state.form.feedingTasks.forEach(task => {
    if (!task.feedingTime) {
      task.feedingTime = '00:00:00'
    }
  })

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      state.sureLoading = true
      try {
        const api = new ProtocolApi()
        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
        activeTab.value = 'basic'
        lastActiveTab.value = 'basic'
      }
    }
  })
}

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

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

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 if (lastActiveTab.value == 'glucose') {
    if (!checkGlucose()) {
      await nextTick()
      activeTab.value = lastActiveTab.value
      return
    }
  }
  else {
    lastActiveTab.value = tab.paneName
  }

  //补料任务 默认选中第一个
  if(tab.paneName == 'tasks'){
    // feedingPumpTabs 是 computed，取第一个的 name
    if (feedingPumpTabs.value.length > 0) {
      feedingTaskActiveTab.value = String(feedingPumpTabs.value[0].feedingPumpNo)
    } else {
      feedingTaskActiveTab.value = ''
    }
  }
}

function addTaskByPump(pumpNo: number) {
  state.form.feedingTasks.push({
    id: 0,
    protocolId: 0,
    feedingPumpNo: pumpNo,
    day: 0,
    feedingTime: '',
    feedingType: 1,
    feedingVolumePercent: 0,
    feedingVolume: 0
  })
}

function removeTaskByPump(pumpNo: number, index: number) {
  // 只移除当前泵下的第index个任务
  const tasks = getTasksByPumpNo(pumpNo)
  const task = tasks[index]
  const globalIndex = state.form.feedingTasks.findIndex(t => t === task)
  if (globalIndex !== -1) {
    state.form.feedingTasks.splice(globalIndex, 1)
  }
}

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

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

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 checkGlucose = () => {
  let valid = true
  state.form.autoGlucoseFeedingRules.forEach((rule: any) => {
    if (rule.cultureDayStarting > rule.cultureDayEnding) {
      valid = false
      proxy.$modal.msgError('培养天数(开始)不能大于培养天数(结束)')
    }
  })

  // 校验培养天数 (开始)和培养天数 (结束)是否存在重叠
  const rules = state.form.autoGlucoseFeedingRules
  for (let i = 0; i < rules.length; i++) {
    for (let j = i + 1; j < rules.length; j++) {
      if (rules[i].cultureDayStarting < rules[j].cultureDayEnding && rules[i].cultureDayEnding > rules[j].cultureDayStarting) {
        valid = false
        proxy.$modal.msgError('培养天数(开始)和培养天数(结束)存在重叠')
      }
      return valid
    }
  }
  return valid
}

// 处理泵选择变化
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 {
    row.pumpSpeed = state.pumpOptions.find(item => item.id == pumpId)?.pumpSpeed ?? 0
    row.configId = state.pumpOptions.find(item => item.id == pumpId)?.configId ?? 0
  } catch (error) {
    console.error('获取泵信息失败:', error)
    proxy.$modal.msgError('获取泵信息失败')
  }
}

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

  // 更新isGlucose状态
  const selectedMedium = state.mediumOptions.find(item => item.id === row.itemDefFeedingMediumID)
  row.isGlucose = selectedMedium?.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: any) =>
    item.itemDefFeedingMediumID !== undefined &&
    item.itemDefFeedingMediumID === row.itemDefFeedingMediumID &&
    item.feedingPumpNo !== row.feedingPumpNo
  )
  if (medium) {
    proxy.$modal.msgWarning('补料培养基存在重复')
  }
}

// feedingType变更时动态调整补料体积输入规则
function handleFeedingTypeChange(row: any, val: number | string | undefined): void {
  const type = Number(val);
  if (type === 1) {
    // 百分比，两位小数，范围0-100
    if (typeof row.feedingVolume === 'number') {
      let v = Math.round(row.feedingVolume * 100) / 100;
      if (v < 0) v = 0;
      if (v > 100) v = 100;
      row.feedingVolume = v;
    } else {
      row.feedingVolume = 0;
    }
  } else if (type === 2) {
    // 体积，非负整数
    if (typeof row.feedingVolume === 'number') {
      let v = Math.floor(row.feedingVolume);
      if (v < 0) v = 0;
      row.feedingVolume = v;
    } else {
      row.feedingVolume = 0;
    }
  }
}

// 补料体积输入框动态属性
function getFeedingVolumeProps(row: any) {
  if (row.feedingType === 1) {
    return { min: 0, max: 100, precision: 2, step: 0.01 };
    return { min: 0, max: 100, precision: 2 };
  } else if (row.feedingType === 2) {
    return { min: 0, precision: 0 };
  }
  return { min: 0 };
}

// 天数+1并复制当前行数据
function addDayCopy(row: any, pumpNo: number) {
  const newRow = { ...row, day: Number(row.day) + 1 };
  newRow.id = 0;
  newRow.feedingPumpNo = pumpNo;
  state.form.feedingTasks.push(newRow);
  // 排序：只对当前泵编号的任务排序
  const tasks = state.form.feedingTasks.filter((t: any) => t.feedingPumpNo === pumpNo);
  tasks.sort((a: any, b: any) => Number(a.day) - Number(b.day));
  // 重新合并排序后的结果到原数组
  let i = 0;
  for (let idx = 0; idx < state.form.feedingTasks.length; idx++) {
    if (state.form.feedingTasks[idx].feedingPumpNo === pumpNo) {
      state.form.feedingTasks[idx] = tasks[i++];
    }
  }
}

// 批量粘贴补料时间
function pasteFeedingTime(row: any, pumpNo: number) {
  const time = row.feedingTime;
  state.form.feedingTasks.forEach((task: any) => {
    if (task.feedingPumpNo === pumpNo && task !== row) {
      task.feedingTime = time;
    }
  });
}

// 批量粘贴补料类型
function pasteFeedingType(row: any, pumpNo: number) {
  const type = row.feedingType;
  state.form.feedingTasks.forEach((task: any) => {
    if (task.feedingPumpNo === pumpNo && task !== row) {
      task.feedingType = type;
      handleFeedingTypeChange(task, type); // 保证体积约束同步
    }
  });
}

// 批量粘贴补料体积
function pasteFeedingVolume(row: any, pumpNo: number) {
  const volume = row.feedingVolume;
  state.form.feedingTasks.forEach((task: any) => {
    if (task.feedingPumpNo === pumpNo && task !== row) {
      task.feedingVolume = volume;
    }
  });
}

const feedingPumpTabs = computed(() => {
  // 只显示已选择补料培养基的泵
  return state.form.fixedFeedingPumps
    .filter(pump => pump.itemDefFeedingMediumID)
    .map(pump => {
      const medium = state.mediumOptions.find(m => m.id === pump.itemDefFeedingMediumID)
      return {
        feedingPumpNo: pump.feedingPumpNo,
        feedingPumpName: pump.feedingPumpName,
        mediumName: medium ? medium.name : ''
      }
    })
})

// 添加判断是否存在糖补料的计算属性
const hasGlucosePump = computed(() => {
  console.log('检查糖补料泵:', state.form.fixedFeedingPumps)
  const hasGlucose = state.form.fixedFeedingPumps.some(pump => {
    const isGlucose = pump.isGlucose === true
    console.log(`泵${pump.feedingPumpNo} isGlucose:`, isGlucose)
    return isGlucose
  })
  console.log('是否存在糖补料泵:', hasGlucose)
  return hasGlucose
})

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, pumpSpeed: number, configId: number }) => ({
      id: item.id ?? 0,
      name: item.deviceNo ?? '',
      pumpSpeed: item.pumpSpeed ?? 0,
      configId: item.configId ?? 0
    })) ?? []
  }
}

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
    })) ?? []
  }
}

function getTasksByPumpNo(pumpNo: number) {
  return state.form.feedingTasks.filter((task: any) => task.feedingPumpNo === pumpNo)
}

// 监听补料培养基变化
watch(() => state.form.fixedFeedingPumps, (newPumps) => {
  newPumps.forEach(pump => {
    if (pump.itemDefFeedingMediumID) {
      const medium = state.mediumOptions.find(m => m.id === pump.itemDefFeedingMediumID)
      pump.isGlucose = medium?.isGlucose ?? false
    }
  })
}, { deep: true })

// 监听反应器选择变化
watch(() => state.form.equReactorId, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    console.log(" ssssssss", state.selectedReactor);
    // 获取选中反应器的信息
    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 (state.id == 0) {
          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
          }
        }
      })
    }
  }
}, { immediate: true })


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;
  }
}

.feeding-task-tabs {
  margin-bottom: 0;

  .el-tabs__header {
    margin-bottom: 10px;
  }

  .el-tab-pane {
    padding: 0 0 10px 0;
  }
}

.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;
}

.pretty-table {
  border-radius: 8px;
  box-shadow: 0 2px 8px #e0e7ef;
  overflow: hidden;
  margin-bottom: 10px;

  .el-table__header th {
    background: #f0f3fa;
    color: #333;
    font-weight: bold;
    font-size: 15px;
    border-bottom: 1.5px solid #e0e7ef;
  }

  .el-table__body tr:hover>td {
    background: #e6f7ff !important;
  }

  .el-table__cell {
    padding: 6px 0;
  }
}

.pretty-delete-btn {
  transition: background 0.2s;

  &:hover {
    background: #ffeded !important;
    color: #f56c6c !important;
  }
}
</style>