<template>
  <div class="wrap-box ant-input" :class="disabled ? 'disabled-box' : ''">
    <a-tag
      v-for="(item, key) in state.tags"
      :key="item + key"
      :closable="!disabled"
      @close="handleClose(key)"
      :style="getClass(key)"
      >{{ item }}</a-tag
    >
    <span class="input-box" v-if="!disabled"
      ><a-input
        v-model:value="state.value"
        :placeholder="placeholder"
        :disabled="disabled"
        :readonly="readonly"
        :bordered="false"
        @press-enter="handlePressEnter"
        @blur="blurData"
        @click="clickData"
        @change="changeData"
    /></span>
    <span class="input-box" v-else
      ><a-input
        v-model:value="state.value"
        :placeholder="placeholder"
        :disabled="disabled"
        :readonly="readonly"
        :bordered="false"
    /></span>
  </div>
</template>
<script lang="ts" setup>
  import { inject, onMounted, reactive, ref, watch } from 'vue';
  import { getDicDetailList } from '/@/api/system/dic';
  import { apiConfigFunc } from '/@/utils/event/design';
  const renderKey = ref(0);
  const props = defineProps({
    value: {
      type: String,
      default: '',
    },
    defaultValue: String,
    placeholder: String,
    disabled: {
      type: Boolean,
      default: false,
    },
    readonly: Boolean,
    styleConfig: {
      type: Object,
      default: () => {
        return {
          colors: [], //颜色配置
          isLoop: true, //是否循环选择样式
        };
      },
    },
    datasourceType: {
      type: String,
      default: 'static',
    }, // static 客户填写 api API获取 dic 数据字典获取
    apiConfig: {
      type: Object,
      default: () => {
        return {
          path: 'CodeGeneration/selection',
          method: 'GET',
          apiId: '93d735dcb7364a0f8102188ec4d77ac7',
        };
      },
    },
    itemId: {
      type: String,
      default: '',
    },
    index: Number,
  });

  const state = reactive({
    tags: [] as Array<string>,
    value: '',
  });
  const emit = defineEmits(['update:value', 'change', 'blur', 'click']);
  onMounted(async () => {
    if (props.value) {
      state.tags = props.value.split(',');
    } else {
      await getData();
    }
  });
  watch(
    () => props.value,
    (val) => {
      if (val) {
        state.tags = val.split(',');
      } else if (val === null) {
        getData();
      }
    },
    {
      immediate: true,
    },
  );
  const isCamelCase = inject<boolean>('isCamelCase', false);
  const formModel = inject<any>('formModel', null);
  async function getData() {
    if (props.datasourceType === 'api' && props.apiConfig?.path) {
      let res = await apiConfigFunc(props.apiConfig, isCamelCase, formModel, props.index);
      if (res && Array.isArray(res)) {
        let arr = res.map((ele) => {
          return ele.label;
        });
        state.tags = arr;
      }
    } else if (props.datasourceType === 'dic' && props.itemId) {
      let res = await getDicDetailList({ itemId: props.itemId });
      if (res && Array.isArray(res)) {
        let arr = res.map((ele) => {
          return ele.name;
        });
        state.tags = arr;
      }
    }
    handleEmit();
  }
  function getClass(index) {
    const defaultBgColor = '#fafafa';
    const defaultFontColor = '#000000';
    const defaultBorderWidth = 1;
    const defaultBorderColor = '#d9d9d9';
    if (props.styleConfig.colors && Array.isArray(props.styleConfig.colors)) {
      if (props.styleConfig.colors[index]) {
        let styleConfig = {
          bgColor: props.styleConfig.colors[index].bgColor
            ? props.styleConfig.colors[index].bgColor
            : defaultBgColor,
          fontColor: props.styleConfig.colors[index].fontColor
            ? props.styleConfig.colors[index].fontColor
            : defaultFontColor,
          borderWidth: props.styleConfig.colors[index].borderWidth
            ? props.styleConfig.colors[index].borderWidth
            : defaultBorderWidth,
          borderColor: props.styleConfig.colors[index].borderColor
            ? props.styleConfig.colors[index].borderColor
            : defaultBorderColor,
        };
        return `
        background-color: ${styleConfig.bgColor};
        border-width: ${styleConfig.borderWidth}px;
        border-color: ${styleConfig.borderColor};
        color: ${styleConfig.fontColor};
        `;
      } else {
        if (props.styleConfig.isLoop) {
          let loopIndex = index % props.styleConfig.colors.length;
          if (props.styleConfig.colors[loopIndex]) {
            let styleConfig = {
              bgColor: props.styleConfig.colors[loopIndex].bgColor
                ? props.styleConfig.colors[loopIndex].bgColor
                : defaultBgColor,
              fontColor: props.styleConfig.colors[loopIndex].fontColor
                ? props.styleConfig.colors[loopIndex].fontColor
                : defaultFontColor,
              borderWidth: props.styleConfig.colors[loopIndex].borderWidth
                ? props.styleConfig.colors[loopIndex].borderWidth
                : defaultBorderWidth,
              borderColor: props.styleConfig.colors[loopIndex].borderColor
                ? props.styleConfig.colors[loopIndex].borderColor
                : defaultBorderColor,
            };
            return `
              background-color: ${styleConfig.bgColor};
              border-width: ${styleConfig.borderWidth}px;
              border-color: ${styleConfig.borderColor};
              color: ${styleConfig.fontColor};
              `;
          } else {
            return `
            background-color: ${defaultBgColor};
            border-width: ${defaultBorderWidth}px;
            border-color: ${defaultBorderColor};
            color: ${defaultFontColor};
        `;
          }
        } else {
          return `
            background-color: ${defaultBgColor};
            border-width: ${defaultBorderWidth}px;
            border-color: ${defaultBorderColor};
            color: ${defaultFontColor};
        `;
        }
      }
    } else {
      return `
            background-color: ${defaultBgColor};
            border-width: ${defaultBorderWidth}px;
            border-color: ${defaultBorderColor};
            color: ${defaultFontColor};
        `;
    }
  }
  function handleEmit() {
    emit('update:value', state.tags.join(','));
  }
  const handleClose = (index) => {
    state.tags.splice(index, 1);
    handleEmit();
    renderKey.value++;
    changeData();
  };
  const handlePressEnter = (e) => {
    state.tags.push(e.target.value);
    state.value = '';
    handleEmit();
    renderKey.value++;
    changeData();
  };
  function blurData() {
    emit('blur');
  }
  function clickData() {
    emit('click');
  }
  function changeData() {
    emit('change');
  }
</script>
<style lang="less" scoped>
  .wrap-box {
    display: inline-block;
    padding: 0 11px;
    text-align: left;

    .ant-tag {
      vertical-align: top;
      margin-top: 4px;
    }
  }

  .input-box {
    box-sizing: border-box;
    margin: 0;
    color: rgb(0 0 0 / 85%);
    font-variant: tabular-nums;
    list-style: none;
    font-feature-settings: tnum;
    display: inline-block;
    width: 240px;
    height: auto;
    margin-right: 8px;
    padding: 0 7px;
    padding-left: 0;
    font-size: 12px;
    line-height: 20px;
    white-space: nowrap;
    opacity: 1;
    transition: all 0.3s;
  }

  .disabled-box {
    background-color: #f5f5f5;
  }
</style>
