<template>
  <div class="text-left">
    <a-cascader
      :class="[style && Object.keys(style).length > 0 ? 'customStyle' : '']"
      :style="style && Object.keys(style).length > 0 ? {} : { width: width }"
      v-model:value="selected"
      :options="options"
      :load-data="loadData"
      :change-on-select="selectedConfig === 'any'"
      @change="handleChange"
      :displayRender="handleRenderDisplay"
      :allowClear="allowClear"
      :placeholder="placeholder"
      :disabled="disabled"
      :size="size"
      @blur="handleBlur"
    >
      <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-cascader>
  </div>
</template>
<script lang="ts">
  import { defineComponent, PropType, ref, inject, watch, computed } from 'vue';
  import { Cascader } from 'ant-design-vue';
  import { propTypes } from '/@/utils/propTypes';
  import { isFunction } from '/@/utils/is';
  import { get, omit } from 'lodash-es';
  import { LoadingOutlined } from '@ant-design/icons-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { apiConfigFunc } from '/@/utils/event/design';

  interface Option {
    value: string;
    label: string;
    loading?: boolean;
    isLeaf?: boolean;
    children?: Option[];
  }
  export default defineComponent({
    name: 'ApiCascader',
    components: {
      LoadingOutlined,
      [Cascader.name]: Cascader,
    },
    props: {
      value: {
        type: [Array, String],
      },
      api: {
        type: Function as PropType<(arg?: Recordable) => Promise<Option[]>>,
        default: null,
      },
      numberToString: propTypes.bool,
      resultField: propTypes.string.def(''),
      labelField: propTypes.string.def('label'),
      valueField: propTypes.string.def('value'),
      childrenField: propTypes.string.def('children'),
      asyncFetchParamKey: propTypes.string.def('parentCode'),
      immediate: propTypes.bool.def(true),
      // 是否有下级，默认是
      isLeaf: {
        type: Function as PropType<(arg: Recordable) => boolean>,
        default: null,
      },
      displayRenderArray: {
        type: Array,
      },
      placeholder: String,
      separator: String,
      showFormat: String,
      selectedConfig: String,
      allowClear: Boolean,
      disabled: Boolean,
      apiConfig: {
        type: Object,
        default: () => {},
      },
      size: String,
      style: Object,
      width: String,
    },
    emits: ['change', 'defaultChange', 'update:value', 'blur'],
    setup(props, { emit }) {
      const apiData = ref<any[]>([]);
      const options = ref<Option[]>([]);
      const loading = ref<boolean>(false);
      const { t } = useI18n();

      const formModel = inject<any>('formModel', null);
      const isCamelCase = inject<boolean>('isCamelCase', false);
      const selected = ref();
      watch(
        apiData,
        (data) => {
          const opts = generatorOptions(data);
          options.value = opts;
        },
        { deep: true },
      );

      watch(
        () => props.value,
        (val) => {
          selected.value = Array.isArray(val) ? val : !!val ? val.toString().split(',') : [];
        },
        {
          deep: true,
          immediate: true,
        },
      );

      function generatorOptions(options: any[]): Option[] {
        const { labelField, valueField, numberToString, childrenField, isLeaf } = props;
        return options.reduce((prev, next: Recordable) => {
          if (next) {
            const value = next[valueField];
            const item = {
              ...omit(next, [labelField, valueField]),
              label: next[labelField],
              value: numberToString ? `${value}` : value,
              isLeaf: isLeaf && typeof isLeaf === 'function' ? isLeaf(next) : false,
            };
            const children = Reflect.get(next, childrenField);
            if (children) {
              Reflect.set(item, childrenField, generatorOptions(children));
            }
            prev.push(item);
          }
          return prev;
        }, [] as Option[]);
      }

      async function loadData(selectedOptions: Option[]) {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;

        const api = props.api;
        if (!api || !isFunction(api)) return;
        try {
          const res = await api({
            [props.asyncFetchParamKey]: Reflect.get(targetOption, 'value'),
          });
          if (Array.isArray(res)) {
            const children = generatorOptions(res);
            targetOption.children = children;
            return;
          }
          if (props.resultField) {
            const children = generatorOptions(get(res, props.resultField) || []);
            targetOption.children = children;
          }
        } catch (e) {
          console.error(e);
        } finally {
          targetOption.loading = false;
        }
      }

      watch(
        () => props.apiConfig,
        async () => {
          options.value = await apiConfigFunc(props.apiConfig, isCamelCase, formModel);
        },
        {
          immediate: true,
          deep: true,
        },
      );

      function handleChange(keys, args) {
        const emitValue = keys ? keys.join(',') : '';
        emit('defaultChange', keys, args);
        emit('update:value', emitValue);
        emit('change', emitValue);
      }

      function handleBlur() {
        emit('blur');
      }

      function handleRenderDisplay({ labels, selectedOptions }) {
        if (selected.value.length === selectedOptions.length) {
          if (props.showFormat === 'all') {
            return labels.join(` ${props.separator} `);
          } else {
            return labels[labels.length - 1];
          }
        }
        if (props.displayRenderArray && props.displayRenderArray?.length) {
          return props.displayRenderArray.join(` ${props.separator} `);
        }
        return '';
      }
      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 textalign = computed(() => {
        return props.style ? props.style['text-align'] : 'left';
      });
      return {
        selected,
        options,
        loading,
        t,
        handleChange,
        handleBlur,
        loadData,
        handleRenderDisplay,
        customwidth,
        textalign,
        fontstyle,
        fontsize,
        border,
        backgroundcolor,
        color,
        height,
      };
    },
  });
</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);
      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);
    }
  }
</style>
