<template>
  <div>
    <a-input-number
      :class="[style && Object.keys(style).length > 0 ? 'customStyle' : '']"
      :placeholder="placeholder"
      :maxlength="parseInt(maxlength as string)"
      :addonBefore="addonBefore"
      :addonAfter="addonAfter"
      :disabled="disabled"
      :size="size"
      v-model:value="valueRef"
      :style="{ width: width }"
      :formatter="formatterVal"
      :parser="formatterVal"
      @change="handleChange"
      @blur="emit('blur')"
    >
      <template #prefix v-if="prefix">
        <Icon :icon="prefix" />
      </template>
    </a-input-number>
  </div>
</template>

<script lang="ts" setup>
  import { watch, ref, inject, toRaw, computed } from 'vue';
  import { Icon } from '/@/components/Icon';
  import JBC from 'jsbi-calculator';
  import { ComputationalConfig } from '../../Designer/src/types';
  import { mean, max, min } from 'lodash-es';
  import { camelCaseString, formatter } from '/@/utils/event/design';

  const { calculator } = JBC;
  const formModel = inject<any>('formModel', null); // 注入表单数据
  const isCamelCase = inject<boolean>('isCamelCase', false);
  const emit = defineEmits(['update:value', 'change', 'blur']);

  const props = defineProps({
    value: Number,
    width: String,
    maxlength: [String, Number],
    placeholder: String,
    addonBefore: String,
    addonAfter: String,
    prefix: String,
    disabled: Boolean,
    computationalConfig: Array as PropType<ComputationalConfig[]>,
    index: Number,
    size: String,
    decimals: Number,
    style: Object,
  });

  const valueRef = ref(0);

  watch(
    () => props.value,
    (val) => {
      valueRef.value = val!;
      emit('change', val);
    },
    // {
    //   immediate: true,
    // },
  );
  watch(
    () => formModel,
    () => {
      if (!toRaw(props)?.computationalConfig) return;

      let expressionStr = '';

      for (let config of toRaw(props).computationalConfig!) {
        const bindTable = !isCamelCase
          ? `${config.bindTable}List`
          : `${camelCaseString(config.bindTable!)}List`;
        const bindField = !isCamelCase ? config.bindField : camelCaseString(config.bindField!);

        if (config.type === 'computational' || config.type === 'money-chinese') {
          if (config.isMainForm) {
            //如果是主表字段 直接从formModel 取
            expressionStr += formModel[bindField!] ? `(${formModel[bindField!]})` : 0;
          } else {
            //如果是附表 从formModel 取出来 需要进行处理
            if (formModel[bindTable]?.length <= 0) return;
            if (config.computationalMethod) {
              const fieldArray = formModel[bindTable].map(
                (x: { [x: string]: any }) => Number(x[bindField!]) || 0,
              );
              let sumVal = 0;
              if (fieldArray?.length) {
                sumVal = fieldArray?.reduce((prev, cur) => {
                  return calculator(`((${prev})+(${cur}))`);
                });
              }
              switch (config.computationalMethod) {
                case 'sum':
                  expressionStr += `(${sumVal})`;
                  break;
                case 'mean':
                  expressionStr += `(${mean(fieldArray)})`;
                  break;
                case 'min':
                  expressionStr += `(${min(fieldArray)})`;
                  break;
                case 'max':
                  expressionStr += `(${max(fieldArray)})`;
                  break;
              }
            } else {
              expressionStr +=
                formModel[bindTable][props.index!] && formModel[bindTable][props.index!][bindField!]
                  ? `(${formModel[bindTable][props.index!][bindField!]})`
                  : 0;
            }
          }
        } else {
          expressionStr += `${config.label!}`;
        }
      }

      if (props.computationalConfig!.length > 0) {
        try {
          valueRef.value =
            calculator(`(${expressionStr})`) === 'undefined'
              ? 0
              : Number(calculator(`(${expressionStr})`));
          emit('update:value', Number(formatter(valueRef.value.toString(), props.decimals)));
        } catch {
          console.error('计算式配置错误', expressionStr);
        }
      }
    },
    { deep: true, immediate: true },
  );

  const formatterVal = (value) => {
    return formatter(value, props.decimals);
  };

  const handleChange = (val) => {
    emit('change');
    emit('update:value', val);
  };
  const color = computed(() => {
    return props.style?.color;
  });
  const backgroundcolor = computed(() => {
    return props.style
      ? props.style['background-color'] || (props.disabled ? '#f5f5f5' : '#fff')
      : '#fff';
  });
  const border = computed(() => {
    return props.style?.border || '1px solid #d9d9d9';
  });
  const fontsize = computed(() => {
    return props.style ? props.style['font-size'] : '14px';
  });
  const fontstyle = computed(() => {
    return props.style ? props.style['font-style'] : 'normal';
  });
  const customwidth = computed(() => {
    return props.style?.width;
  });
  const height = computed(() => {
    return props.style?.height || '32px';
  });
  const textalign = computed(() => {
    return props.style ? props.style['text-align'] : 'left';
  });
</script>
<style scoped lang="less">
  .customStyle {
    width: v-bind(customwidth) !important;

    :deep(.ant-input-number) {
      background-color: v-bind(backgroundcolor);
      border: v-bind(border);
      font-size: v-bind(fontsize);
      font-style: v-bind(fontstyle);
      color: v-bind(color);
      text-align: v-bind(textalign);
      height: v-bind(height);
      line-height: v-bind(height);
    }
  }
</style>
