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

import { FtMessage } from '@/libs/message'
import { compareJSON, convertValuesToString } 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,
})
console.log(formData)

/**
 * 标签单位映射表，用于显示各参数的单位
 */
const labelUnitMap: Record<string, any> = formulaStore.labelUnitMap
/**
 * 配方配置列表
 */
const formulaConfigList = ref(formulaStore.formulaConfigList)
/**
 * 组件挂载时注册方法供父组件调用
 */
watchEffect(() => {
  formData.value = cloneDeep(formulaStore.defaultFormulaInfo)
  formData.value = convertValuesToString(formData.value, 'name')
  // formData.value = convertValuesToInt(formData.value)
})
const settingFormRef = ref()
/**
 * 处理表单提交
 * 根据不同的type属性值执行不同的保存逻辑
 */
const handleSubmit = () => {
  settingFormRef.value.validate(async (valid: any) => {
    if (valid) {
      // 修改默认值
      const diff = compareJSON(formulaStore.defaultFormulaInfo, formData.value)
      const diffKeys = Object.keys(diff)
      if (diffKeys.length) {
        await 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 (value.substring(0, 1) === '.' || value.split('.').length > 2) {
    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
      ref="settingFormRef"
      class="form-box"
      :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="item.name_ch"
        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'">
          <ft-input
            v-model="formData[item.setting_id]"
            layout-name="number"
            style="width: 80%"
            :name="item.setting_id"
            :controls="false"
            :disabled="!props.editable"
          >
            <template v-if="labelUnitMap[item.setting_id]" #append>
              {{ labelUnitMap[item.setting_id] }}
            </template>
          </ft-input>
        </template>
        <template v-if="item.val_type === 'float'">
          <ft-input
            v-model="formData[item.setting_id]"
            layout-name="number"
            style="width: 80%"
            :name="item.setting_id"
            :controls="false"
            :disabled="!props.editable"
          >
            <template v-if="labelUnitMap[item.setting_id]" #append>
              {{ labelUnitMap[item.setting_id] }}
            </template>
          </ft-input>
        </template>
        <template v-else-if="item.val_type === 'enum'">
          <el-select
            v-model="formData[item.setting_id]"
            v-prevent-keyboard
            style="width: 80%"
            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 class="default-btn">
      <el-button v-if="editable" type="primary" @click="handleSubmit">
        确定
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.formula-form {
  font-size: 20px !important;
  height: 100%;
  align-items: center;
  .form-box {
    height: calc(100% - 50px);
    overflow: auto;
  }
  .default-btn {
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    .el-button {
      width: 100px;
    }
  }
}

.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-select) {
  height: 42px;
}
:deep(.el-select__wrapper) {
  height: 42px;
}
: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>
