<template>
  <div class="code-image">
    <img :id="`barcode${props.componentKey}`" v-if="imgSrc && isValid" />
    <div class="placebox" v-else>
      <div class="tips">{{ txt }}</div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { inject, ref, watch, nextTick, computed } from 'vue';
  import { apiConfigFunc } from '/@/utils/event/design';
  import { useI18n } from '/@/hooks/web/useI18n';
  import JsBarcode from 'jsbarcode';

  const { t } = useI18n();
  const props = defineProps({
    defaultValue: String,
    codeType: String,
    format: String,
    displayValue: Boolean,
    apiConfig: Object,
    componentKey: {
      type: String,
      default: '',
    },
  });
  const imgSrc = ref();
  const options = ref({
    format: props.format,
    displayValue: props.displayValue,
  });

  const isValid = ref<boolean>(true);
  const formModel = inject<any>('formModel', null);
  const isCamelCase = inject<boolean>('isCamelCase', false);

  const txt = computed(() => {
    return isValid.value ? t('请先进行配置') : t('此格式不支持该文本');
  });

  const getBarCode = () => {
    if (imgSrc.value) {
      isValid.value = true;
      nextTick(() => {
        try {
          JsBarcode(`#barcode${props.componentKey}`, imgSrc.value, options.value);
        } catch (error) {
          isValid.value = false;
        }
      });
    }
  };

  watch(
    () => [props.displayValue, props.format],
    () => {
      options.value.format = props.format;
      options.value.displayValue = props.displayValue;
      getBarCode();
    },
  );
  watch(
    () => [props.defaultValue, props.apiConfig, props.codeType],
    async () => {
      if (props.codeType == 'api') {
        imgSrc.value = await apiConfigFunc(props.apiConfig, isCamelCase, formModel);
      } else if (props.codeType == 'fixed') {
        imgSrc.value = props.defaultValue;
      }
      getBarCode();
    },
    {
      deep: true,
      immediate: true,
    },
  );
</script>
<style scoped lang="less">
  .placebox {
    width: 200px;
    height: 100px;
    background: rgb(0 0 0 / 2%);
    border: 2px dashed #d9d9d9;
    text-align: center;
    display: flex;
    justify-content: center;
    align-items: center;

    .tips {
      color: rgb(0 0 0 / 43%);
      flex: 1;
    }
  }
</style>
