<template>
  <div class="flex items-center">
    <a-form-item>
      <RadioGroup v-model:value="radioValue" :options="radioData" @change="handleRadioChange" />
    </a-form-item>
    <div v-if="checkboxData.length" class="flex items-center">
      <div class="mb-2 mr-1">(</div>
      <a-form-item>
        <CheckboxGroup
          v-model:value="checkboxValue"
          :options="checkboxData"
          @change="handleCheckboxChange"
          :disabled="checkboxDisabled"
        />
      </a-form-item>
      <a-form-item>
        <a-input
          :style="{ width: '150px', border: 0, borderBottom: '1px solid #ccc' }"
          :placeholder="props.placeholder || '请输入'"
          v-model:value="inputValue"
          :disabled="disabled"
          @change="handleInputChange"
        />
      </a-form-item>
      <div class="mb-2 ml-1">)</div>
    </div>
    <a-form-item v-else>
      <a-input
        :placeholder="props.placeholder || '请输入'"
        v-model:value="inputValue"
        @change="handleInputChange"
      />
    </a-form-item>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, watch, ref, onMounted, unref } from 'vue';
  import { RadioGroup, CheckboxGroup } from 'ant-design-vue';
  import { isFunction } from '/@/utils/is';
  import { get } from 'lodash-es';
  import { propTypes } from '/@/utils/propTypes';
  import { useDebounceFn } from '@vueuse/core';

  export default defineComponent({
    name: 'ApiComplex',
    components: { RadioGroup, CheckboxGroup },
    props: {
      api: { type: Function as PropType<(arg?: Recordable) => Promise<Recordable>> },
      params: { type: Object },
      immediate: { type: Boolean, default: true },
      resultField: propTypes.string.def(''),
      placeholder: { type: String },
    },
    emits: ['change'],
    setup(props, { attrs, emit }) {
      const radioData = props.params?.radioData || [
        { label: '无', value: 0 },
        { label: '有', value: 1 },
      ];
      const checkboxData = ref([]);
      const getAttrs = computed(() => {
        return {
          ...(props.api ? { checkboxData: unref(checkboxData) } : {}),
          ...attrs,
        } as any;
      });
      // console.log('🚀 ~ file: ApiComplex.vue:82 ~ attrs:', attrs);
      // console.log('🚀 ~ file: ApiComplex.vue:82 ~ props:', props);
      const radioValue = ref(0);
      const inputValue = ref('');
      const checkboxValue = ref([]);
      const checkboxDisabled = computed(() => {
        return radioValue.value ? false : true;
      });
      const disabled = computed(() => {
        if (checkboxData.value.length) {
          return checkboxValue.value &&
            checkboxValue.value.filter(ele => {
              return ele == '-1';
            }).length
            ? false
            : true;
        } else {
          return radioValue.value ? false : true;
        }
      });
      const isFirstLoaded = ref<Boolean>(false);
      const loading = ref(false);
      watch(
        () => attrs.formValues,
        (v: any) => {
          // console.log('🚀 ~ file: ApiComplex.vue:102 ~ setup ~ v:', v);
          const field = v.field;
          const defaultValue = v?.model?.[field];
          radioValue.value = defaultValue?.bool;
          inputValue.value = defaultValue?.remark;
          checkboxValue.value = defaultValue?.dictValues;
        },
      );
      watch(
        () => props.params?.dictCode,
        () => {
          !unref(isFirstLoaded) && fetch();
        },
        { deep: true },
      );

      watch(
        () => props.immediate,
        v => {
          v && !isFirstLoaded.value && fetch();
        },
      );

      onMounted(() => {
        props.immediate && fetch();
      });

      async function fetch() {
        const api = props.api;
        if (!api || !isFunction(api)) return;
        checkboxData.value = [];
        try {
          loading.value = true;
          const res = await api(props.params);
          if (Array.isArray(res)) {
            checkboxData.value = res;
            checkboxData.value.push({
              label: '其他',
              value: '-1',
            });
            return;
          }
          if (props.resultField) {
            checkboxData.value = get(res, props.resultField) || [];
            checkboxData.value.push({
              label: '其他',
              value: '-1',
            });
          }
        } catch (error) {
          console.warn(error);
        } finally {
          loading.value = false;
        }
      }

      function emitChange() {
        debouncedFn();
      }

      // 防抖
      const debouncedFn = useDebounceFn(() => {
        const data = {
          bool: radioValue.value,
          boolText: radioData,
          dictValues: checkboxValue.value,
          remark: inputValue.value,
          dictCode: props.params?.dictCode,
        };
        emit('change', data);
      }, 1000);

      // 单选改变
      function handleRadioChange(e) {
        checkboxValue.value = e.target.value ? checkboxValue.value : [];
        radioValue.value = e.target.value;
        emitChange();
      }

      // 复选改变
      function handleCheckboxChange(e) {
        inputValue.value = e.includes('-1') ? inputValue.value : '';
        checkboxValue.value = e;
        emitChange();
      }

      // 输入改变
      function handleInputChange(e) {
        inputValue.value = e.target.value || '';
        emitChange();
      }

      return {
        getAttrs,
        loading,
        props,
        radioData,
        radioValue,
        checkboxData,
        checkboxValue,
        inputValue,
        disabled,
        checkboxDisabled,
        handleRadioChange,
        handleCheckboxChange,
        handleInputChange,
      };
    },
  });
</script>
