<template>
  <div
    v-if="loading"
    class="text-center absolute left-0 right-0 m-auto"
    style="top: calc(100vh - 50%)"
    ><a-spin size="large"
  /></div>
  <div v-else class="h-full">
    <a-tabs v-model:activeKey="activeKey" size="large" class="h-full">
      <a-tab-pane key="0" :tab="t('模板配置')">
        <ListStyle v-model:value="generatorConfig!.listConfig.listStyle" />
      </a-tab-pane>
      <a-tab-pane key="1" :tab="t('查询配置')">
        <div class="h-full pt-4">
          <div class="flex items-center pb-4">
            <NodeHead :node-name="t('查询配置列表')" class="ml-10px" />
          </div>
          <div :class="prefixCls" style="max-height: calc(100% - 94px)">
            <a-table
              size="middle"
              :columns="queryColumns"
              :pagination="false"
              :data-source="generatorConfig.listConfig?.queryConfigs"
              :key="queryTableKey"
              :scroll="{ y: 'calc(100% - 56px) !important' }"
              class="search-config"
            >
              <template #headerCell="{ column }">
                <div v-if="column.key === 'sort'" class="header-cell__custom-title">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-fangxiang1" />
                  </svg>
                </div>
                <div v-else class="header-cell__custom-title">{{ column.title }}</div>
              </template>
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key !== 'action'">
                  <template v-if="column.key === 'sort'">
                    <svg class="icon queryDraggable-icon" aria-hidden="true" style="cursor: move">
                      <use xlink:href="#icon-paixu" />
                    </svg>
                  </template>
                  <template v-if="column.key === 'fieldName'">
                    <a-select
                      v-model:value="record[column.dataIndex]"
                      style="width: 100%"
                      :options="querySelectOption"
                      :placeholder="t('请选择查询项')"
                    />
                  </template>
                </template>
                <template v-if="column.key === 'action'">
                  <div class="text-[#ff8080]" @click="queryRemove(index)">{{ t('删除') }}</div>
                </template>
              </template>
            </a-table>

            <div class="mt-2 mx-10px pb-4">
              <a-button type="dashed" block @click="queryAdd">
                <PlusOutlined />
                {{ t('新增') }}
              </a-button>
            </div>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2" :tab="t('列表配置')">
        <div class="tree-left-contain">
          <CollapseContainer class="tree-left-title" :iconStyle="{ fontSize: '12px' }">
            <template #title>
              <NodeHead :node-name="t('左侧树配置')" class="ml-10px" />
            </template>
            <a-form
              :label-col="{ span: 6 }"
              :wrapper-col="{ span: 18 }"
              labelAlign="left"
              class="!px-10px"
            >
              <a-form-item
                :label="t('配置树')"
                :style="{ margin: 0 }"
                :wrapper-col="{ style: { textAlign: 'right' } }"
              >
                <a-switch
                  :disabled="isDisabled"
                  v-model:checked="generatorConfig!.listConfig!.isLeftMenu"
                  @change="changeLeftMenu"
                />
              </a-form-item>
            </a-form>
            <div v-if="generatorConfig?.listConfig?.isLeftMenu" class="tree-left-container px-10px">
              <a-form
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16, style: { textAlign: 'right' } }"
                labelAlign="left"
              >
                <a-form-item
                  :label="t('数据来源')"
                  :labelCol="{ span: 24, style: { lineHeight: '14px', paddingBottom: '10px' } }"
                  :wrapper-col="{ style: { width: '100%' } }"
                >
                  <a-radio-group
                    :disabled="isDisabled"
                    class="!flex w-full"
                    v-model:value="generatorConfig.listConfig.leftMenuConfig!.datasourceType"
                    button-style="solid"
                    size="default"
                    @change="handleRadioChange"
                  >
                    <a-radio-button value="tree">{{ t('树结构') }}</a-radio-button>
                    <!-- <a-radio-button value="static">{{ t('静态数据') }}</a-radio-button> -->
                    <a-radio-button value="api">API</a-radio-button>
                    <a-radio-button value="dic">{{ t('数据字典') }}</a-radio-button>
                  </a-radio-group>
                </a-form-item>
                <div
                  v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'static'"
                  class="static-box"
                >
                  <div
                    v-if="!generatorConfig.listConfig.leftMenuConfig!.staticData?.length"
                    class="static-empty"
                  >
                    {{ t('暂无数据') }}
                  </div>
                  <a-tree
                    v-else
                    block-node
                    showIcon
                    :tree-data="generatorConfig.listConfig.leftMenuConfig!.staticData"
                  >
                    <template #title="item">
                      <div class="tree-node">
                        <span>{{ item.title }}</span>
                        <span :class="isDisabled ? ' cursor-not-allowed' : ''">
                          <Icon
                            icon="ant-design:plus-outlined"
                            @click="addTreeNode(item.key, item.title)"
                            size="14"
                            color="#999"
                          />
                          &nbsp;
                          <Icon
                            icon="ant-design:delete-outlined"
                            size="14"
                            color="#999"
                            @click="
                              delTreeNode(
                                generatorConfig.listConfig.leftMenuConfig!.staticData,
                                item.key,
                              )
                            "
                          />
                        </span>
                      </div>
                    </template>
                  </a-tree>
                  <div @click="addTreeNodeParent" class="add-box">
                    <Icon icon="ant-design:plus-circle-outlined" />
                    {{ t('添加父级') }}
                  </div>
                </div>
                <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'tree'">
                  <a-form-item :label="t('标题')" required>
                    <a-select
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.treeConfig!.id"
                      style="width: 100%"
                      :options="treeSelectOption"
                      :field-names="{ label: 'name', value: 'id', options: 'children' }"
                      @change="changeTreeConfigId"
                    />
                  </a-form-item>
                  <a-form-item :label="t('关联配置')" required>
                    <div @click="changeTreeConfig" class="inline-block w-full"
                      ><InputModel
                        :value="generatorConfig.listConfig.leftMenuConfig!.treeConfig!.configTip"
                        :placeholder="t('配置关联配置')"
                        style="width: 100%; min-width: 100px"
                    /></div>
                  </a-form-item>
                  <a-form-item :label="t('允许多选')">
                    <a-switch
                      v-model:checked="generatorConfig.listConfig.leftMenuConfig!.treeConfig!.isMultiple"
                    />
                  </a-form-item>
                  <a-button type="primary" @click="resetTreeConfig" style="width: 100%"
                    >重置</a-button
                  >
                </div>
                <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'dic'">
                  <a-form-item :label="t('数据选项')" required>
                    <!-- <DicItemSelect
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.dictionaryItemId"
                    /> -->
                    <DicTreeSelect
                      :disabled="isDisabled"
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.dictionaryItemId"
                    />
                  </a-form-item>
                </div>
                <div v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType === 'api'">
                  <a-form-item :label="t('接口配置')" required>
                    <div @click="showApiDialog" class="inline-block w-full"
                      ><InputModel
                        :disabled="isDisabled"
                        :value="generatorConfig.listConfig.leftMenuConfig!.apiConfig!.path"
                        :placeholder="t('点击进行接口配置')"
                        style="width: 100%; min-width: 100px"
                    /></div>
                  </a-form-item>
                </div>
                <template
                  v-if="generatorConfig.listConfig.leftMenuConfig!.datasourceType != 'tree'"
                >
                  <a-form-item :label="t('关联字段')" required>
                    <a-select
                      :disabled="isDisabled"
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.listFieldName"
                      style="width: 100%"
                      :options="selectOption"
                    />
                  </a-form-item>
                  <a-form-item :label="t('树形标题')">
                    <a-input
                      :disabled="isDisabled"
                      v-model:value="generatorConfig.listConfig.leftMenuConfig!.menuName"
                      :placeholder="t('请输入树形标题')"
                    />
                  </a-form-item>
                </template>
              </a-form>
            </div>
          </CollapseContainer>
        </div>
        <div class="right-contarin">
          <div class="h-full">
            <CollapseContainer class="h-full" :iconStyle="{ fontSize: '12px' }">
              <template #title>
                <NodeHead :node-name="t('列表配置')" class="ml-10px" />
              </template>

              <div class="right-top">
                <div class="right-top-list">
                  <span class="right-top-file"> {{ t('默认排序') }}</span>
                  <a-switch
                    :disabled="isDisabled"
                    v-model:checked="generatorConfig!.listConfig!.defaultOrder"
                    @change="handleOrderChange"
                  />
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('排序字段') }}</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.orderBy"
                    :options="selectOption"
                    :placeholder="t('请选择排序字段')"
                    :disabled="isDisabled||generatorConfig!.listConfig!.defaultOrder"
                  />
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('排序方式') }}</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.orderType"
                    :disabled="isDisabled"
                    style="width: 100px !important"
                  >
                    <a-select-option value="asc">{{ t('升序') }}</a-select-option>
                    <a-select-option value="desc">{{ t('降序') }}</a-select-option>
                  </a-select>
                </div>
              </div>
              <div :class="prefixCls">
                <a-table
                  size="middle"
                  :columns="listColumns"
                  :pagination="false"
                  :data-source="generatorConfig?.listConfig?.columnConfigs"
                  :key="columnTableKey"
                  class="list-config"
                >
                  <template #headerCell="{ column }">
                    <div v-if="column.key === 'sort'" class="header-cell__custom-title">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-fangxiang1" />
                      </svg>
                    </div>
                    <div v-else class="header-cell__custom-title">{{ column.title }}</div>
                  </template>
                  <template #bodyCell="{ column, record, index }">
                    <template v-if="column.key !== 'action'">
                      <template v-if="column.key === 'sort'">
                        <svg
                          class="icon columnDraggable-icon"
                          :class="isDisabled ? ' cursor-not-allowed' : 'cursor: move'"
                          aria-hidden="true"
                        >
                          <use xlink:href="#icon-paixu" />
                        </svg>
                      </template>
                      <!---如果是checked一类的组件-->
                      <template v-if="column.key === 'columnName'">
                        <a-select
                          v-model:value="record[column.dataIndex]"
                          style="width: 100%"
                          :options="selectOption"
                          @change="(_, option) => handleColumnNameChange(option, index)"
                        />
                      </template>

                      <template v-if="column.key === 'mainField'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          @change="changeMainField(index)"
                        />
                      </template>

                      <template v-if="column.key === 'showLabel'">
                        <Switch v-model:checked="record[column.dataIndex]" />
                      </template>
                    </template>
                    <template v-if="column.key === 'action'">
                      <div
                        :class="isDisabled ? '!cursor-not-allowed' : 'text-[#ff8080]'"
                        @click="columnRemove(index)"
                        >{{ t('删除') }}</div
                      >
                    </template>
                  </template>
                </a-table>

                <div class="mt-2 mx-10px pb-4">
                  <a-button type="dashed" block @click="columnAdd">
                    <PlusOutlined />
                    {{ t('新增') }}
                  </a-button>
                </div>
              </div>
            </CollapseContainer>
          </div>
        </div>
      </a-tab-pane>
      <a-tab-pane class="tab-list3" key="3" :tab="t('按钮设置')">
        <div class="h-full pt-4">
          <NodeHead :node-name="t('按钮列表')" class="ml-10px mb-4" />
          <div
            :class="[prefixCls, 'pb-4']"
            :style="{ height: `calc(100% - ${!isCustomForm ? 94 : 38}px)` }"
          >
            <a-table
              size="middle"
              :columns="buttonColumns"
              :pagination="false"
              :data-source="generatorConfig?.listConfig?.buttonConfigs"
              :scroll="{ y: `calc(100% - ${!isCustomForm ? 56 : 16}px) !important` }"
            >
              <template #headerCell="{ column }">
                <div class="header-cell__custom-title">{{ column.title }}</div>
              </template>
              <template #bodyCell="{ column, record, index }">
                <!---如果是checked一类的组件-->
                <template v-if="column.key === 'isUse'">
                  <a-checkbox v-model:checked="record[column.dataIndex]" />
                </template>
                <template v-if="column.key === 'name'">
                  <a-input
                    :disabled="generatorConfig?.listConfig?.buttonConfigs[index].isDefault"
                    v-model:value="record[column.dataIndex]"
                  />
                </template>

                <template v-if="column.key === 'code'">
                  <a-input
                    :disabled="generatorConfig?.listConfig?.buttonConfigs[index].isDefault"
                    v-model:value="record[column.dataIndex]"
                  />
                </template>

                <template v-if="column.key === 'icon'">
                  <template v-if="!record.isDefault">
                    <IconPicker v-model:value="record[column.dataIndex]" :disabled="false" />
                  </template>
                  <template v-else>
                    <a-input v-model:value="record[column.dataIndex]" disabled />
                  </template>
                </template>
                <template v-if="column.key === 'action'">
                  <template v-if="record.code === 'startwork'">
                    配置：<SettingOutlined @click="handleStartWorkSetting" />
                  </template>
                  <div
                    :class="isCustomForm ? '!cursor-not-allowed' : 'text-[#ff8080]'"
                    @click="buttonRemove(index)"
                    v-else-if="!record.isDefault"
                    >{{ t('删除') }}</div
                  >
                </template>
              </template>
            </a-table>
          </div>
          <div class="mt-2 mx-10px pb-4" v-if="!isCustomForm">
            <a-button type="dashed" block @click="buttonAdd">
              <PlusOutlined />
              {{ t('新增') }}
            </a-button>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
    <ApiConfig
      v-if="apiConfigDialog"
      :isLeftMenu="true"
      v-model:apiConfigDialog="apiConfigDialog"
      v-model:apiConfig="apiConfig"
      :title="t('API配置')"
    />
    <a-modal
      v-model:visible="staticDataVisible"
      :title="modelTitle"
      @ok="addStaticDataParent"
      :afterClose="closeModal"
    >
      <a-form ref="formRef" :model="staticDataParent" style="padding: 20px 20px 0">
        <a-form-item
          :label="t('选项名')"
          name="name"
          :rules="[{ required: true, message: t('请输入选项名') }]"
        >
          <a-input v-model:value="staticDataParent.name" :placeholder="t('请输入选项名')" />
        </a-form-item>
        <a-form-item
          :label="t('选项值')"
          name="value"
          :rules="[{ required: true, message: t('请输入选项值') }]"
        >
          <a-input v-model:value="staticDataParent.value" :placeholder="t('请输入选项值')" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!-- 关联配置弹窗 -->
    <a-modal
      :visible="formTreeState.visible"
      :title="t('关联配置')"
      :width="1200"
      :maskClosable="false"
      :okText="t('确定')"
      :cancelText="t('取消')"
      @ok="submitFormTree"
      @cancel="formTreeState.visible = false"
    >
      <div class="model-box" v-if="formTreeState.visible">
        <a-row type="flex" align="middle">
          <a-col flex="120px" class="text-right"
            ><em class="required-icon">*</em>&nbsp;{{ t('树结构名称') }}：</a-col
          >
          <a-col flex="auto">
            <a-input
              v-model:value="generatorConfig.listConfig.leftMenuConfig!.treeConfig.name"
              :placeholder="t('树结构名称')"
              disabled
            />
          </a-col>
          <a-col flex="120px" class="text-right">{{ t('树类型') }}：</a-col>
          <a-col flex="auto">
            <a-select
              v-model:value="generatorConfig.listConfig.leftMenuConfig!.treeConfig.type"
              disabled
              style="width: 100%"
            >
              <a-select-option :value="TreeStructureType.STATIC">静态树</a-select-option>
              <a-select-option :value="TreeStructureType.API">API树</a-select-option>
            </a-select>
          </a-col>
        </a-row>
        <div style="height: 20px"></div>
        <a-table
          v-if="formTreeState.visible"
          :columns="treeColumns"
          :data-source="generatorConfig.listConfig.leftMenuConfig!.treeConfig.config"
          :pagination="false"
          :scroll="{ y: '400px' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'bindFiled'">
              <a-select
                v-model:value="record.bindFiled"
                style="width: 100%"
                :options="selectOption"
              />
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
    <StartWork
      v-if="startWorkDialog"
      v-model:startWorkDialog="startWorkDialog"
      v-model:startWorkConfig="startWorkConfig"
      title="发起审批配置"
    />
  </div>
</template>
<script lang="ts" setup>
  import { computed, inject, onMounted, Ref, ref, watch, nextTick, reactive, unref } from 'vue';
  import { PlusOutlined, SettingOutlined } from '@ant-design/icons-vue';
  import { GeneratorConfig } from '/@/model/generator/generatorConfig';
  import { ButtonConfig, ColumnConfig, QueryConfig } from '/@/model/generator/listConfig';
  import { TableFieldConfig } from '/@/model/generator/tableStructureConfig';
  import { ComponentOptionModel } from '/@/model/generator/codeGenerator';
  import { CollapseContainer } from '/@/components/Container/index';
  import { unionWith, cloneDeep } from 'lodash-es';
  import { Switch } from 'ant-design-vue';
  import { DicTreeSelect } from '/@/components/DicTreeSelect';
  import { IconPicker, Icon } from '/@/components/Icon';
  import { ApiConfig } from '/@/components/ApiConfig';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { isNullAndUnDef } from '/@/utils/is';
  import { noShowList, TableInfo, ColumnType } from '/@/components/Designer';
  import Sortable from 'sortablejs';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { InputModel } from '/@/components/ApiConfig';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { geList } from '/@/api/system/generator/treeStructure';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import { getInfo } from '/@/api/system/generator/treeStructure';
  import StartWork from '/@/components/CreateCodeStep/src/components/StartWork.vue';
  import ListStyle from './ListStyle.vue';

  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();
  const props = defineProps({
    //是否是编辑状态
    isUpdate: {
      type: Boolean,
      default: false,
    },
  });
  let treeSelectOption = ref([]);
  const formTreeState = reactive({
    visible: false,
  });
  const treeColumns = [
    {
      title: '序号',
      align: 'center',
      customRender: ({ index }) => `${index + 1}`, // 显示每一行的序号
      width: 80,
    },
    {
      title: t('树结构字段名称'),
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: t('关联表单字段'),
      dataIndex: 'bindFiled',
      key: 'bindFiled',
      align: 'center',
    },
  ];
  const { notification } = useMessage();
  const generatorConfig = inject<GeneratorConfig>('generatorConfig') as GeneratorConfig;
  const current = inject<Ref<number>>('current') as Ref<number>;
  const designType = inject<string>('designType', '');
  const tableInfo = inject<Ref<TableInfo[]>>('tableInfo', ref([]));
  const isCustomForm = computed(() => {
    return generatorConfig.outputConfig.funcType == 1 && !generatorConfig!.outputConfig!.createCode
      ? true
      : false;
  });
  const queryColumns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      width: 70,
      align: 'center',
    },
    {
      title: t('查询项'),
      dataIndex: 'fieldName',
      key: 'fieldName',
      align: 'center',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 108,
    },
  ]);

  const listColumns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 50,
    },
    {
      title: t('列表字段'),
      dataIndex: 'columnName',
      key: 'columnName',
      align: 'center',
    },
    {
      title: t('主字段'),
      dataIndex: 'mainField',
      width: '10%',
      key: 'mainField',
      align: 'center',
    },
    {
      title: t('是否显示标签'),
      dataIndex: 'showLabel',
      width: '15%',
      key: 'showLabel',
      align: 'center',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 88,
    },
  ]);

  const buttonColumns = ref([
    {
      title: t('启用'),
      dataIndex: 'isUse',
      key: 'isUse',
      width: '5%',
      align: 'center',
    },
    {
      title: t('按钮名称'),
      dataIndex: 'name',
      key: 'name',
      width: '30%',
    },
    {
      title: t('按钮编码'),
      dataIndex: 'code',
      key: 'code',
      width: '30%',
    },
    {
      title: t('按钮图标'),
      dataIndex: 'icon',
      key: 'icon',
      width: '20%',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
    },
  ]);

  const activeKey = ref<string>('0');
  const queryTableKey = ref<number>(0);
  const columnTableKey = ref<number>(0);

  const apiConfigDialog = ref<boolean>(false);

  const staticDataVisible = ref<boolean>(false);
  const staticDataParent = reactive({
    name: '' as string,
    value: '' as string,
  });

  const currentKey = ref('');
  const formRef = ref();
  const modelTitle = ref('');
  const loading = ref(true);
  const apiConfig = ref({});
  const startWorkDialog = ref<boolean>(false);
  const startWorkConfig = ref();

  const isDisabled = computed(() => {
    return generatorConfig.outputConfig.funcType === 1 ? false : true;
  });

  onMounted(async () => {
    //如果已经有按钮设置了 就不再添加默认值
    if (
      generatorConfig?.listConfig?.buttonConfigs &&
      generatorConfig.listConfig.buttonConfigs.length === 0
    ) {
      generatorConfig.listConfig.buttonConfigs = [
        {
          isUse: true,
          name: t('刷新'),
          code: 'refresh',
          icon: 'ant-design:reload-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('查看'),
          code: 'view',
          icon: 'ant-design:eye-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('新增'),
          code: 'add',
          icon: 'ant-design:plus-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('编辑'),
          code: 'edit',
          icon: 'ant-design:form-outlined',
          isDefault: true,
        },
        {
          isUse: true,
          name: t('删除'),
          code: 'delete',
          icon: 'ant-design:delete-outlined',
          isDefault: true,
        },
        {
          isUse: false,
          name: t('发起审批'),
          code: 'startwork',
          icon: 'ant-design:form-outlined',
          isDefault: true,
          schemaInitConfig: {
            enabled: false,
            enabledAddApprove: false,
            config: {
              id: '',
            },
          },
        },
      ];
      try {
        await initTreeData();
      } catch (error) {}
    }
  });
  //过滤出 所有主表数据字段  子表的不需要  不在列表页展示的不需要
  const filterMainComponent = (
    list: ComponentOptionModel[] | null,
    isSearch = false,
  ): Recordable[] => {
    if (!list) return [];
    let mainComponents = [] as Recordable[];
    let mainTableFieldConfigs = [] as TableFieldConfig[];

    const remoteComponents = [
      'select',
      'associate-select',
      'associate-popup',
      'multiple-popup',
      'checkbox',
      'radio',
    ];
    generatorConfig.tableStructureConfigs?.forEach((x) => {
      if (x.isMain) mainTableFieldConfigs = x.tableFieldConfigs;
    });
    for (const item of list) {
      //去除子表单组件  和 不在列表页展示的组件
      if (noShowList.includes(item.type)) {
        if (['tab', 'grid', 'card'].includes(item.type)) {
          for (const child of item.layout!) {
            mainComponents = unionWith(mainComponents, filterMainComponent(child.list, isSearch));
          }
        }
        if (item.type == 'table-layout') {
          item.layout!.forEach((element1) => {
            for (const child of element1.list!) {
              mainComponents = unionWith(
                mainComponents,
                filterMainComponent(child.children!, isSearch),
              );
            }
          });
        }
      } else if (item.type.indexOf('range') !== -1) {
        //查询配置不要时间范围和日期范围
        if (!isSearch) {
          mainComponents.push({
            key: item.key,
            value: item.bindStartTime,
            label: t(`{name}开始时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
          });
          mainComponents.push({
            key: item.key,
            value: item.bindEndTime,
            label: t(`{name}结束时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
          });
        }
      } else {
        let notInQuery = false;
        //组件的数据是使用api并且引用组件值作为参数的组件 不进入查询列表
        if (
          ((remoteComponents.includes(item.type) && item.options?.datasourceType === 'api') ||
            item.type === 'cascader') &&
          isSearch
        ) {
          notInQuery = item.options?.apiConfig?.apiParams?.some((para) => {
            const hasFormData = para.tableInfo?.some((info) => {
              if (!info.value) return false;
              return info.bindType === 'data' && info.value?.slice(0, 2) !== '3-';
            });
            return hasFormData;
          });
        }
        //组件：树形组件 不进入查询列表 不进入列表配置
        if (item.type === 'tree-component') {
          notInQuery = true;
        }
        if (!notInQuery) {
          if (item.type === 'time' || item.type === 'date') {
            //查询时 时间选择和日期选择需要保存format
            mainComponents.push({
              value: item.bindField,
              label: item.label,
              type: item.type,
              format: item.options?.format,
            });
          } else if (isSearch && item.type === 'info' && item.options?.infoType === 2) {
            //查询时 信息体为当前时间 则查询为时间范围
            mainComponents.push({
              value: item.bindField,
              label: item.label,
              type: item.type,
              // format: 'YYYY-MM-DD HH:mm:ss',
              isDate: true,
            });
          } else {
            let isNumber;

            if (unref(designType) !== 'data') {
              let fieldType;
              mainTableFieldConfigs?.map((x) => {
                if (x.fieldName === item.bindField) {
                  fieldType = x.fieldType;
                }
              });
              isNumber = [2, 3, 7].includes(fieldType);
            } else {
              const table = tableInfo?.value.find((x) => x.isMain); //找到主表信息
              const field = table?.fields.find((x) => x.name === item.bindField); //找到当前字段信息
              isNumber = field?.type === ColumnType.NUMBER;
            }
            if ((item.type == 'input' && !item.options?.isSave) || item.type !== 'input') {
              mainComponents.push({
                key: item.key,
                value: item.bindField,
                label: item.label,
                type: item.type,
                isNumber,
                componentProps: item.options,
              });
            }
          }
        }
      }
    }

    return mainComponents;
  };
  const getConfigCodeInfo = () => {
    let listComponent = generatorConfig.listConfig.columnConfigs;

    generatorConfig.listConfig.columnConfigs = listComponent.map((component) => {
      const columnConfig: ColumnConfig = {
        key: component.key, //数据优先存在编辑时 绑定字段相同的情况 所以需要唯一标识
        columnName: component.columnName,
        label: component.label,
        columnWidth: '100%',
        mainField: props.isUpdate ? component.mainField : false,
        showLabel: props.isUpdate
          ? component.showLabel === undefined
            ? true
            : component.showLabel
          : true,
        isNumber: component.isNumber,
        componentType: component.componentType,
        format: component.format || undefined,
        componentProps: component.componentProps,
      };
      return columnConfig;
    });
  };
  const getConfigInfo = () => {
    let listComponent = filterMainComponent(generatorConfig!.formJson!.list);
    let queryComponent: any = filterMainComponent(generatorConfig!.formJson!.list, true);

    let queryConfigs: QueryConfig[] = [];
    let columnConfigs: ColumnConfig[] = [];

    // 编辑时 列表配置需要判断key和绑定字段都相同时 则不进行处理
    // key不同并且绑定字段相同（数据优先换了组件但绑定的字段是绑定过的）、key相同绑定字段不同（数据优先已存在的组件换绑字段）
    if (props.isUpdate) {
      //新增时列表配置的组件
      const addColumns = generatorConfig.listConfig.columnConfigs.map((x) => {
        return { key: x.key, field: x.columnName };
      });
      //编辑时列表配置的组件
      const editColumns = listComponent.map((x) => {
        return { key: x.key, field: x.value };
      });

      //编辑时列表配置没有被删除的组件（已经删除的组件删掉）
      columnConfigs = generatorConfig.listConfig.columnConfigs.filter((x) =>
        editColumns.some((clm) => clm.key === x.key && clm.field === x.columnName),
      );
      //除去列表配置新增时已经设置好的组件
      listComponent = listComponent.filter(
        (x) => !addColumns.some((clm) => clm.key === x.key && clm.field === x.value),
      );

      //新增时查询配置的组件名称
      const addQueryNames = generatorConfig.listConfig.queryConfigs.map((x) => x.fieldName);
      //编辑时查询配置的组件名称
      const editQueryNames = queryComponent.map((x) => x.value);
      //编辑时查询配置没有被删除的组件（已经删除的组件删掉）
      queryConfigs = generatorConfig.listConfig.queryConfigs.filter((x) =>
        editQueryNames.includes(x.fieldName),
      );
      // //除去查询配置新增时已经设置好的组件
      queryComponent = queryComponent.filter((x) => !addQueryNames.includes(x.value));
    }
    columnConfigs.forEach((component) => {
      if (component.showLabel === undefined) component.showLabel = true;
    });

    generatorConfig.listConfig.columnConfigs = listComponent.map((component) => {
      const columnConfig: ColumnConfig = {
        key: component.key, //数据优先存在编辑时 绑定字段相同的情况 所以需要唯一标识
        columnName: component.value,
        label: component.label,
        columnWidth: '100%',
        mainField: false,
        showLabel: true,
        isNumber: component.isNumber,
        componentType: component.type,
        format: component.format || undefined,
        componentProps: component.componentProps,
      };
      return columnConfig;
    });

    generatorConfig.listConfig.queryConfigs = queryComponent.map((component) => {
      const queryConfig: QueryConfig = {
        fieldName: component.value,
        width: 8,
        isDate: ['time', 'date'].includes(component.type) || !!component.isDate,
        format: component.format || undefined,
      };
      return queryConfig;
    });

    if (props.isUpdate) {
      generatorConfig.listConfig.columnConfigs.unshift(...columnConfigs);
      generatorConfig.listConfig.queryConfigs.unshift(...queryConfigs);
    }
  };

  watch(
    () => current.value,
    (val) => {
      if (val === 2) {
        loading.value = false;
        if (generatorConfig.outputConfig.funcType === 1) {
          getConfigInfo();
        } else {
          getConfigCodeInfo();
        }
        startWorkConfig.value = generatorConfig.listConfig.buttonConfigs.find(
          (item) => item.code === 'startwork',
        )?.schemaInitConfig;
        apiConfig.value = cloneDeep(generatorConfig?.listConfig.leftMenuConfig?.apiConfig);
      }
    },
    {
      immediate: true,
    },
  );

  watch(
    () => generatorConfig?.listConfig?.queryConfigs,
    (val) => {
      if (val && val.length && !isDisabled.value) {
        nextTick(() => {
          const tbody: any = document.querySelector('.search-config .ant-table-tbody');
          if (!tbody) return;
          Sortable.create(tbody, {
            handle: '.queryDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(generatorConfig?.listConfig?.queryConfigs);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              generatorConfig!.listConfig!.queryConfigs = cloneDeep(columns);
              queryTableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );
  watch(
    () => [generatorConfig?.listConfig?.columnConfigs, activeKey.value],
    (val) => {
      if (val[0] && val[0].length && val[1] === '2' && !isDisabled.value) {
        nextTick(() => {
          const tbody: any = document.querySelector('.list-config .ant-table-tbody');
          Sortable.create(tbody, {
            handle: '.columnDraggable-icon',
            onEnd: ({ oldIndex, newIndex }) => {
              if (isNullAndUnDef(oldIndex) || isNullAndUnDef(newIndex) || newIndex === oldIndex) {
                return;
              }
              const columns = cloneDeep(generatorConfig?.listConfig?.columnConfigs);
              if (oldIndex > newIndex) {
                columns.splice(newIndex, 0, columns[oldIndex]);
                columns.splice(oldIndex + 1, 1);
              } else {
                columns.splice(newIndex + 1, 0, columns[oldIndex]);
                columns.splice(oldIndex, 1);
              }
              generatorConfig!.listConfig!.columnConfigs = cloneDeep(columns);
              columnTableKey.value++;
            },
          });
        });
      }
    },
    {
      deep: true,
      immediate: true,
    },
  );

  watch(
    apiConfig,
    (val) => {
      generatorConfig!.listConfig.leftMenuConfig!.apiConfig = cloneDeep(val);
      delete generatorConfig!.listConfig.leftMenuConfig!.apiConfig?.script;
    },
    {
      deep: true,
    },
  );

  watch(
    () => startWorkConfig.value,
    (val) => {
      generatorConfig.listConfig.buttonConfigs.forEach((item) => {
        if (item.code === 'startwork') {
          item.schemaInitConfig = val;
        }
      });
    },
    {
      deep: true,
    },
  );
  const showApiDialog = () => {
    apiConfigDialog.value = true;
  };

  const changeLeftMenu = (value) => {
    if (value && !generatorConfig?.listConfig?.leftMenuConfig?.datasourceType) {
      generatorConfig!.listConfig!.leftMenuConfig!.datasourceType = 'static';
    }
  };

  const queryAdd = () => {
    if (isDisabled.value) return;
    //给各个组件赋默认值
    const pushObj: QueryConfig = {
      fieldName: '',
      width: 8,
      isDate: false,
    };
    generatorConfig?.listConfig?.queryConfigs.push(pushObj);
  };

  const queryRemove = (index) => {
    if (isDisabled.value) return;
    generatorConfig?.listConfig?.queryConfigs.splice(index, 1);
  };

  const columnAdd = () => {
    //给各个组件赋默认值
    const pushObj: ColumnConfig = {
      key: '',
      label: '',
      columnName: '',
      columnWidth: '100%',
      mainField: false,
      showLabel: true,
      componentType: '',
    };
    generatorConfig?.listConfig?.columnConfigs.push(pushObj);
    // queryOptionData.value.push(pushObj);
  };

  const columnRemove = (index) => {
    if (isDisabled.value) return;
    generatorConfig?.listConfig?.columnConfigs.splice(index, 1);
  };

  const buttonAdd = () => {
    //给各个组件赋默认值
    const pushObj: ButtonConfig = {
      isUse: true,
      name: '',
      code: '',
      icon: '',
      isDefault: false,
    };
    generatorConfig?.listConfig?.buttonConfigs.push(pushObj);
  };

  const buttonRemove = (index) => {
    generatorConfig?.listConfig?.buttonConfigs.splice(index, 1);
  };

  const closeModal = () => {
    formRef.value.resetFields();
  };

  const addStaticDataParent = async () => {
    const valid = await onCheck();
    if (valid) {
      if (currentKey.value) {
        //子级新增
        findTreeNode(generatorConfig.listConfig.leftMenuConfig!.staticData);
      } else {
        //父级新增
        generatorConfig.listConfig.leftMenuConfig!.staticData?.push({
          title: staticDataParent.name,
          key: staticDataParent.value,
        });
      }
      staticDataVisible.value = false;
    }
  };
  const findTreeNode = (node) => {
    node?.some((item) => {
      if (item.key === currentKey.value) {
        if (!item.children) item.children = [];
        item.children.push({
          title: staticDataParent.name,
          key: staticDataParent.value,
        });
        return true;
      } else {
        if (item.children?.length) {
          return findTreeNode(item.children);
        } else {
          return false;
        }
      }
    });
  };

  const delTreeNode = (node, key) => {
    if (isDisabled.value) return;
    node?.some((item, index) => {
      if (item.key === key) {
        node.splice(index, 1);
        return true;
      } else {
        if (item.children?.length) {
          return delTreeNode(item.children, key);
        } else {
          return false;
        }
      }
    });
  };
  const addTreeNodeParent = () => {
    if (isDisabled.value) return;
    staticDataVisible.value = true;
    currentKey.value = '';
    modelTitle.value = t('添加父级选项');
  };
  const addTreeNode = (key, title) => {
    if (isDisabled.value) return;
    staticDataVisible.value = true;
    currentKey.value = key;
    modelTitle.value = t(`添加【{title}】的子选项`, { title });
  };

  const onCheck = async () => {
    try {
      await formRef.value.validateFields();
      return true;
    } catch (errorInfo) {
      return false;
    }
  };

  const handleOrderChange = (val) => {
    if (val) {
      generatorConfig.listConfig.orderBy = '';
      generatorConfig.listConfig.orderType = undefined;
    }
  };

  const selectOption = computed(() => {
    return filterMainComponent(generatorConfig?.formJson?.list);
  });

  const querySelectOption = computed(() => {
    return filterMainComponent(generatorConfig?.formJson?.list, true);
  });

  //切换数据来源的时候 默认清理掉其他数据
  const handleRadioChange = (e): void => {
    if (e.target.value === 'api') {
      generatorConfig!.listConfig!.leftMenuConfig!.dictionaryItemId = '';
    } else {
      generatorConfig!.listConfig!.leftMenuConfig!.fieldName = '';
      generatorConfig!.listConfig!.leftMenuConfig!.relationFieldName = '';
    }
  };

  const handleColumnNameChange = (option, index) => {
    generatorConfig!.listConfig.columnConfigs[index].componentType = option.type;
    generatorConfig!.listConfig.columnConfigs[index].label = option.label;
  };

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    const { listConfig } = generatorConfig;
    const {
      queryConfigs,
      columnConfigs,
      buttonConfigs,
      isLeftMenu,
      leftMenuConfig,
      orderBy,
      defaultOrder,
    } = listConfig!;
    const fieldNameAll = [] as string[];

    //TODO 验证查询配置
    for (let i = 0; i < queryConfigs.length; i++) {
      fieldNameAll.push(queryConfigs[i].fieldName);
      if (!queryConfigs[i].fieldName) {
        notification.error({
          message: t('提示'),
          description: t(`查询配置第{index}条，未选择列名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }
    //判断查询配置查询项是否有重复值
    if ([...new Set(fieldNameAll)].length < fieldNameAll.length) {
      notification.error({
        message: t('提示'),
        description: t('查询配置 查询项不能重复'),
      }); //提示消息
      return false;
    }
    //判断是否有左侧菜单
    if (isLeftMenu) {
      if (!leftMenuConfig) {
        notification.error({
          message: t('提示'),
          description: t('如果需要左侧菜单必须完善配置！'),
        }); //提示消息
        return false;
      }

      if (!leftMenuConfig.datasourceType) {
        notification.error({
          message: t('提示'),
          description: t('必须选择数据来源！'),
        }); //提示消息
        return false;
      }

      if (!leftMenuConfig.listFieldName) {
        notification.error({
          message: t('提示'),
          description: t('必须选择列表关联字段！'),
        }); //提示消息
        return false;
      }

      //如果数据来源为数据字典
      if (leftMenuConfig.datasourceType === 'dic') {
        if (!leftMenuConfig.dictionaryItemId) {
          notification.error({
            message: t('提示'),
            description: t('必须选择数据字典项!'),
          }); //提示消息
          return false;
        }
      }
      //如果数据来源为数据源
      else if (leftMenuConfig.datasourceType === 'datasource') {
        if (!leftMenuConfig.datasourceId) {
          notification.error({
            message: t('提示'),
            description: t('必须选择数据源!'),
          }); //提示消息
          return false;
        }
        //左侧菜单标题
        if (!leftMenuConfig.menuName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-标题!'),
          }); //提示消息
          return false;
        }

        //id字段
        if (!leftMenuConfig.fieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-id字段!'),
          }); //提示消息
          return false;
        }

        //父级字段
        if (!leftMenuConfig.parentFiledName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-父级字段!'),
          }); //提示消息
          return false;
        }

        //显示字段
        if (!leftMenuConfig.showFieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-显示字段!'),
          }); //提示消息
          return false;
        }

        //关联字段
        if (!leftMenuConfig.relationFieldName) {
          notification.error({
            message: t('提示'),
            description: t('必须配置左侧菜单-关联字段!'),
          }); //提示消息
          return false;
        }
      }
    }

    if (!columnConfigs || columnConfigs.length === 0) {
      notification.error({
        message: t('提示'),
        description: t('列表字段配置不能为空!'),
      }); //提示消息
      return false;
    }

    const columnNameAll = [] as string[];

    //验证列表配置
    for (let i = 0; i < columnConfigs.length; i++) {
      columnNameAll.push(columnConfigs[i].columnName);
      if (!columnConfigs[i].columnName) {
        notification.error({
          message: t('提示'),
          description: t(`列表配置第{index}条，未选择列名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }

    //判断列表配置列表字段是否有重复值
    if ([...new Set(columnNameAll)].length < columnNameAll.length) {
      notification.error({
        message: t('提示'),
        description: t('列表配置 列表字段不能重复'),
      }); //提示消息
      return false;
    }

    //判断排序 如果不是默认排序 需要自己配置排序字段
    if (!defaultOrder) {
      if (!orderBy) {
        notification.error({
          message: t('提示'),
          description: t('如果是非默认排序,必须配置排序字段!'),
        }); //提示消息
        return false;
      }
    }

    //验证按钮配置
    for (let i = 0; i < buttonConfigs.length; i++) {
      if (!buttonConfigs[i].name) {
        notification.error({
          message: t('提示'),
          description: t(`按钮配置第{index}条，未填写按钮名！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }

      if (!buttonConfigs[i].code) {
        notification.error({
          message: t('提示'),
          description: t(`按钮配置第{index}条，未填写按钮编码！`, { index: i + 1 }),
        }); //提示消息
        return false;
      }
    }
    return true;
  };
  function changeMainField(index) {
    generatorConfig?.listConfig?.columnConfigs.forEach((o, idx) => {
      if (idx != index) {
        o.mainField = false;
      }
    });
  }
  async function initTreeData() {
    let res = await geList();
    treeSelectOption.value = res;
  }
  function resetTreeConfig() {
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.id = '';
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.config = [];
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.isMultiple = false;
  }
  async function changeTreeConfigId(id) {
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.config = [];
    let res = await getInfo(id);
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.type = res.type;
    generatorConfig.listConfig.leftMenuConfig!.treeConfig.name = res.name;
    if (generatorConfig.listConfig.leftMenuConfig!.treeConfig.type == TreeStructureType.STATIC) {
      if (res.columns) {
        let columnsObj = JSON.parse(res.columns);
        changeColumn(columnsObj);
      }
    } else {
      if (res.config) {
        let configObj = JSON.parse(res.config);
        changeColumn(configObj.apiData.apiColumns);
      }
    }
  }
  function changeTreeConfig() {
    formTreeState.visible = true;
  }

  function changeColumn(columns) {
    for (let index = 1; index < columns.length; index++) {
      if (index % 2) {
        let labelIndex = index - 1;
        generatorConfig.listConfig.leftMenuConfig!.treeConfig.config.push({
          bindFiled: '',
          name:
            generatorConfig.listConfig.leftMenuConfig!.treeConfig.type == TreeStructureType.STATIC
              ? getTitle(columns[labelIndex].title)
              : columns[labelIndex].title,
          value: columns[index].dataIndex,
        });
      }
    }
  }
  function submitFormTree() {
    formTreeState.visible = false;
    generatorConfig.listConfig.leftMenuConfig!.treeConfig!.configTip = '已配置';
  }
  function getTitle(title) {
    if (title.includes('(')) {
      let arr = title.split('(');
      if (arr.length > 0 && arr[1].includes(')')) {
        let arr2 = arr[1].split(')');
        return arr2[0];
      }
    }
    return '';
  }

  function handleStartWorkSetting() {
    startWorkDialog.value = true;
  }
  defineExpose({ validateStep });
</script>
<style lang="less" scoped>
  :deep(.ant-tabs-nav-wrap) {
    display: block !important;
  }

  :deep(.ant-tabs-tab) {
    width: 33.33% !important;
    display: block !important;
    text-align: center !important;
  }

  :deep(.ant-radio-button-wrapper) {
    flex: 1;
    text-align: center;
    padding: 0 4px;
    display: block;
  }

  :deep(.ant-form-item-label > label) {
    &::after {
      display: none;
    }
  }

  :deep(.collapse-box) {
    height: calc(100% - 50px);
    overflow: auto;
  }

  .vben-basic-table .ant-table-wrapper {
    height: auto;
    max-height: 100%;
    overflow: auto;
  }

  .tree-left-contain {
    width: 304px;
    float: left;
    height: 100%;
    border-right: 1px solid #eee;
    overflow-y: auto;
  }

  .right-contarin {
    overflow-y: auto;
    height: 100%;
  }

  :deep(.ant-tabs-content) {
    height: 100% !important;
    overflow-y: auto;
  }

  .right-top-list {
    display: inline-block;
    padding-right: 15px;
    margin-bottom: 10px;
  }

  .right-top-file {
    display: inline-block;
    padding-right: 10px;
  }

  .right-top-list > div {
    width: 140px !important;
    display: inline-block;
  }

  .right-top {
    border-bottom: 1px solid #e5e7eb;
    padding: 15px 10px 5px;
  }

  .tree-node {
    display: flex;
    justify-content: space-between;
  }

  .static-box {
    margin: 20px 0;

    .static-empty {
      text-align: center;
    }

    .add-box {
      color: #5e95ff;
      margin-top: 10px;
    }
  }

  .tree-left-container {
    :deep(.ant-form-item) {
      margin-bottom: 10px;
    }
  }

  :deep(.ant-tabs-nav) {
    margin-bottom: 0;
  }

  .icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentcolor;
    overflow: hidden;
    display: inline-block;
  }

  .tab-list3 {
    .ant-input[disabled] {
      background: #fafafa;
      color: #000;
    }
  }

  .model-box {
    padding: 20px;
  }

  .q-box {
    display: flex;
    align-items: center;
    font-size: 14px;
    margin-left: 50px;

    .label-box {
      color: #666;
      margin-right: 6px;
    }

    .tip {
      color: #ccc;
      margin-left: 6px;
    }
  }
</style>
