<script lang="ts" setup>
import { formulaNameMap } from 'libs/constant'
import { cloneDeep } from 'lodash'
import { ref, watchEffect } from 'vue'

import { FtMessage } from '@/libs/message'
import { compareJSON, convertValuesToInt } from '@/libs/utils'
import { useFormulaStore } from '@/stores/formulaStore'

const props = defineProps<{
  editable: boolean
}>()
const formulaStore = useFormulaStore()
/**
 * 当前表单数据
 * 不同模式下有不同的初始值：
 * - home: 当前选中的配方
 * - setting: 默认配方信息
 * - formula: 当前选中的配方或默认配方
 */
const formData = ref<Record<string, any>>({
  ...formulaStore.defaultFormulaInfo,
})

/**
 * 标签单位映射表，用于显示各参数的单位
 */
const labelUnitMap: Record<string, any> = formulaStore.labelUnitMap
/**
 * 配方配置列表
 */
const formulaConfigList = ref(formulaStore.formulaConfigList)
/**
 * 组件挂载时注册方法供父组件调用
 */
watchEffect(() => {
  formData.value = cloneDeep(formulaStore.defaultFormulaInfo)
  formData.value = convertValuesToInt(formData.value)
})

/**
 * 处理表单提交
 * 根据不同的type属性值执行不同的保存逻辑
 */
const handleSubmit = () => {
  // 修改默认值
  const diff = compareJSON(formulaStore.defaultFormulaInfo, formData.value)
  const diffKeys = Object.keys(diff)
  if (diffKeys.length) {
    Promise.all(
      diffKeys.map(async (key) => {
        await formulaStore.setSettingFormulaConfig(key, diff[key].newVal || diff[key].obj2)
      }),
    )
    FtMessage.success('配方修改成功')
  }
  formulaStore.getFormualDefaultData()
}
const size = 'default'
const validatePass = (rule: any, value: any, callback: any, config: Formula.FormulaConfig) => {
  if (!value && value !== 0 && value !== '0') {
    callback(new Error('此为必填项'))
  }
  else if (config.val_type === 'int' || config.val_type === 'float') {
    const temp = Number(value)
    if (temp < config.val_lower_limit || temp > config.val_upper_limit) {
      callback(new Error(`输入范围为${config.val_lower_limit}-${config.val_upper_limit}`))
    }
  }
  callback()
}
</script>

<template>
  <div class="formula-form">
    <el-form
      :disabled="!props.editable"
      :model="formData"
      label-width="auto"
      label-position="right"
      :size="size"
      inline
    >
      <el-form-item
        v-for="item in formulaConfigList.filter((data) => data.is_visible_in_setting_page)"
        :key="item.setting_id"
        :label="formulaNameMap[item.setting_id]"
        style="width: 50%"
        :prop="item.setting_id"
        :rules="[
          {
            required: true,
            validator: (rule, value, callback) => validatePass(rule, value, callback, item),
            trigger: 'blur',
          },
        ]"
      >
        <template v-if="item.val_type === 'int'">
          <el-input
            v-model.number="formData[item.setting_id]"
            v-prevent-keyboard
            style="width: 80%"
            type="number"
            :name="item.setting_id"
            :controls="false"
            :disabled="!props.editable"
          >
            <template v-if="labelUnitMap[item.setting_id]" #append>
              {{ labelUnitMap[item.setting_id] }}
            </template>
          </el-input>
        </template>
        <template v-if="item.val_type === 'float'">
          <el-input
            v-model.number="formData[item.setting_id]"
            v-prevent-keyboard
            style="width: 80%"
            type="number"
            :name="item.setting_id"
            :controls="false"
            :disabled="!props.editable"
          >
            <template v-if="labelUnitMap[item.setting_id]" #append>
              {{ labelUnitMap[item.setting_id] }}
            </template>
          </el-input>
        </template>
        <template v-else-if="item.val_type === 'enum'">
          <el-select
            v-model="formData[item.setting_id]"
            v-prevent-keyboard
            style="width: 80%;height:40px"
            placeholder="请选择"
            readonly
          >
            <el-option v-for="log in item.enums" :key="log" :label="log" :value="log" />
          </el-select>
        </template>
      </el-form-item>
    </el-form>
    <div :style="{ marginLeft: '33%' }">
      <slot name="formulaBtn">
        <div class="default-btn">
          <el-button v-if="editable" type="primary" class="config-btn" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </slot>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.formula-form {
  font-size: 20px !important;
  padding: 5px;
  padding-left: 15px;
  align-items: center;
  .default-btn {
    margin-top: 1rem;
  }
  .config-btn {
    height: 3rem;
    width: 8rem;
  }
}

.formula-form-item {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.formData-input-config {
  width: 10vw;
}
:deep(.el-input__inner) {
  text-align: left;
  height: 40px;
}
:deep(.el-form-item) {
  margin-right: 0;
  align-items: center;
}
:deep(.el-input-group__append) {
  font-size: 12px;
  padding: 0 1vw;
}
/* 进入动画的初始状态 */
.slide-right-enter-from {
  transform: translateX(100%);
}
/* 进入动画的结束状态（也可以理解为激活状态） */
.slide-right-enter-to {
  transform: translateX(0);
}
/* 进入动画的过渡曲线等 */
.slide-right-enter-active {
  transition: transform 0.3s ease-in-out;
}
/* 离开动画的初始状态（激活状态） */
.slide-right-leave-from {
  transform: translateX(0);
}
/* 离开动画的结束状态 */
.slide-right-leave-to {
  transform: translateX(100%);
}
/* 离开动画的过渡曲线等 */
.slide-right-leave-active {
  transition: transform 0.3s ease-in-out;
}
</style>
