<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"
          v-model:config="generatorConfig!.listConfig.listStyleConfig"
          @list-style="handleStyleChange"
        />
      </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 class="q-box" v-if="designType !== 'notable'">
              <div class="label-box">高级查询</div>
              <a-switch v-model:checked="generatorConfig.listConfig.isAdvancedQuery" />
              <div class="tip">
                注意事项：高级查询开启后，可在列表页面编辑预先设置的查询视图，然后进行快捷查询。
              </div>
            </div>
          </div>
          <div :class="prefixCls" style="max-height: calc(100% - 95px)">
            <a-table
              size="middle"
              :columns="queryColumns"
              :pagination="false"
              :data-source="queryConfigsData"
              :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('请选择查询项')"
                      @change="changeQueryConfig(index)"
                    />
                  </template>
                  <template v-if="column.key === 'fieldValue'">
                    <SearchFormItem
                      v-if="record.schemas"
                      :schema="record.schemas"
                      :formProps="{}"
                      :value="record.fieldValue"
                      @change="
                        (val) => {
                          if (val) record.fieldValue = val;
                        }
                      "
                    />
                    <span v-else>请先选择查询项</span>
                  </template>

                  <!-- <template v-if="column.key === 'fieldValue'">
                    <a-input-number v-model:value="record[column.dataIndex]" style="width: 100%" />
                  </template> -->
                  <!-- <template v-if="column.key === 'width'">
                  <a-input-number
                    v-model:value="record[column.dataIndex]"
                    addon-after="/ 24"
                    style="width: 100%"
                  />
                </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
                  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-button type="primary" @click="addTreeConfig" class="w-full mt-1">
                添加树
              </a-button>
              <a-tabs
                v-model:activeKey="leftMenuIndex"
                v-if="generatorConfig?.listConfig.leftMenuConfig!.length>1"
              >
                <a-tab-pane
                  :key="index"
                  v-for="(config, index) in generatorConfig?.listConfig.leftMenuConfig"
                >
                  <template #tab>
                    <span>
                      {{ config.title || index + 1 }}
                      <Icon
                        icon="ant-design:close-circle-outlined"
                        size="14"
                        color="#999"
                        class="close-icon"
                        @click.stop="delLeftMenuConfig(index)"
                      />
                    </span>
                  </template>
                  <LeftMenuTree
                    :config="config"
                    :isShowTitle="true"
                    :treeSelectOption="treeSelectOption"
                    :selectOption="selectOption"
                    @handle-radio-change="handleRadioChange"
                    @change-tree-config-id="changeTreeConfigId"
                    @change-tree-config="changeTreeConfig"
                    @reset-tree-config="resetTreeConfig"
                    @show-api-dialog="showApiDialog"
                  />
                </a-tab-pane>
              </a-tabs>
              <LeftMenuTree
                :config="generatorConfig?.listConfig.leftMenuConfig![0]"
                :isShowTitle="false"
                :treeSelectOption="treeSelectOption"
                :selectOption="selectOption"
                @handle-radio-change="handleRadioChange"
                @change-tree-config-id="changeTreeConfigId"
                @change-tree-config="changeTreeConfig"
                @reset-tree-config="resetTreeConfig"
                @show-api-dialog="showApiDialog"
                v-else
              />
            </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">列表样式</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.listStyle"
                    @change="handleStyleChange"
                  >
                    <a-select-option value="default">默认模式</a-select-option>
                    <a-select-option value="card">卡片式</a-select-option>
                  </a-select>
                </div> -->
                <div
                  class="right-top-list"
                  v-if="generatorConfig!.listConfig!.listStyle=== LIST_MODE.CARD"
                >
                  <span class="right-top-file">排列方式</span>
                  <a-select
                    v-model:value="generatorConfig!.listConfig!.arrangeType"
                    @change="handleArrageChange"
                  >
                    <a-select-option value="one">一行一字段</a-select-option>
                    <a-select-option value="two">一行两字段</a-select-option>
                  </a-select>
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('列表标题') }}</span>
                  <a-input
                    v-model:value="generatorConfig!.listConfig!.listTitle"
                    :placeholder="t('可填写列表标题，非必填')"
                    style="width: 180px"
                  />
                </div>
                <div class="right-top-list">
                  <span class="right-top-file">{{ t('每页条数') }}</span>
                  <a-input-number
                    v-model:value="generatorConfig!.listConfig!.pageSize"
                    :placeholder="t('可填写每页条数，非必填')"
                    style="width: 90px"
                  />
                </div>

                <template v-if="designType !== 'notable'">
                  <div class="right-top-list">
                    <span class="right-top-file"> {{ t('默认排序') }}</span>
                    <a-switch
                      v-model:checked="generatorConfig!.listConfig!.defaultOrder"
                      @change="handleOrderChange"
                    />
                  </div>
                  <div class="right-top-list">
                    <span class="right-top-file">{{ t('排序字段') }}</span>
                    <a-select
                      mode="multiple"
                      v-model:value="generatorConfig!.listConfig!.orderByArr"
                      :options="selectOption"
                      :placeholder="t('请选择排序字段')"
                      :disabled="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="generatorConfig?.listConfig?.defaultOrder"
                      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 class="right-top-list">
                    <HeaderMerging @change-header-merging-data="changeHeaderMergingData" />
                  </div>
                </template>
              </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"
                          aria-hidden="true"
                          style="cursor: move"
                        >
                          <use xlink:href="#icon-paixu" />
                        </svg>
                      </template>
                      <template v-if="column.key === 'label'">
                        <a-input v-model:value="record[column.dataIndex]" />
                      </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 === 'alignType'">
                        <a-select v-model:value="record[column.dataIndex]" style="width: 100%">
                          <a-select-option value="left">
                            {{ t('左对齐') }}
                          </a-select-option>
                          <a-select-option value="center">
                            {{ t('居中') }}
                          </a-select-option>
                          <a-select-option value="right">
                            {{ t('右对齐') }}
                          </a-select-option>
                        </a-select>
                      </template>
                      <template v-if="column.key === 'columnWidth'">
                        <a-input
                          v-model:value="record[column.dataIndex]"
                          :disabled="record.autoWidth"
                        />
                      </template>

                      <template v-if="column.key === 'autoWidth'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          @change="record.columnWidth = '100'"
                        />
                      </template>

                      <template v-if="column.key === 'isTotal'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          :disabled="!record.isNumber"
                        />
                      </template>
                      <template v-if="column.key === 'isFixed'">
                        <Switch v-model:checked="record[column.dataIndex]" />
                      </template>
                      <template v-if="column.key === 'isFilter' || column.key === 'textBold'">
                        <Switch v-model:checked="record[column.dataIndex]" />
                      </template>
                      <template v-if="column.key === 'aRow'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          :disabled="generatorConfig.listConfig.arrangeType === 'one'"
                        />
                      </template>
                      <template v-if="column.key === 'rowSpan'">
                        <Switch
                          v-model:checked="record[column.dataIndex]"
                          :disabled="generatorConfig.listConfig.arrangeType === 'one'"
                          @change="
                            () => {
                              if (record[column.dataIndex]) {
                                generatorConfig?.listConfig?.columnConfigs.forEach((o) => {
                                  o[column.dataIndex] = false;
                                });
                                record[column.dataIndex] = true;
                              }
                            }
                          "
                        />
                      </template>
                    </template>
                    <template v-if="column.key === 'action'">
                      <div class="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>
                <template v-if="designType === 'notable'">
                  <NodeHead nodeName="接口配置" class="node-title" />
                  <ApiFormConfig
                    :info="generatorConfig?.listConfig?.apiConfig"
                    type="list"
                    @change-config="changeConfig"
                  />
                </template>
              </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% - 95px)` }">
            <a-table
              size="middle"
              :columns="buttonColumns"
              :pagination="false"
              :data-source="generatorConfig?.listConfig?.buttonConfigs"
              :scroll="{ y: `calc(100% - 56px) !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]"
                    :disabled="buttonDisabled(record)"
                    @change="handleCheck(record)"
                  />
                </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.isDefault">
                    <a-select v-model:value="record.buttonType" class="!mr-1.5" size="small">
                      <a-select-option value="primary">主按钮</a-select-option>
                      <a-select-option value="default">默认按钮</a-select-option>
                      <a-select-option value="danger">危险按钮</a-select-option>
                      <a-select-option value="link">链接按钮</a-select-option>
                      <a-select-option value="text">文本按钮</a-select-option>
                      <a-select-option value="modal">弹窗按钮</a-select-option>
                    </a-select>
                    位置:
                    <a-select v-model:value="record.showType" class="!mr-1.5" size="small">
                      <a-select-option value="inline">行内</a-select-option>
                      <a-select-option value="top">顶部</a-select-option>
                    </a-select>
                    <ButtonModalConfig
                      v-if="record.buttonType == 'modal'"
                      v-model:modalData="record.modal"
                      :formJson="[]"
                    >
                      <SettingOutlined class="cursor-pointer" />
                    </ButtonModalConfig>
                    <ExecuteEvent
                      v-else
                      v-model:processEvent="record.setting"
                      classStyle="inline mr-1"
                    >
                      <SettingOutlined class="cursor-pointer" />
                    </ExecuteEvent>
                    <DeleteTwoTone two-tone-color="#ff8080" @click="buttonRemove(index)" />
                  </template>
                  <template v-if="record.code === 'edit' && designType !== 'notable'">
                    并发锁:
                    <a-switch v-model:checked="record.isEnableLock" size="small" />
                  </template>
                  <template v-if="record.code === 'startwork'">
                    并发锁:
                    <a-switch v-model:checked="record.isEnableLock" size="small" />
                    配置：<SettingOutlined @click="handleStartWorkSetting" />
                  </template>
                  <template v-if="settingBtn.includes(record.code)">
                    <SettingOutlined @click="handleSetting(record.code)" />
                  </template>
                </template>
              </template>
            </a-table>
          </div>
          <div class="mt-2 mx-10px pb-4">
            <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![leftMenuIndex].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![leftMenuIndex].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![leftMenuIndex].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>
    <PushOrder
      v-if="pushOrderDialog"
      v-model:pushOrderDialog="pushOrderDialog"
      v-model:pushOrderConfig="pushOrderConfig"
      title="推单规则配置"
    />
    <StartWork
      v-if="startWorkDialog"
      v-model:startWorkDialog="startWorkDialog"
      v-model:startWorkConfig="startWorkConfig"
      title="发起审批配置"
    />
    <ApiConfigModal
      v-if="apiFormDialog"
      v-model:apiFormDialog="apiFormDialog"
      :apiBtnConfig="apiBtnConfig"
      @get-btn-config="getBtnConfig"
      title="API配置"
    />
  </div>
</template>
<script lang="ts" setup>
  import { computed, inject, onMounted, Ref, ref, watch, nextTick, reactive, unref } from 'vue';
  import { PlusOutlined, DeleteTwoTone, 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, random } from 'lodash-es';
  import { Switch } from 'ant-design-vue';
  import ListStyle from '/@/components/CreateCodeStep/src/components/ListStyle.vue';
  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 { BasicColumn } from '/@/components/Table';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { PrintButton } from '/@/enums/printEnum';
  import { geList } from '/@/api/system/generator/treeStructure';
  import { changeCompsApiConfig, changeEventApiConfig, getMainTable } from '/@/utils/event/design';
  import { TreeStructureType } from '/@/enums/treeStructure';
  import { getInfo } from '/@/api/system/generator/treeStructure';
  import PushOrder from './components/PushOrder.vue';
  import ExecuteEvent from './components/ExecuteEvent.vue';
  import StartWork from './components/StartWork.vue';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { useDesign } from '/@/hooks/web/useDesign';
  import ApiFormConfig from './components/ApiFormConfig.vue';
  import ApiConfigModal from './components/ApiConfigModal.vue';
  import LeftMenuTree from './components/LeftMenuTree.vue';
  import { LIST_MODE } from '/@/enums/formViewEnum';
  import SearchFormItem from '/@/components/Form/src/components/SearchFormItem.vue';
  import { buildComponentType } from '/@/utils/helper/designHelper';
  import HeaderMerging from './components/HeaderMerging.vue';
  import ButtonModalConfig from '/@/components/CreateCodeStep/src/components/ButtonModalConfig.vue';

  const interfaceInfo = [
    {
      key: '1',
      title: 'Query Params',
      tableInfo: [],
    },
    {
      key: '2',
      title: 'Header',
      tableInfo: [],
    },
    {
      key: '3',
      title: 'Body',
      tableInfo: [],
    },
  ];
  const { prefixCls } = useDesign('basic-table');
  const { t } = useI18n();
  const props = defineProps({
    //是否是自定义表单生成代码
    isFormGenerator: {
      type: Boolean,
      default: false,
    },
    //是否是编辑状态
    isUpdate: {
      type: Boolean,
      default: false,
    },
    //自定义表单生成代码使用
    designType: {
      type: String,
      default: '',
    },
  });
  const { notification } = useMessage();
  let treeSelectOption = ref([]);
  const generatorConfig = inject<GeneratorConfig>('generatorConfig') as GeneratorConfig;
  const current = inject<Ref<number>>('current') as Ref<number>;
  const designType = inject<string>('designType', props.isFormGenerator ? props.designType : '');
  const tableInfo = inject<Ref<TableInfo[]>>('tableInfo', ref([]));
  const isCustomForm = inject<boolean>('isCustomForm', false);
  const formTreeState = reactive({
    visible: false,
  });

  const leftMenuIndex = ref(0);

  const configs = [
    {
      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: 'batchdelete',
      icon: 'ant-design:delete-outlined',
      isDefault: true,
      apiConfig: {
        method: '',
        path: '',
        apiId: '',
        apiParams: interfaceInfo,
      },
    },
    {
      isUse: false,
      name: '复制数据',
      code: 'copyData',
      icon: 'ant-design:copy-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('快速导出'),
      code: 'export',
      icon: 'ant-design:export-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('打印'),
      code: 'print',
      icon: 'ant-design:printer-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('模板打印'),
      code: PrintButton.CODE,
      icon: 'ant-design:printer-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: '推单',
      code: 'pushorder',
      icon: 'ant-design:appstore-filled',
      isDefault: true,
      setting: {
        type: 'api',
        formInfo: [],
      },
    },
  ];
  const defaultConfigs = [
    {
      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,
      isEnableLock: true,
    },
    {
      isUse: true,
      name: t('删除'),
      code: 'delete',
      icon: 'ant-design:delete-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('批量删除'),
      code: 'batchdelete',
      icon: 'ant-design:delete-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: '复制数据',
      code: 'copyData',
      icon: 'ant-design:copy-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('打印'),
      code: 'print',
      icon: 'ant-design:printer-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('模板打印'),
      code: PrintButton.CODE,
      icon: 'ant-design:printer-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: '推单',
      code: 'pushorder',
      icon: 'ant-design:appstore-filled',
      isDefault: true,
      setting: {
        type: 'api',
        formInfo: [],
      },
    },
    {
      isUse: false,
      name: t('批量设置权限所属人'),
      code: 'batchSetUserId',
      icon: 'ant-design:setting-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('快速导入'),
      code: 'import',
      icon: 'ant-design:import-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('快速导出'),
      code: 'export',
      icon: 'ant-design:export-outlined',
      isDefault: true,
    },
    {
      isUse: false,
      name: t('发起审批'),
      code: 'startwork',
      icon: 'ant-design:form-outlined',
      isDefault: true,
      isEnableLock: true,
      schemaInitConfig: {
        enabled: false,
        enabledAddApprove: false,
        config: {
          id: '',
        },
      },
    },
    {
      isUse: false,
      name: t('查看流转记录'),
      code: 'flowRecord',
      icon: 'ant-design:form-outlined',
      isDefault: true,
    },
  ];

  const settingBtn = computed(() => {
    return designType === 'notable' || unref(designType) === 'notable'
      ? ['batchdelete', 'pushorder']
      : ['pushorder'];
  });
  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 queryColumns = ref([
    {
      dataIndex: 'sort',
      key: 'sort',
      width: 70,
      align: 'center',
    },
    {
      title: t('查询项'),
      dataIndex: 'fieldName',
      key: 'fieldName',
      align: 'center',
    },
    {
      title: t('默认值'),
      dataIndex: 'fieldValue',
      key: 'fieldValue',
      align: 'center',
    },
    // {
    //   title: t('宽度'),
    //   dataIndex: 'width',
    //   key: 'width',
    //   width: '40%',
    // },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 108,
    },
  ]);

  const listDefaultColumns: BasicColumn[] = [
    {
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 50,
    },
    {
      title: t('列表名称'),
      dataIndex: 'label',
      key: 'label',
      align: 'center',
    },
    {
      title: t('列表字段'),
      dataIndex: 'columnName',
      key: 'columnName',
      align: 'center',
    },
    {
      title: t('对齐方式'),
      dataIndex: 'alignType',
      key: 'alignType',
      width: 120,
      align: 'center',
    },
    {
      title: t('开启行合并'),
      dataIndex: 'rowSpan',
      width: 108,
      key: 'rowSpan',
      align: 'center',
    },
    {
      title: t('自适应宽度'),
      dataIndex: 'autoWidth',
      width: 108,
      key: 'autoWidth',
      align: 'center',
    },
    {
      title: t('宽度'),
      dataIndex: 'columnWidth',
      key: 'columnWidth',
      width: 108,
      align: 'center',
    },
    {
      title: t('是否合计'),
      dataIndex: 'isTotal',
      width: 108,
      key: 'isTotal',
      align: 'center',
    },
    {
      title: '列头筛选',
      dataIndex: 'isFilter',
      key: 'isFilter',
      align: 'center',
      width: 108,
    },
    {
      title: '是否固定',
      dataIndex: 'isFixed',
      key: 'isFixed',
      align: 'center',
      width: 108,
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 88,
    },
  ];

  const listNotableColumns: BasicColumn[] = [
    {
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
      width: 50,
    },
    {
      title: t('列表字段'),
      dataIndex: 'columnName',
      key: 'columnName',
      align: 'center',
    },
    {
      title: t('对齐方式'),
      dataIndex: 'alignType',
      key: 'alignType',
      width: 120,
      align: 'center',
    },
    {
      title: t('自适应宽度'),
      dataIndex: 'autoWidth',
      width: 108,
      key: 'autoWidth',
      align: 'center',
    },
    {
      title: t('宽度'),
      dataIndex: 'columnWidth',
      key: 'columnWidth',
      width: 108,
      align: 'center',
    },
    {
      title: t('是否合计'),
      dataIndex: 'isTotal',
      width: 108,
      key: 'isTotal',
      align: 'center',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
      width: 88,
    },
  ];

  const listCardColumns: BasicColumn[] = [
    {
      dataIndex: 'sort',
      key: 'sort',
      align: 'center',
    },
    {
      title: t('列表字段'),
      dataIndex: 'columnName',
      key: 'columnName',
      width: '30%',
    },
    {
      title: t('对齐方式'),
      dataIndex: 'alignType',
      key: 'alignType',
      width: '15%',
    },
    {
      title: t('独占一行'),
      dataIndex: 'aRow',
      key: 'aRow',
      align: 'center',
    },
    {
      title: t('字段名加粗'),
      dataIndex: 'textBold',
      key: 'textBold',
    },
    {
      title: t('操作'),
      key: 'action',
      fixed: 'right',
      align: 'center',
    },
  ];

  const buttonColumns = ref([
    {
      title: t('启用'),
      dataIndex: 'isUse',
      key: 'isUse',
      width: '5%',
      align: 'center',
    },
    {
      title: t('按钮名称'),
      dataIndex: 'name',
      key: 'name',
      width: '27%',
    },
    {
      title: t('按钮编码'),
      dataIndex: 'code',
      key: 'code',
      width: '27%',
    },
    {
      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 pushOrderDialog = ref<boolean>(false);
  const startWorkDialog = ref<boolean>(false);
  const apiFormDialog = ref<boolean>(false);

  const staticDataVisible = ref<boolean>(false);
  let listColumns: BasicColumn[] = listDefaultColumns;

  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 pushOrderConfig = ref();
  const startWorkConfig = ref();
  const apiBtnConfig = ref();
  const settingCode = ref('');

  const selectOption: any = ref([]);
  const querySelectOption: any = ref([]);
  const queryConfigsData: any = ref([]);

  //过滤出 所有主表数据字段  子表的不需要  不在列表页展示的不需要
  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') {
          for (const child of item.layout!) {
            for (const el of child.list) {
              mainComponents = unionWith(
                mainComponents,
                filterMainComponent(el.children!, isSearch),
              );
            }
          }
        }
      } else if (item.type.indexOf('range') !== -1) {
        //查询配置不要时间范围和日期范围
        if (!isSearch) {
          mainComponents.push({
            key: item.key + random(10, 100),
            value: item.bindStartTime,
            label: t(`{name}开始时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
            componentProps: item.options,
          });
          mainComponents.push({
            key: item.key + random(10, 100),
            value: item.bindEndTime,
            label: t(`{name}结束时间`, { name: item.label }),
            type: item.type,
            format: item.options?.format,
            componentProps: item.options,
          });
        }
      } 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,
              isDate: true,
              format: item.options?.format,
              componentProps: item.options,
            });
          } 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: false,
              componentProps: { ...item.options, showTime: true, format: 'YYYY-MM-DD HH:mm:ss' },
            });
          } 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,
                isDate: false,
                componentProps: item.options,
              });
            }
          }
        }
      }
    }

    return mainComponents;
  };
  onMounted(async () => {
    //如果已经有按钮设置了 就不再添加默认值
    try {
      await initTreeData();
    } catch (error) {}
  });
  // const selectOption = computed(() => {
  //   let arr = filterMainComponent(generatorConfig?.formJson?.list);
  //   return arr.filter((o) => {
  //     return ['time', 'date'].includes(o.type) && o.componentProps.searchType == 'range'
  //       ? false
  //       : true;
  //   });
  // });

  // const querySelectOption = computed(() => {
  //   return filterMainComponent(generatorConfig?.formJson?.list, true);
  // });
  // const queryConfigsData = computed(() => {
  //   return querySelectOption.value.map((ele) => {
  //     ele.fieldName = ele.value;
  //     ele.schemas = {
  //       component: buildComponentType(ele.type),
  //       field: ele.value,
  //       label: ele.label,
  //       componentProps: ele.componentProps,
  //     };
  //     return ele;
  //   });
  // });
  watch(
    () => pushOrderConfig.value,
    (val) => {
      generatorConfig.listConfig.buttonConfigs.forEach((item) => {
        if (item.code === 'pushorder') {
          item.setting = val;
        }
      });
    },
    {
      deep: true,
    },
  );
  watch(
    () => startWorkConfig.value,
    (val) => {
      generatorConfig.listConfig.buttonConfigs.forEach((item) => {
        if (item.code === 'startwork') {
          item.schemaInitConfig = val;
        }
      });
    },
    {
      deep: true,
    },
  );

  function submitFormTree() {
    formTreeState.visible = false;
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig!.configTip =
      '已配置';
  }
  const getConfigInfo = () => {
    let listComponent = filterMainComponent(generatorConfig!.formJson!.list);
    let queryComponent = filterMainComponent(generatorConfig!.formJson!.list, true);
    let columnConfigs: ColumnConfig[] = [];
    let queryConfigs: QueryConfig[] = [];
    // 编辑时 列表配置需要判断key和绑定字段都相同时 则不进行处理
    // key不同并且绑定字段相同（数据优先换了组件但绑定的字段是绑定过的）、key相同绑定字段不同（数据优先已存在的组件换绑字段）
    if (props.isUpdate) {
      //新增时列表配置的组件
      const addColumns = generatorConfig.listConfig.columnConfigs.map((x) => {
        return { key: x.key, field: x.columnName, label: x.label };
      });
      //编辑时列表配置的组件
      const editColumns = listComponent.map((x) => {
        return {
          key: x.key,
          field: x.value,
          label: x.label,
          componentProps: x.componentProps,
        };
      });
      //编辑时列表配置没有被删除的组件（已经删除的组件删掉）
      columnConfigs = generatorConfig.listConfig.columnConfigs.filter((x) => {
        return editColumns.some((clm) => {
          if (clm.key === x.key && clm.field === x.columnName) {
            x.label = clm.label;
            x.componentProps = clm.componentProps;
            return true;
          }
        });
      });
      //除去列表配置新增时已经设置好的组件
      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) => {
        if (editQueryNames.includes(x.fieldName)) {
          let obj = queryComponent.find((o) => o.value == x.fieldName);
          if (obj && !['time', 'date'].includes(obj.type)) {
            return x;
          }
        }
      });
      //除去查询配置新增时已经设置好的组件
      queryComponent = queryComponent.filter(
        (x) => ['time', 'date'].includes(x.type) || !addQueryNames.includes(x.value),
      );
    }

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

    generatorConfig.listConfig.queryConfigs = queryComponent.map((component) => {
      const queryConfig: QueryConfig = {
        fieldName: component.value,
        isDate: ['time', 'date'].includes(component.type)
          ? component.componentProps.searchType == 'range'
            ? true
            : false
          : !!component.isDate,
        format: component.format || undefined,
      };
      if (
        ['time', 'date'].includes(component.type) &&
        component.componentProps.searchType == 'range'
      ) {
        queryConfig.isDateRange = true;
      }
      return queryConfig;
    });

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

  const handleStyleChange = (val) => {
    let mode = [LIST_MODE.DEFAULT, LIST_MODE.VERTICAL, LIST_MODE.HORIZONTAL];
    if (mode.includes(val)) {
      generatorConfig.listConfig.arrangeType = '';
      listColumns = designType === 'notable' ? listNotableColumns : listDefaultColumns;
    } else if (val === LIST_MODE.CARD) {
      generatorConfig.listConfig.arrangeType = 'two';
      listColumns = listCardColumns;
    }
  };

  watch(
    () => current.value,
    (val, oldVal) => {
      if (
        ((val === 1 && isCustomForm) || !isCustomForm) &&
        !generatorConfig.listConfig?.buttonConfigs?.length
      ) {
        generatorConfig.listConfig.buttonConfigs =
          designType === 'notable' || unref(designType) === 'notable' ? configs : defaultConfigs;
      }
      handleStyleChange(generatorConfig.listConfig.listStyle);
      pushOrderConfig.value = generatorConfig.listConfig.buttonConfigs.find(
        (item) => item.code === 'pushorder',
      )?.setting;
      startWorkConfig.value = generatorConfig.listConfig.buttonConfigs.find(
        (item) => item.code === 'startwork',
      )?.schemaInitConfig;
      if (!isCustomForm && !props.isFormGenerator && val === 3 && oldVal !== 4) {
        if (designType !== 'data') {
          let tableFieldConfigs = getMainTable(generatorConfig.tableStructureConfigs);

          changeCompsApiConfig(generatorConfig.formJson.list, designType, tableFieldConfigs);
          changeEventApiConfig(generatorConfig.formEventConfig, designType, tableFieldConfigs);
        }
      }
      if (
        (!isCustomForm && !props.isFormGenerator && val === 3 && oldVal !== 4) ||
        ((isCustomForm || props.isFormGenerator) && val === 1)
      ) {
        loading.value = false;

        getConfigInfo();
        apiConfig.value = cloneDeep(
          generatorConfig?.listConfig.leftMenuConfig![leftMenuIndex.value]!.apiConfig,
        );
      }
    },
    {
      immediate: true,
    },
  );
  function changeHeaderMergingData(val) {
    if (generatorConfig.listConfig.isHeaderMerging) {
      generatorConfig!.listConfig!.headerMergingData = val;
    } else {
      generatorConfig!.listConfig!.headerMergingData = [];
    }
  }
  function changeQueryConfig(index) {
    let record = queryConfigsData.value[index];
    let arr = querySelectOption.value.filter(function (elem) {
      return record.fieldName == elem.value;
    });
    if (arr.length > 0) {
      let ele = arr[0];
      if (ele.schemas) {
        queryConfigsData.value[index].schemas = ele.schemas;
      } else {
        queryConfigsData.value[index].schemas = {
          component: buildComponentType(ele.type),
          field: ele.value,
          label: ele.label,
          componentProps: ele.componentProps,
        };
      }
    }
    queryTableKey.value++;
  }
  watch(
    () => generatorConfig?.listConfig?.queryConfigs,
    (val) => {
      if (val && val.length) {
        let arr = filterMainComponent(generatorConfig?.formJson?.list);
        selectOption.value = arr.filter((o) => {
          return ['time', 'date'].includes(o.type) && o.componentProps.searchType == 'range'
            ? false
            : true;
        });
        querySelectOption.value = filterMainComponent(generatorConfig?.formJson?.list, true);
        queryConfigsData.value = cloneDeep(querySelectOption.value).map((ele) => {
          ele.fieldName = ele.value;
          ele.schemas = {
            component: buildComponentType(ele.type),
            field: ele.value,
            label: ele.label,
            componentProps: ele.componentProps,
          };
          return ele;
        });
        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 - 1, 0, columns[oldIndex - 1]);
                columns.splice(oldIndex, 1);
              } else {
                columns.splice(newIndex, 0, columns[oldIndex - 1]);
                columns.splice(oldIndex - 1, 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') {
        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![leftMenuIndex.value].apiConfig = cloneDeep(val);
      delete generatorConfig!.listConfig.leftMenuConfig![leftMenuIndex.value].apiConfig?.script;
    },
    {
      deep: true,
    },
  );
  watch(
    () => generatorConfig.listConfig.isAdvancedQuery,
    (_val: boolean) => {
      // 存储所有查询配置列表
      generatorConfig.listConfig.querySelectOption = JSON.stringify(querySelectOption.value);
    },
  );
  // const datasourceColumns = ref<string[]>([]);

  const showApiDialog = () => {
    apiConfigDialog.value = true;
  };

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

  const queryAdd = () => {
    //给各个组件赋默认值
    const pushObj = {
      fieldName: '',
      fieldValue: '',
      schemas: null,
      isDate: false,
    };
    queryConfigsData.value.push(pushObj);
  };

  const queryRemove = (index) => {
    queryConfigsData.value.splice(index, 1);
  };

  const columnAdd = () => {
    //给各个组件赋默认值
    const pushObj: ColumnConfig = {
      key: '',
      label: '',
      columnName: '',
      columnWidth: '100',
      alignType: '',
      autoWidth: true,
      isTotal: false,
      isFilter: false,
      isFixed: false,
      componentType: '',
      aRow: generatorConfig.listConfig.arrangeType === 'one',
      textBold: false,
    };
    generatorConfig?.listConfig?.columnConfigs.push(pushObj);
    // queryOptionData.value.push(pushObj);
  };

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

  const buttonAdd = () => {
    //给各个组件赋默认值
    const pushObj: ButtonConfig = {
      isUse: true,
      name: '',
      code: '',
      icon: '',
      isDefault: false,
      setting: [],
      showType: 'top',
      buttonType: 'primary',
    };
    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![leftMenuIndex.value].staticData);
      } else {
        //父级新增
        generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].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 delLeftMenuConfig = (index) => {
    generatorConfig?.listConfig.leftMenuConfig!.splice(index, 1);
    if (leftMenuIndex.value === index) {
      leftMenuIndex.value = index - 1 || 0;
    }
  };

  // const delTreeNode = (node, key) => {
  //   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 = () => {
  //   staticDataVisible.value = true;
  //   currentKey.value = '';
  //   modelTitle.value = t('添加父级选项');
  // };
  // const addTreeNode = (key, title) => {
  //   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 handleArrageChange = (val) => {
    generatorConfig.listConfig.columnConfigs.forEach((item) => {
      item.aRow = val === 'one';
    });
  };

  //切换数据来源的时候 调用 获取数据源字段接口
  // const handleDatasourceChange = async (id: string): Promise<void> => {
  //   datasourceColumns.value = await getDatasourceColumn(id);
  // };
  //切换数据来源的时候 默认清理掉其他数据
  const handleRadioChange = (e): void => {
    if (e.target.value === 'api') {
      generatorConfig!.listConfig!.leftMenuConfig![leftMenuIndex.value].dictionaryItemId = '';
    } else {
      generatorConfig!.listConfig!.leftMenuConfig![leftMenuIndex.value].fieldName = '';
      generatorConfig!.listConfig!.leftMenuConfig![leftMenuIndex.value].relationFieldName = '';
    }
  };
  async function initTreeData() {
    let res = await geList();
    treeSelectOption.value = res;
  }

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

  //验证当前步骤的数据
  const validateStep = async (): Promise<boolean> => {
    generatorConfig.listConfig.queryConfigs = queryConfigsData.value.map((ele) => {
      if (ele.fieldValue && Array.isArray(ele.fieldValue) && ele.fieldValue.length == 2) {
        ele.fieldValue = ele.fieldValue.join(',');
      }
      return ele;
    });
    const { listConfig } = generatorConfig;
    if (
      generatorConfig!.listConfig!.orderByArr &&
      generatorConfig!.listConfig!.orderByArr.length > 0
    )
      generatorConfig!.listConfig!.orderBy = generatorConfig!.listConfig!.orderByArr.join(',');
    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.some((x) => !x.datasourceType)) {
        notification.error({
          message: t('提示'),
          description: t('必须选择数据来源！'),
        }); //提示消息
        return false;
      }

      if (leftMenuConfig.some((x) => x.datasourceType === 'tree' && !x.treeConfig.id)) {
        notification.error({
          message: t('提示'),
          description: t('必须选择树！'),
        }); //提示消息
        return false;
      } else {
        if (leftMenuConfig.some((x) => x.datasourceType !== 'tree' && !x.listFieldName)) {
          notification.error({
            message: t('提示'),
            description: t('必须选择列表关联字段！'),
          }); //提示消息
          return false;
        }
      }

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

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

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

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

        //关联字段
        if (dataSoureConfig.some((x) => !x.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 handleCheck(e) {
    if (e.code == 'startwork') {
      generatorConfig?.listConfig?.buttonConfigs.some((o) => {
        if (o.code == 'flowRecord') {
          o.isUse = e.isUse;
          return true;
        } else {
          return false;
        }
      });
    }
  }
  function buttonDisabled(e) {
    let disabled = false;
    generatorConfig?.listConfig?.buttonConfigs.some((o) => {
      if (o.code == 'startwork' && e.code == 'flowRecord') {
        disabled = !o.isUse;
        return true;
      } else {
        return false;
      }
    });
    return disabled;
  }
  function addTreeConfig() {
    generatorConfig.listConfig.leftMenuConfig!.push({
      datasourceType: 'tree',
      listFieldName: undefined,
      apiConfig: {},
      dictionaryItemId: undefined,
      menuName: '',
      parentIcon: '',
      childIcon: '',
      staticData: [],
      treeConfig: {
        id: '',
        name: '',
        type: TreeStructureType.STATIC,
        configTip: '',
        config: [],
        isMultiple: false,
      },
    });
    leftMenuIndex.value = generatorConfig.listConfig.leftMenuConfig!.length - 1;
  }
  function resetTreeConfig() {
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.id = '';
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.config = [];
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.isMultiple = false;
  }
  async function changeTreeConfigId(id) {
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.config = [];
    let res = await getInfo(id);
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.type = res.type;
    generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.name = res.name;
    if (
      generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].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![leftMenuIndex.value].treeConfig.config.push({
          bindFiled: '',
          name:
            generatorConfig.listConfig.leftMenuConfig![leftMenuIndex.value].treeConfig.type ==
            TreeStructureType.STATIC
              ? getTitle(columns[labelIndex].title)
              : columns[labelIndex].title,
          value: columns[index].dataIndex,
        });
      }
    }
  }
  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 handleSetting(code) {
    if (code === 'pushorder') {
      pushOrderDialog.value = true;
    } else {
      settingCode.value = code;
      apiFormDialog.value = true;
      apiBtnConfig.value = generatorConfig.listConfig.buttonConfigs.find(
        (item) => item.code === code,
      )?.apiConfig;
    }
  }

  function getBtnConfig(config) {
    generatorConfig.listConfig.buttonConfigs?.forEach((item) => {
      if (item.code === settingCode.value) {
        item.apiConfig = config;
      }
    });
  }

  function handleStartWorkSetting() {
    startWorkDialog.value = true;
  }

  function changeConfig(config) {
    generatorConfig.listConfig.apiConfig = config;
  }
  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(.vben-basic-table .ant-table) {
    height: auto;
  }

  :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-tab) {
      padding: 7px !important;
      min-width: 80px;
    }

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

    :deep(.ant-tabs-tab-btn) {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    :deep(.ant-tabs-nav-wrap) {
      display: inline-flex !important;
    }

    .close-icon {
      position: absolute;
      right: 0;
      top: calc(50% - 7px);
      margin: 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;
    }
  }

  .node-title {
    border-bottom: 1px solid #e5e7eb;
    padding: 10px;
    margin-bottom: 16px;
  }
</style>
