<template>
  <a-form-item :label="t('数据来源')">
    <a-radio-group
      button-style="solid"
      v-model:value="info.options.datasourceType"
      size="small"
      :disabled="disabled"
      @change="handleDatasourceChange"
    >
      <a-radio-button
        value="staticData"
        v-if="
          info.type === 'radio' ||
          info.type === 'checkbox' ||
          info.type === 'select' ||
          info.type === 'auto-complete'
        "
      >
        {{ t('静态数据') }}
      </a-radio-button>
      <a-radio-button value="api">API</a-radio-button>
      <!-- <a-radio-button value="datasource">数据源</a-radio-button> -->
      <a-radio-button value="dic">{{ t('数据字典') }}</a-radio-button>
    </a-radio-group>
  </a-form-item>
  <div v-if="info.options.datasourceType === 'staticData'">
    <StaticData
      :disabled="disabled"
      :options="info.options"
      @handleOptionsRemove="
        (index) => {
          emit('handleOptionsRemove', index);
        }
      "
      @handleInsertOption="handleInsertOption"
      @handleDefaultSelect="
        (val) => {
          info.options.defaultSelect = val;
        }
      "
      :type="info.type === 'checkbox' ? 'checkbox' : 'radio'"
    />
  </div>
  <div v-if="info.options.datasourceType === 'datasource'">
    <a-form-item :label="t('数据选项')">
      <DatasourceSelect v-model:value="info.options.datasourceId" @change="handleFieldChange" />
    </a-form-item>
    <a-form-item :label="t('显示字段')">
      <a-select v-model:value="info.options.labelField" :placeholder="t('请选择显示字段')">
        <a-select-option v-for="(item, idx) in fieldOptions" :value="item" :key="idx" />
      </a-select>
    </a-form-item>
    <a-form-item :label="t('保存字段')">
      <a-select v-model:value="info.options.valueField" :placeholder="t('请选择保存字段')">
        <a-select-option v-for="(item, idx) in fieldOptions" :value="item" :key="idx" />
      </a-select>
    </a-form-item>
  </div>
  <div v-if="info.options.datasourceType === 'api'">
    <a-form-item :label="t('接口配置')">
      <a-input
        v-model:value="info.options.apiConfig.path"
        :placeholder="t('点击进行接口配置')"
        :disabled="disabled"
        @click="apiConfigDialog = true"
      >
        <template #suffix>
          <Icon icon="ant-design:ellipsis-outlined" />
        </template>
      </a-input>
    </a-form-item>
  </div>
  <div v-if="info.options.datasourceType === 'dic'">
    <a-form-item :label="t('数据选项')">
      <DicTreeSelect
        v-model:value="info.options.itemId"
        @change="handleDicChange"
        :disabled="disabled"
      />
    </a-form-item>
  </div>
  <a-form-item
    :label="formLabel"
    v-if="
      info.type === 'associate-popup' ||
      info.type === 'multiple-popup' ||
      info.type === 'associate-select' ||
      (info.type === 'button' && info.options.isSpecial && info.options.buttonType == 1)
    "
  >
    <a-input :value="configText" :placeholder="t('点击进行配置')" @click="showConfigDialog">
      <template #suffix>
        <Icon icon="ant-design:ellipsis-outlined" />
      </template>
    </a-input>
  </a-form-item>
  <DataSourceAssoConfig
    v-if="dataSourceAssoDia"
    v-model:dataSourceAssoDia="dataSourceAssoDia"
    v-model:dataSourceOptions="info.options.dataSourceOptions"
    :selectedList="list"
    :type="info.type"
  />
  <ApiAssoConfig
    v-if="apiAssoDia"
    :disabled="disabled"
    v-model:apiAssoDia="apiAssoDia"
    v-model:apiConfig="info.options.apiConfig"
    :selectedList="list"
    :type="info.type"
  />
  <DicAssoConfig
    v-if="dicAssoDia"
    v-model:dicAssoDia="dicAssoDia"
    v-model:dicOptions="info.options.dicOptions"
    :selectedList="list"
    :type="info.type"
    :disabled="disabled"
  />
  <ApiConfig
    v-if="apiConfigDialog"
    :isSubForm="info.isSubFormChild"
    v-model:apiConfigDialog="apiConfigDialog"
    v-model:apiConfig="info.options.apiConfig"
    :formItem="info"
    :hasExample="hasExample"
    :title="t('API配置')"
  />
</template>

<script lang="ts" setup>
  import { watch, ref, inject, computed } from 'vue';
  import DataSourceAssoConfig from './DataSourceAssoConfig.vue';
  import ApiAssoConfig from './ApiAssoConfig.vue';
  import DicAssoConfig from './DicAssoConfig.vue';
  import StaticData from './StaticData.vue';
  import { getDatasourceColumn } from '/@/api/system/datasource';
  import { Icon } from '/@/components/Icon';
  import { DatasourceSelect } from '/@/components/DataSourceSelect';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { DicTreeSelect } from '/@/components/DicTreeSelect';

  import { message } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const props = defineProps({
    data: { type: Object },
    disabled: { type: Boolean, default: () => false },
    hasExample: { type: Boolean, default: () => true },
  });
  const { widgetForm, widgetFormSelect } = inject('state') as any; //整个表单json配置

  const emit = defineEmits(['update:data', 'handleOptionsRemove']);
  const info = ref<any>(props.data);
  const dataSourceAssoDia = ref<boolean>(false);
  const apiAssoDia = ref<boolean>(false);
  const dicAssoDia = ref<boolean>(false);
  const apiConfigDialog = ref<boolean>(false);
  const list = ref<any[]>([]);
  const selectedList = ref<any[]>([]);
  const selectedSingleList = ref<any[]>([]); //单表组件内部引用列表

  const fieldOptions = ref<string[]>([]);
  const notBindFieldConfig = ['select', 'radio', 'checkbox', 'associate-select'];
  const noAssociateComponents = [
    'multiple-popup',
    'associate-popup',
    'associate-select',
    'form',
    'tab',
    'card',
    'grid',
    'one-for-one',
    'button',
  ];

  watch(
    () => props.data,
    (val) => {
      info.value = val;
    },
    {
      immediate: true,
      deep: true,
    },
  );
  watch(
    info.value,
    (val) => {
      emit('update:data', val);
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const getSelectedList = (list, isOneForOne = false) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getSelectedList(child.list, isOneForOne);
        }
      } else if (item.type == 'table-layout') {
        for (const child of item.layout!) {
          for (const sub of child.list) {
            getSelectedList(sub.children, isOneForOne);
          }
        }
      } else if (item.type === 'one-for-one') {
        getSelectedList(item.children, true);
      } else if (item.type === 'form') {
        if (item.bindTable === widgetFormSelect.bindTable) {
          selectedList.value = item.children.filter((child: any) => {
            return !noAssociateComponents.includes(child.type);
          });
        }
      } else {
        if (!noAssociateComponents.includes(item.type)) {
          if (isOneForOne) item.isSingleFormChild = true;
          selectedList.value.push(item);
        }
      }
    });
  };

  watch(
    () => widgetForm.list,
    () => {
      if (widgetForm.list.length) {
        selectedSingleList.value = [];
        selectedList.value = [];
        getSelectedList(widgetForm.list);
        list.value = selectedList.value;
      }
    },
    {
      immediate: true,
      deep: true,
    },
  );

  const configText = computed(() => {
    const datasourceType = info.value.options.datasourceType;
    const dicOptions = info.value.options.dicOptions;
    const outputParams = info.value.options.apiConfig?.outputParams;
    if (
      (datasourceType === 'dic' && dicOptions?.length) ||
      (datasourceType === 'api' && outputParams?.length)
    ) {
      return t('已配置');
    } else {
      return '';
    }
  });
  const formLabel = computed(() => {
    return info.value?.type === 'multiple-popup' ? t('显示配置') : t('联想配置');
  });

  const handleDatasourceChange = () => {
    info.value.options.params = null;
    info.value.options.labelField = 'label';
    info.value.options.valueField = 'value';

    if (info.value.options.datasourceType === 'dic') {
      info.value.options.params = info.value.options.itemId
        ? { itemId: info.value.options.itemId }
        : null;
      info.value.options.labelField = 'name';
    }
    if (info.value.options.datasourceType !== 'staticData') {
      if (info.value.type == 'multiple-popup' || info.value.type == 'checkbox') {
        info.value.options.defaultTempValue = [];
      }
      info.value.options.defaultSelect = null;
    } else {
      info.value.options.defaultSelect = info.value.options.staticOptions[0].value;
    }
  };
  const handleInsertOption = () => {
    const index = info.value.options.staticOptions.length + 1;
    info.value.options.staticOptions.push({
      key: index,
      label: `Option ${index}`,
      value: `Option ${index}`,
    });
  };
  const handleFieldChange = async (id: string) => {
    if (!id) return;
    info.value.options.labelField = undefined;
    info.value.options.valueField = undefined;
    info.value.options.dataSourceOptions = [];
    info.value.options.params = id;
    fieldOptions.value = await getDatasourceColumn(id);

    if (fieldOptions.value.length) {
      fieldOptions.value.map((item, index) => {
        let options = {};
        if (notBindFieldConfig.includes(info.value.type)) {
          options = { key: index + 1, name: item };
        } else {
          options = {
            key: index + 1,
            name: item,
            tableTitle: item,
            bindField: '',
            show: true,
            width: '150',
          };
        }
        info.value.options.dataSourceOptions.push(options);
      });
    }
  };

  const handleDicChange = (val) => {
    info.value.options.params = { itemId: val };
  };
  const showConfigDialog = () => {
    if (info.value.options.datasourceType === 'datasource') {
      if (info.value.type === 'associate-popup' && !selectedList.value.length) {
        message.error(t('请保证存在一个或一个以上可联想绑定数据的组件'));
      } else {
        dataSourceAssoDia.value = true;
      }
    } else if (info.value.options.datasourceType === 'api') {
      apiAssoDia.value = true;
    } else if (info.value.options.datasourceType === 'dic') {
      dicAssoDia.value = true;
    }
  };
</script>
