<template>
  <formula
    v-bind="{ ...$attrs, value: valueCompute, fields, dataType: _dataType }"
    :formulas="formulas"
    :class="$style.formula"
    v-on="{ ...$listeners, input: onInput }"
  />
</template>

<script>
import formulas from '@/form-designer/formula'
import formula from '@/form-designer/sd-formula.vue'
import components from './_import-components/sd-formula-compute-import'

export default {
  name: 'SdFormulaCompute',
  components: { ...components, formula },
  props: {
    valueString: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [Object, String],
      default: undefined,
    },
    // 加载fields，此方法会替换fields
    loadFields: {
      type: Function,
      default: undefined,
    },
    dataType: {
      type: String,
      default: undefined,
    },
  },
  data() {
    return {
      formulas: [],
      fields: [],
    }
  },
  computed: {
    valueCompute() {
      return this.valueString && this.value ? JSON.parse(this.value) : this.value
    },
    _dataType() {
      // 用户和部门是数组，兼容使用了SdFieldPicker组件中选择的人员或部门字段的type
      if (['user', 'group'].includes(this.dataType)) {
        return this.dataType + '[]'
      }
      return this.dataType
    },
  },
  created() {
    formulas().then((values) => {
      this.formulas = values
    })
    this.fields = this.$attrs.fields || []
    this.loadFields?.().then((data) => {
      this.fields = data
    })
  },
  methods: {
    onInput(value) {
      this.$emit('input', this.valueString && value ? JSON.stringify(value) : value)
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.formula {
  line-height: 1;
  > span {
    padding: 0;
  }
}
</style>
