<template>
  <div class="step1-box">
    <div class="step1">
      <div class="flex justify-between mb-3">
        <NodeHead nodeName="输入参数" />
        <a-button type="primary" @click="addInParams">添加参数</a-button>
      </div>
      <a-table
        :columns="intableColumns"
        :data-source="intableData"
        :pagination="false"
        :defaultExpandAllRows="true"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'name'">
            <a-input v-model:value="record.name" :placeholder="t('请填写参数名称')" />
          </template>
          <template v-else-if="column.dataIndex === 'type'">
            <a-select v-model:value="record.type" style="width: 180px" :options="options1" />
          </template>
          <template v-else-if="column.dataIndex === 'value'">
            <a-input
              v-if="record.type == 'value'"
              v-model:value="record.value"
              :placeholder="t('请填写参数值')"
            />
            <a-input
              v-else-if="record.type == 'api'"
              v-model:value="record.apiConfig.path"
              :placeholder="t('点击配置API')"
              @click="showApiConfig(index)"
            >
              <template #suffix>
                <Icon icon="ant-design:ellipsis-outlined" />
              </template>
            </a-input>
            <div v-else>请选择参数类型</div>
          </template>
          <template v-else-if="column.dataIndex === 'component'">
            <a-select v-model:value="record.component" style="width: 260px" :options="options" />
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button danger type="link" @click="deleteInData(index)">删除</a-button>
          </template>
        </template>
      </a-table>

      <div class="flex justify-between mb-3 mt-5">
        <NodeHead nodeName="输出参数" />
        <a-button type="primary" @click="addParams">添加参数</a-button>
      </div>
      <a-table
        :columns="tableColumns"
        :data-source="tableData"
        :pagination="false"
        :defaultExpandAllRows="true"
      >
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'name'">
            <a-input v-model:value="record.name" :placeholder="t('请填写参数名称')" />
          </template>
          <template v-else-if="column.dataIndex === 'component'">
            <a-select v-model:value="record.component" style="width: 260px" :options="options" />
          </template>

          <template v-else-if="column.dataIndex === 'action'">
            <a-button danger type="link" @click="deleteData(index)">删除</a-button>
          </template>
        </template>
      </a-table>
    </div>
    <ApiConfig
      v-if="apiConfigDialog"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="intableData[curTableidx].apiConfig"
      :title="t('API配置')"
      isQrcode
    />
  </div>
</template>
<script lang="ts" setup>
  import { inject, onMounted, ref } from 'vue';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { Icon } from '/@/components/Icon';
  import { notification, type SelectProps } from 'ant-design-vue';
  const { t } = useI18n();
  const tableData = ref([]);
  const intableData = ref<any>([]);
  const apiConfigDialog = ref<boolean>(false);
  const curTableidx = ref(0);
  const options1 = ref<SelectProps['options']>([
    {
      value: 'value',
      label: '值',
    },
    {
      value: 'api',
      label: 'API',
    },
  ]);
  const intableColumns = [
    {
      title: t('参数名称'),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: t('类型'),
      dataIndex: 'type',
      align: 'center',
      width: 200,
    },
    {
      title: t('参数默认值（无传入值时启用）'),
      dataIndex: 'value',
      align: 'center',
    },
    {
      title: t('绑定组件'),
      dataIndex: 'component',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      align: 'center',
    },
  ];
  const tableColumns = [
    {
      title: t('参数名称'),
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: t('绑定组件'),
      dataIndex: 'component',
      align: 'center',
    },
    {
      title: t('操作'),
      dataIndex: 'action',
      align: 'center',
    },
  ];

  defineEmits(['register']);
  const generatorConfig = inject<GeneratorConfig>('generatorConfig');
  const options = ref([]);
  onMounted(() => {
    options.value = [];
    getComponents(generatorConfig?.formJson?.list);
    tableData.value = generatorConfig.outParams;
    intableData.value = generatorConfig.innerParams;
  });
  function getComponents(list) {
    list.forEach((item) => {
      if (['grid', 'card', 'tab'].includes(item.type)) {
        item.layout.forEach((lay) => {
          getComponents(lay.list);
        });
      } else if (item.type == 'one-for-one') {
        getComponents(item.children);
      } else if (item.type == 'table-layout') {
        item.layout.forEach((lay) => {
          lay.list.forEach((chil) => {
            getComponents(chil.children);
          });
        });
      } else if (!['form', 'sun-form'].includes(item.type)) {
        if (item.bindField) {
          options.value.push({
            label: item.label,
            value: JSON.stringify({ table: item.bindTable, field: item.bindField }),
          });
        } else if (['time-range', 'date-range'].includes(item.type)) {
          options.value.push({
            label: item.label + '开始时间',
            value: JSON.stringify({ table: item.bindTable, field: item.bindStartTime }),
          });
          options.value.push({
            label: item.label + '结束时间',
            value: JSON.stringify({ table: item.bindTable, field: item.bindEndTime }),
          });
        }
      }
    });
  }
  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    const inarray = findDuplicates(intableData.value);
    const outarray = findDuplicates(tableData.value);

    if (inarray.length > 0 || outarray.length > 0) {
      let msg = t(
        `${inarray.length > 0 ? '输入参数名称' + inarray.join(',') + '重复;' : ''}\n${
          outarray.length > 0 ? '输出参数名称' + outarray.join(',') + '重复;' : ''
        }`,
      );
      notification.warning({
        title: t('提示'),
        message: msg,
      });
      return false;
    }
    generatorConfig.innerParams = intableData.value;
    generatorConfig.outParams = tableData.value;
    return true;
  };
  function findDuplicates(arr) {
    let seen = new Set();
    let duplicates: string[] = [];

    arr.forEach((item) => {
      if (seen.has(item.name)) {
        duplicates.push(item.name);
      } else {
        seen.add(item.name);
      }
    });

    return duplicates;
  }
  function addParams() {
    tableData.value.push({
      name: '',
      component: '',
      mainComponent: '',
    });
  }
  function deleteData(idx) {
    tableData.value.splice(idx, 1);
  }

  const showApiConfig = (index) => {
    apiConfigDialog.value = true;
    curTableidx.value = index;
  };
  function addInParams() {
    intableData.value.push({
      name: '',
      type: '',
      value: '',
      apiConfig: {
        path: 'CodeGeneration/selection',
        method: 'GET',
        apiId: '93d735dcb7364a0f8102188ec4d77ac7',
      },
    });
  }
  function deleteInData(idx) {
    intableData.value.splice(idx, 1);
  }
  defineExpose({ validateStep });
</script>
<style lang="less" scoped>
  :deep(.ant-input-affix-wrapper) {
    height: auto;
  }
</style>
