<template>
  <a-tabs>
    <a-tab-pane :key="item.key" :tab="item.title" v-for="item in props.apiParams">
      <a-table
        :dataSource="item.tableInfo"
        :columns="apiConfigColumns"
        :pagination="false"
        :scroll="{ y: '400px' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'assignmentType'">
            <a-select
              v-model:value="record.assignmentType"
              style="width: 100%"
              :placeholder="t('请选择赋值类型')"
              @change="
                () => {
                  record.config = null;
                  record.value = '';
                }
              "
              allowClear
            >
              <a-select-option :value="bind.value" v-for="bind in bindType" :key="bind.value">
                {{ bind.label }}
              </a-select-option>
            </a-select>
          </template>
          <template v-else-if="column.key === 'value'">
            <!-- 组件数据 -->
            <a-tree-select
              v-if="record.assignmentType === 'formData'"
              v-model:value="record.value"
              show-search
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :placeholder="t('点击选择表单数据')"
              allow-clear
              tree-default-expand-all
              :tree-data="data.dataInfo"
              @select="(_, node) => handleSelect(node, record)"
            />
            <a-input
              v-else
              v-model:value="record.value"
              :placeholder="record.type ? t('请填写值') : t('请先选择赋值类型后再配置值')"
            />
          </template>
        </template>
      </a-table>
    </a-tab-pane>
  </a-tabs>
</template>

<script setup lang="ts">
  // import { TreeProps } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { ApiParams } from '/@/components/ApiConfig/src/interface';
  import { message } from 'ant-design-vue';
  import { isValidJSON } from '/@/utils/event/design';
  import { inject, onMounted, reactive } from 'vue';
  const generatorConfig = inject('generatorConfig') as any;

  const { t } = useI18n();
  const props = withDefaults(
    defineProps<{
      apiParams: Array<ApiParams>;
      updateIds?: Array<string>;
    }>(),
    {
      apiParams: () => {
        return [];
      },
    },
  );
  let data = reactive({
    dataInfo: [
      {
        title: t('表单数据'),
        value: 'formData',
        disabled: true,
        children: [],
      },
      {
        title: '当前信息',
        value: 'currentInfo',
        disabled: true,
        children: [
          {
            title: t('当前人员名称'),
            value: '3-name',
          },
          {
            title: t('当前人员ID'),
            value: '3-id',
          },
          {
            title: t('当前人员编码'),
            value: '3-code',
          },
          {
            title: t('当前人员手机号'),
            value: '3-mobile',
          },
          {
            title: t('当前人员所属组织架构名称'),
            value: '3-departmentName',
          },
          {
            title: t('当前人员所属组织架构ID'),
            value: '3-departmentId',
          },
          {
            title: t('当前人员岗位ID'),
            value: '3-postId',
          },
          {
            title: t('当前人员角色ID'),
            value: '3-roles.id',
          },
        ],
      },
    ] as any[],
  });
  let bindType = [
    {
      label: t('值'),
      value: 'value',
    },
    {
      label: t('组件数据'),
      value: 'formData',
    },
  ];
  let apiConfigColumns = [
    {
      title: t('API入参名称'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('API入参类型'),
      dataIndex: 'dataType',
      key: 'dataType',
      align: 'center',
    },
    {
      title: t('赋值类型'),
      dataIndex: 'assignmentType',
      key: 'assignmentType',
      align: 'center',
    },
    {
      title: t('赋值配置'),
      dataIndex: 'value',
      key: 'value',
      align: 'center',
    },
  ];
  onMounted(() => {
    if (generatorConfig?.formJson.list.length) {
      getSelectedList(generatorConfig?.formJson.list);
    }
  });

  const filtercomps = ['divider', 'upload', 'image', 'qrcode', 'button', 'map', 'opinion', 'title','ai-answer'];

  const getSelectedList = (list, bindTable?, key?) => {
    list?.map((item) => {
      if (['tab', 'grid', 'card'].includes(item.type)) {
        for (const child of item.layout!) {
          getSelectedList(child.list);
        }
      } else if (item.type == 'one-for-one') {
        getSelectedList(item.children, item.bindTable, item.key);
      } else if (item.type !== 'form' && !filtercomps.includes(item.type)) {
        let params: string[] = [];
        if (item.options.datasourceType == 'api' && item.options.apiConfig.apiParams) {
          item.options.apiConfig.apiParams.forEach((p) => {
            p.tableInfo &&
              p.tableInfo.forEach((o) => {
                const value = isValidJSON(o.value);
                if (value) params.push(value.fieldKey);
              });
          });
        }
        let bindField = item.bindField;
        if (item.type == 'time-range' || item.type == 'date-range') {
          bindField = item.bindStartTime + ',' + item.bindEndTime;
        }
        let obj = {
          bindField: bindField,
          bindTable: bindTable,
          tableKey: key,
          fieldKey: item.key,
        };
        data.dataInfo[0].children.push({
          title: item.label,
          value: JSON.stringify(obj),
        });
      }
    });
  };

  const handleSelect = ({ value }, record) => {
    if (!value) {
      message.error(t('请先选择该组件的绑定表及绑定字段'));
      record.value = null;
    }
  };
</script>

<style scoped></style>
