<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    width="1200px"
    class="custom-dialog"
    draggable
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    destroy-on-close
    :style="{ height: '95vh' }"
    @close="close"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="220px"
      size="default"
      v-loading="loading"
    >
      <el-row :gutter="25">
        <!-- 阶段 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="hover" class="group-card">
            <div class="section-title">阶段</div>
            <el-form-item label="策略名称" prop="configName" required>
              <el-input v-model="formData.configName" clearable placeholder="请输入策略名称" />
            </el-form-item>
            <el-form-item label="总理论时长" prop="totalTheoryTime" required>
              <el-input-number v-model="formData.totalTheoryTime" :min="0" style="width:100%" />
              <template #append>min</template>
            </el-form-item>
            <div class="sub-group">
              <div class="sub-title">校准</div>
              <el-form-item label="校准阶段时长" prop="calibrateDuration" required>
                <el-input-number v-model="formData.calibrateDuration" :min="0" style="width:100%" />
                <template #append>s</template>
              </el-form-item>
              <el-form-item label="校准阶段补料占总量百分比" prop="calibrateVolumePercent" required>
                <el-input-number v-model="formData.calibrateVolumePercent" :min="0" :max="100" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
              <el-form-item label="校准理论速度" prop="calibrateTheorySpeed" required>
                <el-input-number v-model="formData.calibrateTheorySpeed" :min="0" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
            </div>
            <div class="sub-group">
              <div class="sub-title">高速</div>
              <el-form-item label="高速阶段泵速百分比" prop="highSpeedPercent" required>
                <el-input-number v-model="formData.highSpeedPercent" :min="0" :max="100" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
              <el-form-item label="高速阶段补料占总量百分比" prop="highSpeedVolumePercent" required>
                <el-input-number v-model="formData.highSpeedVolumePercent" :min="0" :max="100" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
              <el-form-item label="高速理论时长" prop="highSpeedTheoryTime" required>
                <el-input-number v-model="formData.highSpeedTheoryTime" :min="0" style="width:100%" />
                <template #append>min</template>
              </el-form-item>
            </div>
            <div class="sub-group">
              <div class="sub-title">低速</div>
              <el-form-item label="低速阶段泵速百分比" prop="lowSpeedPercent" required>
                <el-input-number v-model="formData.lowSpeedPercent" :min="0" :max="100" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
              <el-form-item label="低速阶段补料占总量百分比" prop="lowSpeedVolumePercent" required>
                <el-input-number v-model="formData.lowSpeedVolumePercent" :min="0" :max="100" style="width:100%" />
                <template #append>%</template>
              </el-form-item>
              <el-form-item label="低速理论时长" prop="lowSpeedTheoryTime" required>
                <el-input-number v-model="formData.lowSpeedTheoryTime" :min="0" style="width:100%" />
                <template #append>min</template>
              </el-form-item>
            </div>
          </el-card>
        </el-col>
        <!-- 监控 -->
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
          <el-card shadow="hover" class="group-card">
            <div class="section-title">监控</div>
            <el-form-item label="环控间隔时间" prop="intervalTime" required>
              <el-input-number v-model="formData.intervalTime" :min="0" style="width:100%" />
              <template #append>s</template>
            </el-form-item>
            <el-form-item label="补料超量百分比" prop="excessPercentage" required>
              <el-input-number v-model="formData.excessPercentage" :min="0" style="width:100%" />
              <template #append>%</template>
            </el-form-item>
            <el-form-item label="超时时间" prop="timeOutSeconds" required>
              <el-input-number v-model="formData.timeOutSeconds" :min="0" style="width:100%" />
              <template #append>s</template>
            </el-form-item>
            <el-form-item label="终点百分比" prop="terminalVolumePercent" required>
              <el-input-number v-model="formData.terminalVolumePercent" :min="0" :max="100" style="width:100%" />
              <template #append>%</template>
            </el-form-item>
            <div class="sub-group">
              <div class="sub-title">抖动</div>
              <el-form-item label="抖动环控时间系数" prop="ditherIntervalCoefficient" required>
                <el-input-number v-model="formData.ditherIntervalCoefficient" :min="0" style="width:100%" />
              </el-form-item>
              <el-form-item label="抖动系数" prop="ditherCoefficient" required>
                <el-input-number v-model="formData.ditherCoefficient" :min="0" style="width:100%" />
              </el-form-item>
              <el-form-item label="抖动观察时间系数" prop="ditherMonitorTime" required>
                <el-input-number v-model="formData.ditherMonitorTime" :min="0" style="width:100%" />
              </el-form-item>
              <el-form-item label="抖动地秤系数" prop="ditherScaleCoefficient" required>
                <el-input-number v-model="formData.ditherScaleCoefficient" :min="0" style="width:100%" />
              </el-form-item>
            </div>
            <div class="sub-group">
              <div class="sub-title">返水</div>
              <el-form-item label="返水环控时间系数" prop="rebateIntervalCoefficient" required>
                <el-input-number v-model="formData.rebateIntervalCoefficient" :min="0" style="width:100%" />
              </el-form-item>
              <el-form-item label="返水系数" prop="rebateCoefficient" required>
                <el-input-number v-model="formData.rebateCoefficient" :min="-100" style="width:100%" />
              </el-form-item>
            </div>
            <div class="sub-group">
              <div class="sub-title">堵塞</div>
              <el-form-item label="堵塞环控时间系数" prop="jamIntervalCoefficient" required>
                <el-input-number v-model="formData.jamIntervalCoefficient" :min="0" style="width:100%" />
              </el-form-item>
              <el-form-item label="堵塞系数" prop="jamCoefficient" required>
                <el-input-number v-model="formData.jamCoefficient" :min="0" style="width:100%" />
              </el-form-item>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close" size="default">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" size="default" :loading="loading">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { UspFeedingConfigApi } from '/@/api/admin/UspFeedingConfigApi'

const props = defineProps<{
  modelValue: boolean
  title: string
}>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'refresh'): void
}>()

const formRef = ref<FormInstance>()
// 取消类型限制，保证所有字段都能用
const formData = reactive({
  configName: '',
  totalTheoryTime: 0,
  calibrateDuration: 0,
  calibrateVolumePercent: 0,
  calibrateTheorySpeed: 0,
  highSpeedPercent: 0,
  highSpeedVolumePercent: 0,
  highSpeedTheoryTime: 0,
  lowSpeedPercent: 0,
  lowSpeedVolumePercent: 0,
  lowSpeedTheoryTime: 0,
  intervalTime: 0,
  excessPercentage: 0,
  timeOutSeconds: 0,
  terminalVolumePercent: 0,
  ditherIntervalCoefficient: 0,
  ditherCoefficient: 0,
  ditherMonitorTime: 0,
  ditherScaleCoefficient: 0,
  rebateIntervalCoefficient: 0,
  rebateCoefficient: 0,
  jamIntervalCoefficient: 0,
  jamCoefficient: 0,
  enabled: true,
  isTwoStep: 0,
  id: 0
})

const rules = {
  configName: [{ required: true, message: '请输入策略名称', trigger: ['blur', 'change'] }],
  totalTheoryTime: [{ required: true, message: '请输入总理论时长', trigger: ['blur', 'change'] }],
  calibrateDuration: [{ required: true, message: '请输入校准阶段时长', trigger: ['blur', 'change'] }],
  calibrateVolumePercent: [{ required: true, message: '请输入校准阶段补料占总量百分比', trigger: ['blur', 'change'] }],
  calibrateTheorySpeed: [{ required: true, message: '请输入校准理论速度', trigger: ['blur', 'change'] }],
  highSpeedPercent: [{ required: true, message: '请输入高速阶段泵速百分比', trigger: ['blur', 'change'] }],
  highSpeedVolumePercent: [{ required: true, message: '请输入高速阶段补料占总量百分比', trigger: ['blur', 'change'] }],
  highSpeedTheoryTime: [{ required: true, message: '请输入高速理论时长', trigger: ['blur', 'change'] }],
  lowSpeedPercent: [{ required: true, message: '请输入低速阶段泵速百分比', trigger: ['blur', 'change'] }],
  lowSpeedVolumePercent: [{ required: true, message: '请输入低速阶段补料占总量百分比', trigger: ['blur', 'change'] }],
  lowSpeedTheoryTime: [{ required: true, message: '请输入低速理论时长', trigger: ['blur', 'change'] }],
  intervalTime: [{ required: true, message: '请输入环控间隔时间', trigger: ['blur', 'change'] }],
  excessPercentage: [{ required: true, message: '请输入补料超量百分比', trigger: ['blur', 'change'] }],
  timeOutSeconds: [{ required: true, message: '请输入超时时间', trigger: ['blur', 'change'] }],
  terminalVolumePercent: [{ required: true, message: '请输入终点百分比', trigger: ['blur', 'change'] }],
  ditherIntervalCoefficient: [{ required: true, message: '请输入抖动环控时间系数', trigger: ['blur', 'change'] }],
  ditherCoefficient: [{ required: true, message: '请输入抖动系数', trigger: ['blur', 'change'] }],
  ditherMonitorTime: [{ required: true, message: '请输入抖动观察时间系数', trigger: ['blur', 'change'] }],
  ditherScaleCoefficient: [{ required: true, message: '请输入抖动地秤系数', trigger: ['blur', 'change'] }],
  rebateIntervalCoefficient: [{ required: true, message: '请输入返水环控时间系数', trigger: ['blur', 'change'] }],
  rebateCoefficient: [{ required: true, message: '请输入返水系数', trigger: ['blur', 'change'] }],
  jamIntervalCoefficient: [{ required: true, message: '请输入堵塞环控时间系数', trigger: ['blur', 'change'] }],
  jamCoefficient: [{ required: true, message: '请输入堵塞系数', trigger: ['blur', 'change'] }]
}

const loading = ref(false)
const dialogVisible = ref(false)
const api = new UspFeedingConfigApi()

watch(
  () => props.modelValue,
  (val) => {
    dialogVisible.value = val
  }
)

watch(
  () => dialogVisible.value,
  (val) => {
    emit('update:modelValue', val)
    if (!val) resetForm()
  }
)

function resetForm() {
  formRef.value?.resetFields()
  Object.assign(formData, {
    configName: '',
    totalTheoryTime: 0,
    calibrateDuration: 0,
    calibrateVolumePercent: 0,
    calibrateTheorySpeed: 0,
    highSpeedPercent: 0,
    highSpeedVolumePercent: 0,
    highSpeedTheoryTime: 0,
    lowSpeedPercent: 0,
    lowSpeedVolumePercent: 0,
    lowSpeedTheoryTime: 0,
    intervalTime: 0,
    excessPercentage: 0,
    timeOutSeconds: 0,
    terminalVolumePercent: 0,
    ditherIntervalCoefficient: 0,
    ditherCoefficient: 0,
    ditherMonitorTime: 0,
    ditherScaleCoefficient: 0,
    rebateIntervalCoefficient: 0,
    rebateCoefficient: 0,
    jamIntervalCoefficient: 0,
    jamCoefficient: 0,
    enabled: true,
    isTwoStep: 0,
    id: 0
  })
}

function setFormData(data: any) {
  Object.assign(formData, data)
}

function close() {
  dialogVisible.value = false
}

async function open(row?: any) {
  dialogVisible.value = true
  if (row && row.id) {
    loading.value = true
    try {
      const res = await api.get({ id: row.id })
      if (res.success && res.data) setFormData(res.data)
      else ElMessage.warning(res.msg || '获取数据失败')
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据出错')
    } finally {
      loading.value = false
    }
  } else resetForm()
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    loading.value = true
    try {
      if (formData.id) {
        const updateInput = {
          ...formData,
          setSpeed: formData.calibrateTheorySpeed,
          speedDiff: 0,
          feedTime: formData.totalTheoryTime
        }
        await api.update(updateInput)
        ElMessage.success('修改成功')
      } else {
        const addInput = {
          ...formData,
          setSpeed: formData.calibrateTheorySpeed,
          speedDiff: 0,
          feedTime: formData.totalTheoryTime
        }
        delete (addInput as any).id
        await api.add(addInput)
        ElMessage.success('新增成功')
      }
      emit('refresh')
      close()
    } catch (error) {
      console.error(error)
      ElMessage.error('提交失败')
    } finally {
      loading.value = false
    }
  })
}

defineExpose({ open })
</script>

<style scoped>
.group-card {
  margin-bottom: 24px;
  border-radius: 10px;
  box-shadow: 0 2px 12px #f0f1f2;
  background: #fff;
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 18px;
  letter-spacing: 2px;
}
.sub-group {
  background: #f7fafd;
  border-radius: 8px;
  padding: 12px 16px 4px 16px;
  margin-bottom: 18px;
  margin-top: 18px;
}
.sub-title {
  font-size: 15px;
  color: #6ca0dc;
  font-weight: bold;
  margin-bottom: 10px;
  letter-spacing: 1px;
}
.el-form-item {
  margin-bottom: 18px !important;
}
@media (max-width: 1200px) {
  .group-card {
    margin-bottom: 16px;
  }
}
</style>
