<template>
  <a-select
    :class="['text-left', style && Object.keys(style).length > 0 ? 'customStyle' : '']"
    :style="style && Object.keys(style).length > 0 ? {} : { width: width }"
    @dropdown-visible-change="handleFetch"
    v-bind="$attrs"
    @change="handleChange"
    :options="getOptions"
    v-model:value="selectedValue"
    :placeholder="placeholder"
    :mode="selectMode"
    :filter-option="handleFilterOption"
    allowClear
    :disabled="disabled"
  >
    <template #[item]="data" v-for="item in Object.keys($slots)">
      <slot :name="item" v-bind="data || {}"></slot>
    </template>
    <template #suffixIcon v-if="loading">
      <LoadingOutlined spin />
    </template>
    <template #notFoundContent v-if="loading">
      <span>
        <LoadingOutlined spin class="mr-1" />
        {{ t('component.form.apiSelectNotFound') }}
      </span>
    </template>
  </a-select>
</template>
<script lang="ts">
  import {
    defineComponent,
    PropType,
    ref,
    computed,
    unref,
    watch,
    inject,
    onMounted,
    watchEffect,
  } from 'vue';
  import { isFunction } from '/@/utils/is';
  import { useAttrs } from '/@/hooks/core/useAttrs';
  import { get, omit } from 'lodash-es';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { propTypes } from '/@/utils/propTypes';
  import { getDicDetailList } from '/@/api/system/dic';
  import { getDatasourceData } from '/@/api/system/datasource';
  import { apiConfigFunc, camelCaseString, isValidJSON } from '/@/utils/event/design';

  // import { apiConfigPageDesignFunc } from '/@/utils/event/pagetool';

  type OptionsItem = { label: string; value: string; disabled?: boolean };

  export default defineComponent({
    name: 'ApiSelect',
    components: {
      LoadingOutlined,
    },
    inheritAttrs: false,
    props: {
      value: {
        type: [Array, Object, String, Number],
      },
      numberToString: propTypes.bool,
      api: {
        type: Function as PropType<(arg?: Recordable) => Promise<OptionsItem[]>>,
        default: null,
      },
      // api params
      params: {
        type: [Array, Object, String, Number],
      },
      placeholder: String,
      resultField: propTypes.string.def(''),
      labelField: propTypes.string.def('label'),
      valueField: propTypes.string.def('value'),
      immediate: propTypes.bool.def(true),
      alwaysLoad: propTypes.bool.def(false),
      //数据来源 默认为空  如果不为空 则参数 api
      datasourceType: String,
      //静态数据默认选项
      staticOptions: Array as PropType<OptionsItem[]>,
      apiConfig: Object,
      mode: String,
      mainKey: String,
      index: Number,
      isMultiple: Boolean,
      isDesign: {
        type: Boolean,
        default: false,
      },
      style: Object,
      width: String,
      disabled: Boolean,
    },
    emits: ['options-change', 'change', 'update:value'],
    setup(props, { emit }) {
      const options = ref<OptionsItem[]>([]);
      const loading = ref(false);
      const isFirstLoad = ref(true);
      const emitData = ref<any[]>([]);
      const attrs = useAttrs();
      const { t } = useI18n();
      const formModel = inject<any>('formModel', null);
      const isCamelCase = inject<boolean>('isCamelCase', false);
      // const widgetFormModel = inject('widgetFormModel', ref<any>({}));
      // Embedded in the form, just use the hook binding to perform form verification
      const selectedValue = ref<string | number | undefined>(undefined);

      const getOptions = computed(() => {
        const { labelField, valueField, numberToString } = props;
        if (Array.isArray(unref(options))) {
          return unref(options).reduce((prev, next: Recordable) => {
            if (next) {
              const value = next[valueField];
              prev.push({
                ...omit(next, [labelField, valueField]),
                label: next[labelField],
                value: numberToString ? `${value}` : value,
              });
            }
            return prev;
          }, [] as OptionsItem[]);
        } else {
          return [];
        }
      });

      watchEffect(() => {
        if (props.isDesign && props.datasourceType === 'api' && props.apiConfig?.apiParams) {
          props.apiConfig.apiParams.forEach((params) => {
            params.tableInfo?.forEach((o) => {
              if (o.bindType == 'data') {
                let val = isValidJSON(o.value);
                let field = '';
                if (val && val.bindTable) {
                  let table = !isCamelCase
                    ? val.bindTable + 'List'
                    : camelCaseString(val.bindTable + '_List');
                  field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
                  formModel &&
                    formModel[table!][props.index || 0] &&
                    formModel[table!][props.index || 0][field];
                } else if (val && val.bindField) {
                  field = !isCamelCase ? val.bindField : camelCaseString(val.bindField);
                  formModel && formModel[field];
                }
              }
            });
          });
          fetch();
        }
      });
      watch(
        () => [props.params, props.apiConfig],
        () => {
          if (props.isDesign) {
            fetch();
          }
        },
        { deep: true },
      );

      watch(
        () => props.datasourceType,
        (val) => {
          fetch();
          selectedValue.value =
            !!props.value && val === 'staticData' ? (props.value as any) : undefined;
        },
      );

      watch(
        () => props.value,
        () => {
          selectedValue.value = ((typeof props.value === 'string' && !!props.value
            ? props.value?.split(',')
            : props.value) || undefined) as any;
          const selectedOption = getOptions.value.find(
            (item) => item[props.valueField] === props.value,
          );
          emit('change', props.value, selectedOption);
        },
        // {
        //   immediate: true,
        // },
      );
      onMounted(() => {
        fetch();
        selectedValue.value = ((typeof props.value === 'string' && !!props.value
          ? props.value?.split(',')
          : props.value) || undefined) as any;
      });

      const selectMode = computed(() => {
        return props.isMultiple ? 'multiple' : props.mode;
      });

      async function fetch() {
        options.value = [];
        let api;
        if (props.datasourceType) {
          if (props.datasourceType === 'staticData') {
            options.value = props.staticOptions!;
            emitChange();
          }
          if (props.datasourceType === 'dic') {
            api = getDicDetailList;
          }
          if (props.datasourceType === 'datasource') {
            api = getDatasourceData;
          }
          if (props.datasourceType === 'api') {
            options.value = await apiConfigFunc(
              props.apiConfig,
              isCamelCase,
              formModel,
              props.index,
            );
          }
          if (props.datasourceType === 'pageDesignApi') {
            //apiConfigPageDesignFunc
            options.value = await apiConfigFunc(props.apiConfig);
          }
        } else {
          api = props.api;
        }

        if (!api || !isFunction(api)) return;
        options.value = [];

        try {
          loading.value = true;
          const res = await api(props.params);
          isFirstLoad.value = false;

          if (Array.isArray(res)) {
            options.value = res;

            emitChange();
            return;
          }
          if (props.resultField) {
            options.value = get(res, props.resultField) || [];
          }
          emitChange();
        } catch (error) {
          console.warn(error);
        } finally {
          loading.value = false;
        }
      }

      const handleFilterOption = (input: string, option) => {
        const label = option.label || option.name;
        return label.toLowerCase().includes(input.toLowerCase());
      };

      async function handleFetch(visible) {
        if (visible) {
          if (props.alwaysLoad) {
            await fetch();
          } else if (!props.immediate && unref(isFirstLoad)) {
            await fetch();
            isFirstLoad.value = false;
          }
        }
      }

      function emitChange() {
        emit('options-change', unref(getOptions));
      }

      function handleChange(value, ...args) {
        const val = (Array.isArray(value) ? value.join(',') : value) || '';
        emitData.value = args;
        emit('update:value', val);
        emit('change', val, ...args);
        selectedValue.value =
          props.value === undefined
            ? val
            : (((typeof props.value === 'string' && !!props.value
                ? props.value?.split(',')
                : props.value) || undefined) as any);
      }
      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 || props.width;
      });
      const height = computed(() => {
        return props.style?.height || '32px';
      });
      const multipleheight = computed(() => {
        return `calc(${height.value} - 6px)`;
      });
      const multiplelineheight = computed(() => {
        return `calc(${height.value} - 8px)`;
      });
      const textalign = computed(() => {
        return props.style ? props.style['text-align'] : 'left';
      });
      return {
        selectedValue,
        attrs,
        getOptions,
        loading,
        t,
        handleFetch,
        handleChange,
        handleFilterOption,
        selectMode,
        customwidth,
        textalign,
        fontstyle,
        fontsize,
        border,
        backgroundcolor,
        color,
        height,
        multiplelineheight,
        multipleheight,
      };
    },
  });
</script>
<style scoped lang="less">
  .customStyle {
    width: v-bind(customwidth);

    &.ant-select-disabled {
      :deep(.ant-select-selector) {
        background-color: v-bind(backgroundcolor);
      }
    }

    :deep(.ant-select-selector) {
      border: v-bind(border);
      background-color: v-bind(backgroundcolor);
      min-height: v-bind(height);
      font-size: v-bind(fontsize);
      font-style: v-bind(fontstyle);
    }

    :deep(.ant-select-selection-item) {
      color: v-bind(color);
      line-height: v-bind(height);
      text-align: v-bind(textalign);
    }

    :deep(.ant-select-selection-placeholder) {
      line-height: v-bind(height);
      text-align: v-bind(textalign);
    }

    &.ant-select-multiple {
      :deep(.ant-select-selection-item) {
        height: v-bind(multipleheight);
        line-height: v-bind(multiplelineheight);
      }
    }
  }
</style>
