<template>
  <div>
    <CustomTextModal v-if="type == CustomButtonModalType.Modal" :info="props">
      <a-button
        :type="buttonStyleType ? (buttonStyleType == 'default' ? '' : buttonStyleType) : 'primary'"
        :style="{
          height: buttonHeight ? buttonHeight + 'px' : '',
          width: buttonWidth ? buttonWidth + 'px' : '',
          margin: margin,
        }"
        :size="size"
        :disabled="disabled"
        :class="buttonStyleType == 'dashed' ? 'ant-dashed-dangerous' : ''"
        :loading="loading"
      >
        <Icon :icon="prefix" v-if="prefix" />
        {{ name }}
        <Icon :icon="suffix" v-if="suffix" /> </a-button
    ></CustomTextModal>
    <a-button
      v-else
      :type="buttonStyleType ? (buttonStyleType == 'default' ? '' : buttonStyleType) : 'primary'"
      :style="{
        height: buttonHeight ? buttonHeight + 'px' : '',
        width: buttonWidth ? buttonWidth + 'px' : '',
        margin: margin,
      }"
      :size="size"
      :disabled="disabled"
      @click="showDialog"
      :class="buttonStyleType == 'dashed' ? 'ant-dashed-dangerous' : ''"
      :loading="loading"
    >
      <Icon :icon="prefix" v-if="prefix" />
      {{ name }}
      <Icon :icon="suffix" v-if="suffix" />
    </a-button>

    <FormItemRest>
      <MultipleSelect
        ref="MultipleSelectRef"
        v-model:multipleDialog="multipleDialog"
        :popupType="popType"
        :dataSourceOptions="dataSourceOptions"
        :params="params"
        v-model:value="defaultVal"
        v-model:popupValue="popupValue"
        :labelField="labelField"
        :valueField="valueField"
        :datasourceType="datasourceType"
        :dicOptions="dicOptions"
        :apiConfig="apiConfig"
        :tableColumns="tableColumns"
        v-model:selectedDataSource="selectedDataSourceVal"
        :mainKey="mainKey"
        :subTableIndex="index"
        @get-list="getList"
        @submit="handleSubmit"
      />
    </FormItemRest>
  </div>
</template>
<script lang="ts" setup>
  import { ref, nextTick, inject, onMounted } from 'vue';
  import { Form } from 'ant-design-vue';
  import { Icon } from '/@/components/Icon';
  import { CustomButtonModalType } from '/@/enums/userEnum';
  import CustomTextModal from '/@/components/Form/src/components/CustomTextModal.vue';

  import MultipleSelect from '../../MultiplePopup/src/components/MultipleSelect.vue';
  import { camelCaseString, isValidJSON } from '/@/utils/event/design';
  import { apiConfigFunc } from '/@/utils/event/design';

  const props = defineProps({
    value: { type: String },
    labelField: { type: String, default: 'label' },
    valueField: { type: String, default: 'value' },
    placeholder: { type: String },
    addonBefore: { type: String },
    addonAfter: { type: String },
    buttonStyleType: { type: String },
    name: String,
    size: String,
    buttonWidth: String,
    buttonHeight: String,
    prefix: String,
    suffix: String,
    disabled: Boolean,
    isSpecial: Boolean,
    buttonType: [String, Number],
    params: { type: [Array, Object, String, Number] },
    dataSourceOptions: { type: Array },
    dicOptions: { type: Array },
    tableColumns: { type: Array },
    //数据来源 默认为空  如果不为空 则参数 api
    datasourceType: String,
    apiConfig: { type: Object },
    mainKey: String,
    index: Number,
    loading: {
      type: Boolean,
      default: false,
    },
    margin: String,
    type: CustomButtonModalType,
    event: Array,
    modal: null,
  });
  const FormItemRest = Form.ItemRest;
  const formModel = inject<any>('formModel', null);
  const isCamelCase = inject<boolean>('isCamelCase', false);
  const multipleDialog = ref<boolean>(false);
  const popupValue = ref('');
  const defaultVal = ref<string | undefined>('');
  const selectedDataSourceVal = ref<any[]>([]);
  const MultipleSelectRef = ref();
  const dataSourceList = ref<string[]>([]);
  const popType = ref('');
  const emit = defineEmits(['change']);

  onMounted(() => {
    if (props.buttonType && 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];
            }
          }
        });
      });
      nextTick(() => {
        getSubDatasourceList();
      });
    }
  });
  const getList = (list) => {
    dataSourceList.value = list;
  };

  const showDialog = async () => {
    if (props.isSpecial) {
      multipleDialog.value = true;
      popType.value = props.buttonType == 1 ? 'associate' : 'button';
    }
    if (!props.buttonType) {
      await apiConfigFunc(props.apiConfig, isCamelCase, formModel, props.index);
    }
  };

  const handleSubmit = () => {
    emit('change');
  };

  const getSubDatasourceList = async () => {
    let showValueArr: string[] = [];
    await MultipleSelectRef.value?.getDatasourceList();

    selectedDataSourceVal.value = [];
    defaultVal.value = props.value;
    const selectedArr = props.value?.split(',');
    dataSourceList.value?.map((item) => {
      selectedArr?.map((selected) => {
        if (item[props.valueField] === selected) {
          selectedDataSourceVal.value?.push(item);
        }
      });
    });

    showValueArr = selectedDataSourceVal.value?.map((item: any) => {
      return item[props.labelField!];
    });

    popupValue.value = showValueArr.length ? showValueArr.join(',') : props.value!;
  };
</script>
