<template>
  <div class="table-search detail__info" :id="formid">
    <el-form
      ref="formRef"
      :model="searchParam"
      :label-position="isLabelPosition"
      :label-width="publicAttr.labelWidth"
      hide-required-asterisk
      :rules="rules"
      @submit.prevent
      @keyup.enter="handleKeyDown"
    >
      <div class="flx-col relative">
        <div class="setting-aside absolute" style="right: 0; z-index: 10" v-if="ifLayoutEditable && !settingStatus">
          <el-button class="enter-x" circle :icon="Operation" @click="gotoSetting"></el-button>
        </div>
        <!--setting-->
        <div class="setting-part flx-shrink mb-8" v-if="settingStatus">
          <header class="flx">
            <section class="funcitons flx-start">
              <el-button class="-enter-y" type="success" plain :icon="Plus" @click="toAddField">{{
                $t("common.addText") + $t("common.table.basicinfo.field")
              }}</el-button>
              <el-button
                class="-enter-y"
                type="danger"
                :icon="DeleteFilled"
                @click="toDeleteShow"
                :disabled="!selectColumn.length"
                >{{ `${$t("common.delText") + $t("common.table.basicinfo.field")}(${selectColumn.length})` }}</el-button
              >
              <el-divider direction="vertical" />
              <el-button-group class="-enter-y">
                <el-popover :visible="visibleNewGroup" trigger="click" placement="top" :width="280">
                  <el-form label-position="top" @submit.prevent>
                    <el-form-item :label="$t('common.table.newGroupTitle')">
                      <el-input
                        ref="newGroupNameRef"
                        class="w-full"
                        v-model.trim="newGroupName"
                        :placeholder="$t('common.inputText') + $t('common.table.newGroupTitle')"
                        input-style="width:80px"
                        @keyup.enter="toAddGroup"
                      />
                    </el-form-item>
                  </el-form>
                  <div class="flx-justify-between">
                    <el-space>
                      <el-select
                        v-model="newGroupSpan"
                        :placeholder="String(searchCol[breakPoint])"
                        class="flx-1"
                        :teleported="false"
                      >
                        <template #prefix>
                          <span class="text-f-c text-disable">{{ $t("sys.setting.columnNum") }}</span>
                        </template>
                        <el-option v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem" :value="ritem" />
                      </el-select>
                      <el-button text @click="visibleNewGroup = false">{{ $t("common.cancelText") }}</el-button>
                      <el-button class="btn-group" type="primary" @click="toAddGroup">{{ $t("common.okText") }}</el-button>
                    </el-space>
                  </div>
                  <template #reference>
                    <el-button class="btn-group" type="primary" @click="handleOpenAddGroupPopo" :disabled="!selectColumn.length">
                      <template #icon>
                        <i class="iconfont icongrid-01"></i>
                      </template>
                      {{ `${$t("common.table.newBasicGroup")}(${selectColumn.length})` }}
                    </el-button>
                  </template>
                </el-popover>
                <el-button :icon="Switch" @click="toToggleShowHideBatch" :disabled="!selectColumn.length">{{
                  $t("common.table.toggleShowHide")
                }}</el-button>
                <el-button type="danger" plain :icon="Brush" @click="toClearSelect" :disabled="!selectColumn.length">{{
                  $t("common.table.clearSelect")
                }}</el-button>
              </el-button-group>
            </section>
            <!-- <span class="text-disable text-h5-m flx-1 text-center">
              {{ $t("common.table.basicinfo.title") }}
            </span> -->
            <div class="flx-1 flx-center mr-4" id="settingSearchInput">
              <el-input
                v-model="searchField"
                :prefix-icon="Search"
                clearable
                style="width: 240px"
                :placeholder="$t('business.baseMsgSetting.searchPh')"
                @clear="searchEvent"
                @input="disshow(searchField)"
              >
                <template #suffix v-if="searchField.length">
                  {{ matchSearchNum + $t("business.baseMsgSetting.matchColNum") }}
                </template>
                <template #append v-if="matchSearchNum">
                  <!-- <el-badge :value="matchSearchNum" class="item"> -->
                  <el-button
                    class="select-match"
                    type="primary"
                    @click="handleSelectMatch"
                    :icon="Select"
                    :title="t('common.table.selectMatch')"
                  ></el-button>
                  <!-- </el-badge> -->
                </template>
              </el-input>
              <!-- <el-tooltip effect="dark" :content="$t('common.table.sesarhFilter')" placement="top" :show-after="200">
                <el-button
                  :type="ifSearchFilter ? 'primary' : 'default'"
                  plain
                  class="ml-8 pl-10 pr-10"
                  @click="
                    () => {
                      ifSearchFilter = !ifSearchFilter;
                      disshow(searchField);
                    }
                  "
                >
                  <template #icon>
                    <i class="iconfont" :class="ifSearchFilter ? 'iconfilter-funnel-01-fill' : 'iconfilter-funnel-01'"></i>
                  </template>
                </el-button>
              </el-tooltip> -->
            </div>
            <aside class="control flx-shrink">
              <el-button class="enter-x" :icon="Refresh" @click="resetSetting">{{ $t("common.resetText") }}</el-button>
              <el-divider direction="vertical" />
              <el-button
                v-if="userInfo.usercode?.trim().toLocaleLowerCase() != 'super'"
                class="enter-x"
                type="primary"
                :icon="Check"
                @click="settingConfirm(formRef)"
                :loading="confirmBtnLoading"
                >{{ $t("common.saveText") }}</el-button
              >
              <el-dropdown
                v-else
                split-button
                class="enter-x mr-12"
                type="primary"
                :disabled="confirmBtnLoading"
                @click="settingConfirm(formRef)"
              >
                <el-icon class="mr-8">
                  <component :is="confirmBtnLoading ? Loading : Check"></component>
                </el-icon>
                {{ $t("common.saveText") }}
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="saveDefaultClick">
                      {{ $t("sys.layout.settings") }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button class="enter-x" :icon="Close" @click="cancelSetting">{{ $t("common.cancelText") }}</el-button>
            </aside>
          </header>
          <!-- <main class="mt-8 flx-start">
            <div class="setting-main_public -enter-y">
              <header class="text-body-b mb-4 flx-justify-between">
                {{ $t("sys.setting.publicAttr") }}
                <span class="text-border">{{ breakPoint }}</span>
              </header>
              <el-form :model="publicAttr">
                <el-form-item prop="labelWidth" class="mb-8" v-if="publicAttr.labelPosition != 'top'">
                  <div class="flx-center">
                    <span class="text-body-c text-secondary-text mr-8 white-nowrap-word"
                      >{{ $t("sys.setting.labelWidth") }}:</span
                    >
                    <el-input class="w-full" v-model="publicAttr.labelWidth" placeholder="auto" input-style="width:120px" />
                  </div>
                </el-form-item>
                <el-form-item class="mb-0" prop="labelPosition">
                  <div class="flx-center">
                    <span class="text-body-c text-secondary-text mr-8">{{ $t("sys.setting.align") }}:</span>
                    <el-radio-group v-model="publicAttr.labelPosition" :id="'public.labelPosition'">
                      <el-radio-button label="left">{{ $t("sys.setting.left") }}</el-radio-button>
                      <el-radio-button label="right">{{ $t("sys.setting.right") }}</el-radio-button>
                      <el-radio-button label="top">{{ $t("sys.setting.top") }}</el-radio-button>
                    </el-radio-group>
                  </div>
                </el-form-item>
              </el-form>
            </div>

            <div
              v-if="activeColumn"
              class="setting-main_private ml-12 -enter-y"
              :class="{
                'is-group': !filterTitle(activeColumn),
                'is-match': selectColumn.length > 1 && selectColumn.includes(activeColumn.field)
              }"
            >
              <header class="text-body-b mb-4">
                {{
                  selectColumn.length > 1 && selectColumn.includes(activeColumn.field)
                    ? `${$t("sys.setting.privateAttr")}:${filterTitle(activeColumn)} \+${selectColumn.length - 1}${$t(
                        "business.baseMsgSetting.matchColNum"
                      )}`
                    : filterTitle(activeColumn)
                    ? `${$t("sys.setting.privateAttr")}:${filterTitle(activeColumn)}`
                    : `${$t("common.table.newGroup")}:` +
                      (activeColumn.label ? htmlDecodeByRegExp(activeColumn.label) : $t("common.notGrouped"))
                }}
              </header>
              <el-form :model="publicAttr">
                <el-form-item>
                  <div class="flx-center">
                    <span class="text-body-c text-secondary-text mr-8 white-nowrap-word">{{ $t("sys.setting.columnNum") }}:</span>
                    <template v-if="activeColumn?.basicinfo">
                      <el-radio-group
                        v-model="activeColumn.basicinfo.span"
                        @change="(val: any) => handleChangeColSpan(val, activeColumn)"
                      >
                        <el-radio-button v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem">{{
                          ritem
                        }}</el-radio-button>
                      </el-radio-group>
                    </template>
                    <template v-else>
                      <el-radio-group v-model="activeColumn.span">
                        <el-radio-button v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem">{{
                          ritem
                        }}</el-radio-button>
                      </el-radio-group>
                    </template>
                  </div>
                </el-form-item>
                <el-form-item class="mt-8">
                  <div class="flx-center">
                    <span class="text-body-c text-secondary-text mr-8 white-nowrap-word">{{ $t("sys.setting.rowNum") }}:</span>
                    <template v-if="activeColumn?.basicinfo">
                      <el-input-number
                        v-model="activeColumn.basicinfo.row"
                        :step="1"
                        :min="1"
                        :max="100"
                        style="width: 120px"
                        placeholder="1"
                        @change="(val: any) => handleChangeColSpan(val, activeColumn, 'row')"
                      />
                    </template>
                    <template v-else>
                      <el-input-number
                        v-model="activeColumn.row"
                        :step="1"
                        :min="1"
                        :max="100"
                        style="width: 120px"
                        placeholder="1"
                        @change="(val: any) => handleChangeColSpan(val, activeColumn, 'row')"
                      />
                    </template>
                  </div>
                </el-form-item>
                <el-form-item class="mb-0 mt-8" v-if="activeColumn.formatEnum">
                  <div class="flx-center">
                    <span class="text-body-c text-secondary-text mr-8 white-nowrap-word">{{ $t("sys.setting.format") }}:</span>
                    <el-select v-model="activeColumn.format" class="m-2" :placeholder="$t('sys.setting.notSet')" clearable>
                      <el-option
                        v-for="item in formatEnumMap?.get(activeColumn.field)"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                </el-form-item>
              </el-form>
            </div>
          </main> -->
        </div>

        <Grid
          :id="formid + '-basicform-groups'"
          ref="gridRef"
          class="basicform-groups flx-1"
          :class="{ setting: settingStatus }"
          :gap="[8, 8]"
          :cols="basicGroupCol"
          :setting="settingStatus"
          :target="formid + `-basicform-groups`"
          @click.stop="handleShowMenu"
        >
          <template #default="scope">
            <template v-if="settingStatus">
              <draggable
                :list="groupFlatColumns"
                :style="scope?.style"
                item-key="label"
                animation="300"
                forceFallback="true"
                handle=".group_handle"
                :group="{ name: 'basicinfoGroup' }"
                @sort="handleSortGroup"
              >
                <template #item="{ element, index }">
                  <GridItem
                    class="detail__info-group"
                    :span="Number(element.span ?? searchCol[breakPoint])"
                    :row="element.row ?? 1"
                    :index="index"
                    :class="{
                      'is-active': activeColumn && activeColumn.label == element.label
                    }"
                  >
                    <!-- @click="!settingStatus && (element.collapsed = !element.collapsed)" -->
                    <div
                      class="title group_handle relative mb-4"
                      @click.stop="ev => handleSelFormItem(element, ev, true)"
                      :class="{
                        'has-hidden': hideGroup(element.list).length > 0 && !settingStatus,
                        'text-h4-m': tableSize == '',
                        'text-h5-m': tableSize == 'medium',
                        'text-body-m': tableSize == 'mini'
                      }"
                      :style="{ lineHeight: FORM_LINE_HEIGHT[globalStore.assemblySize] + 'px' }"
                    >
                      <span class="text-primary-text" style="cursor: text" v-if="!element.edit" @click="toEditAliase(element)">
                        <i class="iconfont iconEditSquare_light"></i>
                        {{ element.label ? htmlDecodeByRegExp(element.label) : $t("common.notGrouped") }}
                      </span>
                      <el-input
                        v-else
                        ref="aliaseInputRef"
                        :class="`detail__info__aliase-input`"
                        v-model.trim="labelInput"
                        style="width: auto"
                        maxlength="20"
                        :placeholder="$t('business.detailSetting.basicGroupName')"
                        @blur="toSaveBaceGroupLabel(element, index)"
                        @keydown.enter="toSaveBaceGroupLabel(element, index)"
                      />
                      <!-- <template v-if="hideGroup(element.list).length > 0 && !settingStatus">
                      <el-text type="primary" link class="search-isOpen ml-8">
                        {{ element.collapsed ? $t("common.table.expand") : $t("common.table.putAway") }}
                        <el-icon class="el-icon--right">
                          <component :is="element.collapsed ? ArrowDown : ArrowUp"></component>
                        </el-icon>
                      </el-text>
                    </template> -->
                      <div class="header-right">
                        <i class="iconfont iconmove text-border mr-12"></i>
                        <el-tooltip
                          effect="dark"
                          :content="isGroupAllSelect(element) ? $t('common.table.unSelectAll') : $t('common.table.selectAll')"
                          placement="top"
                          :show-after="200"
                        >
                          <el-button
                            type="primary"
                            size="small"
                            plain
                            circle
                            class="ml-8 pl-10 pr-10"
                            @click.stop="handleSelectAll(element)"
                          >
                            <template #icon>
                              <i class="iconfont" :class="isGroupAllSelect(element) ? 'iconcheck-square' : 'iconsquare'"></i>
                            </template>
                          </el-button>
                        </el-tooltip>
                        <el-popconfirm
                          width="220"
                          position=""
                          :confirm-button-text="$t('common.delText')"
                          :cancel-button-text="$t('common.cancelText')"
                          :icon="WarningFilled"
                          icon-color="#626AEF"
                          :title="$t('common.table.delGroupTips')"
                          @confirm="toDelGroup(element)"
                        >
                          <template #reference>
                            <el-button size="small" type="danger" plain circle :icon="Delete"></el-button>
                          </template>
                        </el-popconfirm>
                      </div>
                    </div>

                    <Grid
                      class="detail__info-group-list"
                      :collapsed="collapsed"
                      :gap="[8, 2]"
                      :cols="getSpan(element.span, breakPoint)"
                      :setting="settingStatus"
                    >
                      <template #default="scopeGrad">
                        <draggable
                          :list="element.list"
                          :style="scopeGrad?.style"
                          item-key="field"
                          animation="300"
                          :id="element.label ?? 'notgroup'"
                          forceFallback="true"
                          :group="{ name: 'basicinfo' }"
                          @start="handleSortDragStart"
                          @sort="handleSortDrag"
                        >
                          <template #item="groupScope">
                            <GridItem
                              v-if="groupScope.element.basicinfo?.visible !== false"
                              :key="groupScope.index"
                              v-bind="getResponsive(groupScope.element)"
                              :index="groupScope.index"
                              :name="groupScope.element.field"
                              :row="groupScope.element.basicinfo?.row ?? 1"
                              @click.stop="ev => handleSelFormItem(groupScope.element, ev)"
                            >
                              <el-form-item
                                :title="filterTitle(groupScope.element)"
                                class="setting-grid-item"
                                :class="{
                                  'is-active': activeColumn && activeColumn.field == groupScope.element.field,
                                  'is-hidden': groupScope.element?.basicinfo.ishidden,
                                  'is-dragselect': selectColumn.includes(groupScope.element.field),
                                  'is-label-top': publicAttr.labelPosition == 'top',
                                  'is-match': groupScope.element.isMatch
                                }"
                                :data-field="groupScope.element.field"
                              >
                                <template #label>
                                  <span class="text-ellipsis-two">
                                    {{ filterTitle(groupScope.element) }}
                                  </span>
                                </template>
                                <template v-if="groupScope.element.basicinfo?.render">
                                  <BaseFormItem
                                    :field="groupScope.element.field"
                                    :column="groupScope.element.basicinfo ?? {}"
                                    :field-names="groupScope.element.fieldNames"
                                    :search-param="searchParam"
                                  />
                                </template>
                                <template v-else-if="groupScope.element?.render">
                                  <BaseFormItem
                                    :field="groupScope.element.field"
                                    :column="groupScope.element"
                                    :field-names="groupScope.element.fieldNames"
                                    :search-param="searchParam"
                                  />
                                </template>
                                <el-input
                                  v-else
                                  :value="formatFunc(searchParam[handleProp(groupScope.element.field!)], groupScope.element)"
                                  disabled
                                  v-bind="{ ...groupScope.element.basicinfo.props, ...cpBasicinfoAttr(groupScope.element) }"
                                />

                                <div class="setting-grid-item__field">
                                  {{ groupScope.element.field }}
                                </div>
                                <el-button
                                  class="hidden-btn"
                                  :icon="groupScope.element.basicinfo?.ishidden ? View : Hide"
                                  circle
                                  size="small"
                                  style="z-index: 99"
                                  @click.stop="toToggleShowItem(groupScope.element, index)"
                                ></el-button>
                              </el-form-item>
                            </GridItem>
                          </template>
                        </draggable>
                      </template>
                    </Grid>
                  </GridItem>
                </template>
              </draggable>
            </template>
            <template v-else>
              <template v-for="(groupItem, groupIdx) in groupFlatColumns" :key="groupIdx">
                <GridItem
                  class="detail__info-group"
                  v-if="getVisibleLength(groupItem)"
                  :span="Number(groupItem.span ?? searchCol[breakPoint])"
                  :row="groupItem.row ?? 1"
                  :index="groupIdx"
                >
                  <el-skeleton animated :loading="loading" class="mb-8" v-if="groupItem.label">
                    <template #template><el-skeleton-item variant="h3" style="height: 24px; vertical-align: middle" /></template>
                    <div class="group-header flx">
                      <div
                        class="title flx-1 flx-start"
                        @click="!settingStatus && (groupItem.collapsed = !groupItem.collapsed)"
                        :class="{
                          'has-hidden': hideGroup(groupItem.list).length > 0 && !settingStatus,
                          'text-h4-m': tableSize == '',
                          'text-h5-m': tableSize == 'medium',
                          'text-body-m': tableSize == 'mini'
                        }"
                      >
                        <span class="header-title">
                          {{ groupItem.label ? groupItem.label : $t("common.notGrouped") }}
                        </span>
                        <template v-if="hideGroup(groupItem.list).length > 0 && !settingStatus">
                          <el-text type="primary" link class="search-isOpen ml-8">
                            {{ groupItem.collapsed ? $t("common.table.expand") : $t("common.table.putAway") }}
                            <el-icon class="el-icon--right">
                              <component :is="groupItem.collapsed ? ArrowDown : ArrowUp"></component>
                            </el-icon>
                          </el-text>
                        </template>
                      </div>
                      <div class="flx-shrink">
                        <slot :name="'group-header-' + groupIdx"> </slot>
                      </div>
                    </div>
                  </el-skeleton>

                  <Grid
                    class="detail__info-group-list"
                    :collapsed="collapsed"
                    :gap="[16, 2]"
                    :cols="getSpan(groupItem.span, breakPoint)"
                    :setting="settingStatus"
                  >
                    <template #default>
                      <template v-for="(item, index) in showGroup(groupItem.list)" :key="item.field">
                        <GridItem
                          v-if="!item?.basicinfo?.disabled && getIfcanEditVisible(item)"
                          v-bind="getResponsive(item)"
                          :index="index"
                          :row="item.basicinfo?.row ?? 1"
                        >
                          <!-- :class="{'to-search': editable && ![undefined, ''].includes(searchParam[item.basicinfo?.key ?? handleProp(item.field!)])}" -->
                          <!-- :required="item.basicinfo?.required ?? false" -->
                          <el-skeleton
                            animated
                            :loading="typeof searchParam[handleProp(item.field!)]  == 'undefined' && loading"
                            class="mr-12"
                          >
                            <template #template
                              ><el-skeleton-item variant="h3" style="height: 30px; vertical-align: middle"
                            /></template>
                            <el-form-item
                              :title="filterTitle(item)"
                              :prop="item.basicinfo?.key ?? handleProp(item.field!)"
                              :rules="item.rules"
                              :class="{
                                'is-label-top': publicAttr.labelPosition == 'top',
                                'is-editable': getIfCanEditable(item)
                              }"
                              :data-field="item.field"
                            >
                              <template #label>
                                <span class="text-ellipsis-two">
                                  {{ filterTitle(item) }}
                                </span>
                              </template>
                              <template
                                v-if="
                                  getIfCanEditable(item) ||
                                  (item?.basicinfo && item.basicinfo?.render) ||
                                  item?.render ||
                                  item?.enum
                                "
                              >
                                <!-- v-if="getIfCanEditable(item) && ((item?.basicinfo && item.basicinfo?.render) || item?.render)" -->
                                <BaseFormItem
                                  :field="item.field"
                                  :column="getBaseFormCol(item)"
                                  :field-names="item.fieldNames"
                                  :search-param="searchParam"
                                  :disabled="!editable"
                                />
                              </template>
                              <el-input
                                v-else
                                :value="formatFunc(searchParam[handleProp(item.field!)], item)"
                                disabled
                                v-bind="{ ...item.basicinfo.props, ...cpBasicinfoAttr(item) }"
                              />
                              <template #error="errScope">
                                <div class="error-box flx-center" v-if="errScope.error">
                                  <el-tooltip :content="errScope.error" placement="top">
                                    <el-icon><WarningFilled /></el-icon>
                                  </el-tooltip>
                                </div>
                              </template>
                            </el-form-item>
                          </el-skeleton>
                        </GridItem>
                      </template>

                      <template v-if="!groupItem.collapsed">
                        <GridItem
                          v-if="hideGroup(groupItem.list).length > 0"
                          :span="getSpan(groupItem.span, breakPoint)"
                          :row="groupItem.row ?? 1"
                        >
                          <el-divider content-position="left">
                            <span class="text-disable">隐藏字段</span>
                          </el-divider>
                        </GridItem>

                        <GridItem
                          v-for="(item, index) in hideGroup(groupItem.list)"
                          :key="item.field"
                          :row="item.basicinfo?.row ?? 1"
                          v-bind="getResponsive(item)"
                          :index="index"
                        >
                          <!-- :class="{'to-search': editable && ![undefined, ''].includes(searchParam[item.basicinfo?.key ?? handleProp(item.field!)])}" -->
                          <el-form-item
                            v-if="getIfcanEditVisible(item)"
                            :title="filterTitle(item)"
                            :prop="item.basicinfo?.key ?? handleProp(item.field!)"
                            :rules="item.rules"
                            :required="item.basicinfo?.required ?? false"
                            :class="{
                              'is-label-top': publicAttr.labelPosition == 'top',
                              'is-editable': getIfCanEditable(item)
                            }"
                          >
                            <template #label>
                              <span class="text-ellipsis-two">
                                {{ filterTitle(item) }}
                              </span>
                            </template>
                            <el-skeleton
                              animated
                              :loading="typeof searchParam[handleProp(item.field!)]  == 'undefined' && loading"
                              class="mr-12"
                              v-if="getIfcanEditVisible(item)"
                            >
                              <template #template
                                ><el-skeleton-item variant="h3" style="height: 30px; vertical-align: middle"
                              /></template>

                              <template
                                v-if="(getIfCanEditable(item) && item?.basicinfo && item.basicinfo?.render) || item?.render"
                              >
                                <BaseFormItem
                                  :field="item.field"
                                  :column="getBaseFormCol(item)"
                                  :field-names="item.fieldNames"
                                  :search-param="searchParam"
                                  :disabled="!editable"
                                />
                              </template>
                              <el-input v-else :value="formatFunc(searchParam[handleProp(item.field!)], item)" disabled />
                            </el-skeleton>
                          </el-form-item>
                        </GridItem>
                      </template>
                    </template>
                  </Grid>
                </GridItem>
              </template>
            </template>
          </template>
        </Grid>
      </div>
    </el-form>

    <!--悬浮功能菜单-->
    <LjFloatingMenu ref="FloatingMenuRef" @menu-item-click="handleFloatingMenuClick">
      <template #default="{ menuItemClick }">
        <div class="flx-col">
          <div class="flx-start">
            <div class="setting-main_public flx-center">
              <header class="text-f-c mr-4 text-secondary-text">
                {{ $t("common.table.basicinfo.publicAttr") }}
              </header>
              <el-form :model="publicAttr" class="flx-center">
                <el-form-item prop="labelWidth" class="mr-8" v-if="publicAttr.labelPosition != 'top'">
                  <el-input
                    class="w-full"
                    v-model="publicAttr.labelWidth"
                    placeholder="auto"
                    input-style="width:30px"
                    :title="$t('sys.setting.labelWidth')"
                  >
                    <template #prefix>
                      <span class="text-f-c text-disable">{{ $t("sys.setting.labelWidth") }}</span>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item class="mb-0" prop="labelPosition">
                  <el-select
                    v-model="publicAttr.labelPosition"
                    :placeholder="$t('sys.setting.align')"
                    style="width: 90px"
                    :teleported="false"
                  >
                    <template #prefix>
                      <span class="text-f-c text-disable">{{ $t("sys.setting.align") }}</span>
                    </template>
                    <el-option :label="$t('sys.setting.left')" value="left" />
                    <el-option :label="$t('sys.setting.right')" value="right" />
                    <el-option :label="$t('sys.setting.top')" value="top" />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <el-divider v-if="activeColumn" direction="vertical" />
            <div v-if="activeColumn" class="setting-main_private flx-center">
              <header class="text-f-c mr-8 text-secondary-text">
                <el-badge
                  class="item"
                  :value="selectColumn.length > 1 && selectColumn.includes(activeColumn?.field) ? selectColumn.length : ''"
                  type="primary"
                >
                  {{ filterTitle(activeColumn) ? `${$t("common.table.basicinfo.attr")}` : `${$t("common.table.newGroup")}:` }}
                </el-badge>
              </header>
              <el-form :model="publicAttr" class="flx-center">
                <el-form-item>
                  <template v-if="activeColumn?.basicinfo">
                    <el-select
                      v-model="activeColumn.basicinfo.span"
                      :placeholder="String(searchCol[breakPoint])"
                      style="width: 100px"
                      :teleported="false"
                      @change="(val: any) => handleChangeColSpan(val, activeColumn)"
                    >
                      <template #prefix>
                        <span class="text-f-c text-disable">{{ $t("sys.setting.columnNum") }}</span>
                      </template>
                      <el-option v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem" :value="ritem" />
                    </el-select>
                  </template>
                  <template v-else>
                    <el-select
                      v-model="activeColumn.span"
                      style="width: 100px"
                      :placeholder="String(searchCol[breakPoint])"
                      :teleported="false"
                    >
                      <template #prefix>
                        <span class="text-f-c text-disable">{{ $t("sys.setting.columnNum") }}</span>
                      </template>
                      <el-option v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem" :value="ritem + ''" />
                    </el-select>
                  </template>
                </el-form-item>
                <el-form-item class="ml-8">
                  <div class="flx-center">
                    <span class="text-f-c text-secondary-text mr-4 white-nowrap-word">{{ $t("sys.setting.rowNum") }}:</span>
                    <template v-if="activeColumn?.basicinfo">
                      <el-input-number
                        v-model="activeColumn.basicinfo.row"
                        :step="1"
                        :min="1"
                        :max="100"
                        style="width: 65px"
                        controls-position="right"
                        placeholder="1"
                        @change="(val: any) => handleChangeColSpan(val, activeColumn, 'row')"
                      />
                    </template>
                    <template v-else>
                      <el-input-number
                        v-model="activeColumn.row"
                        :step="1"
                        :min="1"
                        :max="100"
                        style="width: 65px"
                        controls-position="right"
                        placeholder="1"
                        @change="(val: any) => handleChangeColSpan(val, activeColumn, 'row')"
                      />
                    </template>
                  </div>
                </el-form-item>
                <el-form-item class="mb-0 ml-8" v-if="activeColumn.formatEnum">
                  <el-select
                    v-model="activeColumn.format"
                    :placeholder="$t('sys.setting.notSet')"
                    clearable
                    style="width: 150px"
                    :teleported="false"
                  >
                    <template #prefix>
                      <span class="text-f-c text-disable">{{ $t("sys.setting.format") }}</span>
                    </template>
                    <el-option
                      v-for="item in formatEnumMap?.get(activeColumn.field)"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-button-group v-if="activeColumn && curGroup" class="mt-4">
            <el-button text @click="menuItemClick('edit', () => toEditAliase(curGroup))">
              <template #icon>
                <i class="iconfont iconEditSquare_light"></i>
              </template>
            </el-button>
            <el-button
              text
              :title="isGroupAllSelect(curGroup) ? $t('common.table.unSelectAll') : $t('common.table.selectAll')"
              @click="menuItemClick('Check', () => handleSelectAll(curGroup))"
            >
              <template #icon>
                <i class="iconfont" :class="isGroupAllSelect(curGroup) ? 'iconcheck-square' : 'iconsquare'"></i>
              </template>
            </el-button>
            <el-popconfirm
              width="220"
              position=""
              :confirm-button-text="$t('common.delText')"
              :cancel-button-text="$t('common.cancelText')"
              :icon="WarningFilled"
              icon-color="#626AEF"
              :title="$t('common.table.delGroupTips')"
              @confirm="menuItemClick('DeleteGroup', () => toDelGroup(curGroup))"
            >
              <template #reference>
                <el-button type="danger" text plain :icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </el-button-group>
          <el-button-group v-else class="mt-4">
            <el-button
              text
              :icon="Plus"
              :title="$t('common.addText') + $t('common.table.basicinfo.field')"
              @click="menuItemClick('plus', toAddField)"
            ></el-button>
            <el-button
              text
              :icon="DeleteFilled"
              type="danger"
              plain
              :title="$t('common.delText') + $t('common.table.basicinfo.field')"
              @click="menuItemClick('DeleteAttr')"
            ></el-button>
            <el-button
              text
              :disabled="!selectColumn.length"
              :title="$t('common.table.newBasicGroup')"
              @click="menuItemClick('group', handleOpenAddGroupPopo)"
            >
              <template #icon>
                <i class="iconfont icongrid-01"></i>
              </template>
            </el-button>
            <el-button
              text
              :icon="Switch"
              :title="$t('common.table.toggleShowHide')"
              @click="menuItemClick('Switch', toToggleShowHideBatch)"
            ></el-button>
            <el-button
              text
              :disabled="!selectColumn.length"
              :icon="Brush"
              :title="$t('common.table.clearSelect')"
              @click="menuItemClick('Brush', toClearSelect)"
            ></el-button>
          </el-button-group>
        </div>
      </template>
    </LjFloatingMenu>
    <!-- 列设置 -->
    <BasicInfoSelect ref="BasicInfoSelectRef" @confirm="toAddFieldsConfirm" />
  </div>
</template>
<script setup lang="tsx" name="BaseForm">
import { computed, ref, inject, watch, getCurrentInstance, onMounted, provide, nextTick } from "vue";
import { ColumnProps, SearchProps } from "@/components/LjVxeTable/interface";
import { BreakPoint } from "@/components/Grid/interface";
import {
  Delete,
  Brush,
  ArrowDown,
  ArrowUp,
  Operation,
  Check,
  Close,
  Refresh,
  Search,
  View,
  Hide,
  WarningFilled,
  Select,
  Switch,
  Loading,
  DeleteFilled,
  Plus
} from "@element-plus/icons-vue";
import BaseFormItem from "./BaseFormItem.vue";
import Grid from "@/components/Grid/index.vue";
import GridItem from "@/components/Grid/components/GridItem.vue";
import draggable from "vuedraggable";
import { cloneDeep, pick, uniq, defaults, throttle, defaultsDeep } from "lodash-es";
import { getDifference, handleProp, handleRowAccordingToProp, isMobile } from "@/utils";
import { ElMessage, ElNotification, ElAffix, type FormInstance, type FormRules } from "element-plus";
import { useI18n } from "vue-i18n";
import { useGlobalStore } from "@/stores/modules/global";
import { BasicDefaultType, BasicGroupType } from "../interface";
import { htmlEncodeByRegExp, htmlDecodeByRegExp } from "@/utils";
import { useUserStore } from "@/stores/modules/user";
import { isArray, isFunction } from "@/utils/is";
import { TABLE_LAYOUT_BASICINFO_ATTR, FORM_LINE_HEIGHT } from "@/config";
import BasicInfoSelect from "./BasicInfoSelect.vue";
import LjFloatingMenu from "@/components/LjFloatingMenu/index.vue";
import { useMagicKeys, whenever } from "@vueuse/core";
import { classNameIncludes } from "@/utils/index";
import tableJson from "@/languages/modules/zh-cn/table.json";

interface GroupBasicProps {
  label?: string;
  list: ColumnProps[];
  /**
   * @description 是否收起隐藏字段
   */
  collapsed?: boolean;
  span?: number;
  row?: number;
  edit?: boolean;
}

interface BaseFormProps {
  /**
   * @description 主表列数据
   */
  columns?: ColumnProps[];
  searchParam?: { [key: string]: any }; // 搜索参数
  /**
   * @description 属性gird响应占位
   */
  searchCol?: number | Record<BreakPoint, number> | any;
  /**
   * @description 分组gird响应占位
   */
  basicGroupCol?: number | Record<BreakPoint, number> | any;
  /**
   * @argument string[] 布局读取/保存时，赋值的属性
   */
  layoutAttr?: string[];
  /**
   * @argument Object 布局默认设置，保存时移除，的属性
   */
  layoutAttrDefine?: BasicDefaultType;
  /**
   * @argument boolean 是否折叠
   */
  collapse?: boolean;
  /**
   * @argument any form表单属性
   */
  formProps: any;
  /**
   * @description 组件唯一标识
   */
  formid?: string;
  /**
   * @description 是否禁止修改布局
   */
  disableSetting?: boolean;
  loading?: boolean;
  /**
   * @description 是否可编辑布局
   */
  ifLayoutEditable?: boolean;
}

// 定义一个变量来存储取消订阅的函数
let unsubscribe: any = null;

// 获取键盘事件
// const { ctrl } = useMagicKeys();
// watch(ctrl, v => {
const { shift } = useMagicKeys();

/**
 * @description 是否可编辑
 */
const editable = inject("editable", ref(false));
const rules = inject("rules", undefined);
const formatEnumMap = inject("baseFormatEnumMap", ref(new Map()));
const { t } = useI18n();
const { userInfo } = useUserStore();
const emit = defineEmits(["confirm", "reset", "saveDefault", "toSetting", "beforeClose"]);

/**
 * @description 是否可编辑
 */
const orderStatus = inject("orderStatus", ref(""));

// 默认值
const props = withDefaults(defineProps<BaseFormProps>(), {
  columns: () => [],
  searchParam: () => ({}),
  layoutAttr: () => [],
  layoutAttrDefine: () => ({}),
  collapse: false,
  searchCol: () => ({ xs: 1, sm: 2, md: 3, lg: 4, xl: 5 }),
  basicGroupCol: () => ({ xs: 3, sm: 3, md: 6, lg: 6, xl: 6 }),
  formid: "formref",
  disableSetting: false
});

// 获取响应式设置
const getResponsive = (item: ColumnProps) => {
  return {
    span: item.basicinfo?.span,
    offset: item.basicinfo?.offset ?? 0,
    xs: item.basicinfo?.xs,
    sm: item.basicinfo?.sm,
    md: item.basicinfo?.md,
    lg: item.basicinfo?.lg,
    xl: item.basicinfo?.xl
  };
};

const globalStore = useGlobalStore();
const tableSize = computed(() => {
  let _size = "";
  switch (globalStore.assemblySize) {
    case "large":
      _size = "";
      break;
    case "small":
      _size = "mini";
      break;
    default:
      _size = "medium";
      break;
  }
  return _size;
});

/**
 * @description 是否默认折叠搜索项
 */
const collapsed = ref(props.collapse);
// const collapsed = ref(false);

/**
 * @description 是否正在编辑
 */
const settingStatus = ref(false);
/**
 * @description 保存按钮加载状态
 */
const confirmBtnLoading = ref(false);

// 获取响应式断点
const gridRef = ref();
const breakPoint = computed<BreakPoint>((): BreakPoint => gridRef.value?.breakPoint);
const isLabelPosition = computed(() => {
  // if (["xs", "sm"].includes(breakPoint.value)) {
  //   return "top";
  // }
  if (isMobile()) return "top";
  return publicAttr.value.labelPosition;
});
// const breakPoint = ref("xl");
// provide("breakPoint", breakPoint);
//另外如果需要全局改变msg,provide接受一个方法作为参数
// provide("breakPointUpdate", (data: any, target: string) => {
//   //此处可以接受参数，也可以不接受参数
//   console.log("breakPointUpdate breakPoint.value  :>> ", data);
//   breakPoint.value = data;
// });

// // 判断是否显示 展开/合并 按钮
// const showCollapse = computed(() => {
//   let show = false;
//   props.columns.reduce((prev, current) => {
//     prev +=
//       (current.basicinfo![breakPoint.value]?.span ?? current.basicinfo?.span ?? 1) +
//       (current.basicinfo![breakPoint.value]?.offset ?? current.basicinfo?.offset ?? 0);
//     if (typeof props.searchCol !== "number") {
//       if (prev > props.searchCol[breakPoint.value]) show = true;
//     } else {
//       if (prev > props.searchCol) show = true;
//     }
//     return prev;
//   }, 0);
//   return show;
// });

/**
 * @description 悬浮快捷菜单
 */
const FloatingMenuRef = ref();
/**
 * @description 当前选中的分组
 */
const curGroup = ref<any>(null);
/**
 * @description 记录当前选中的column
 */
const activeColumn = ref<any>(null);
/**
 * @description 当前已选的 column组
 */
const selectColumn = ref<any>([]);
/**
 * 编辑状态，点击某个column
 * @param item 搜索项item
 */
const handleSelFormItem = (item: any, ev: any, isGroup = false) => {
  nextTick(() => {
    console.log("handleSelFormItem ev :>> ", shift.value, ev, isGroup);
    if (!settingStatus.value && isGroup) {
      item.collapsed = !item.collapsed;
    } else {
      if (isGroup) {
        if (activeColumn.value && activeColumn.value.label == item.label) {
          activeColumn.value = null;
          curGroup.value = null;
          searchField.value && searchEvent();
          FloatingMenuRef.value.hideMenu();
          return;
        }
        curGroup.value = item;
      } else {
        curGroup.value = null;
      }
      searchField.value && searchEvent();
      let hasIdx = selectColumn.value.indexOf(item.field);
      if (!isGroup) {
        if (shift.value) {
          if (hasIdx === -1) {
            selectColumn.value.push(item.field);
          } else {
            selectColumn.value.splice(hasIdx, 1);
          }
        } else {
          let beforeInside = selectColumn.value.includes(item.field);
          console.log("handleSelFormItem drag.value.getSelection() bf beforeInside:>> ", drag.value.getSelection(), beforeInside);
          let before = drag.value.getSelection() ?? [];
          // if (!selectColumn.value.includes(item.field)) {
          let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
          drag.value && drag.value.toggleSelection([oDiv], true);
          let after = drag.value.getSelection() ?? [];
          console.log(
            "handleSelFormItem drag.value.getSelection() af:>> ",
            drag.value.getSelection(),
            before.length,
            after.length
          );
          if (before.length < after.length && !beforeInside) {
            drag.value && drag.value.toggleSelection([oDiv], true);
            console.log("handleSelFormItem drag.value.getSelection() afffffffffff:>> ", drag.value.getSelection());
          }
        }
      }
      activeColumn.value = item;
    }

    FloatingMenuRef.value.showMenu(ev);
  });
};

const handleShowMenu = (ev: any) => {
  if (settingStatus.value) {
    FloatingMenuRef.value.showMenu(ev, true);
  }
};

/**
 * @description 悬浮功能菜单回调
 * @param event 点击事件对象
 * @param {String} action 动作
 * @param {Function} cb 功能事件回调
 * @param {Function} menuCb 组件回调：关闭菜单
 */
const handleFloatingMenuClick = (event: any, action: string, cb?: any, menuCb?: any) => {
  if (action == "DeleteAttr") {
    let _field = event.target.getAttribute("data-field");
    if (_field && !selectColumn.value.includes(_field)) {
      groupFlatColumns.value.forEach((items: any) => {
        items.list.forEach((itm: any) => {
          if (itm.field == _field) {
            itm.basicinfo.visible = false;
            return;
          }
        });
      });
    } else {
      toDeleteShow();
    }
  } else if (action == "Check") {
    cb && cb();
    return;
  }
  cb && cb();
  menuCb && menuCb();
};

/**
 * @description 初始转化的columns；记录设置前记录，方便还原
 */
const flatColumns = ref<GroupBasicProps[]>();
/**
 * @description 展示columns
 */
const groupFlatColumns = ref<GroupBasicProps[]>([]);
let publicAttr = ref<any>({});
const resetPublicAttr = (val = props.formProps) => {
  publicAttr.value.labelPosition = val.labelPosition ?? props.layoutAttrDefine.labelPosition;
  publicAttr.value.labelWidth = val.labelWidth ?? props.layoutAttrDefine.labelWidth;
  publicAttr.value.basicGroup = val.basicGroup ?? props.layoutAttrDefine.basicGroup;
};

declare let DragSelect: any;
const drag = ref<any>(null);

/**
 * @description 拖拽选择时，阻止默认事件的类名列表
 */
const classNamesToCheck = [
  "group_handle", // 分组拖拽按钮
  "setting-grid-item",
  // "el-input__inner", // 搜索输入框
  "hidden-btn", // 字段隐藏按钮
  "select-match" // 搜索输入框
];
/**
 * @description 初始化拖拽
 */
const initDragSelect = () => {
  // settingFooterRef.value?.updateRoot();
  drag.value && drag.value.stop();
  drag.value = null;
  drag.value = new DragSelect({
    selectables: document.getElementsByClassName("setting-grid-item"),
    area: document.getElementById(props.formid + "-basicform-groups"),
    selectedClass: "to-dragselect",
    multiSelectMode: true,
    onDragStart: (element: any) => {
      console.log(element.target);
      console.log(element.target.parentNode);
      console.log(element.target.parentNode.parentNode);
      if (element && element.target) {
        let includesResult = classNameIncludes(element.target, classNamesToCheck);
        console.log("element.target.className :>> ", element.target.className);
        console.log("element.target. includesResult :>> ", includesResult);

        if (includesResult) {
          drag.value.break();
        }
      }

      console.log("onDragStart selectColumn.value :>> ", JSON.stringify(selectColumn.value), drag.value.getSelection());
    },
    // onElementSelect(el: any) {
    //   console.log("onElementSelect el :>> ", el);
    // },
    // onElementUnselect(el: any) {
    //   console.log("onElementUnselect el :>> ", el);
    // },
    callback: (arr: any) => {
      //鼠标抬起后返回所有选中的元素
      console.log("callback arr :>> ", arr);
      selectColumn.value = [];

      if (!arr.length) {
        activeColumn.value = null;
        return;
      }

      arr.forEach((item: any) => {
        let _field = item.getAttribute("data-field");
        selectColumn.value.push(_field);
      });

      let _field = selectColumn.value[selectColumn.value.length - 1];
      console.log("_field :>> ", _field, activeColumn.value);
      // if (!activeColumn.value || !selectColumn.value.includes(activeColumn.value.field)) {
      if (!activeColumn.value) {
        let _item = null;
        groupFlatColumns.value.forEach((items: any) => {
          let tg_item = items.list.find((item: any) => item.field == _field);
          if (tg_item) {
            _item = tg_item;
            return;
          }
        });

        activeColumn.value = _item;
      }

      console.log("activeColumn.value: >>", activeColumn.value, selectColumn.value);
    }
  });
};

/**
 * @description 占用列数，点击时
 */
const handleChangeColSpan = (val: any, data: any, attr = "span") => {
  console.log("handleChangeColSpan selectColumn.value, val :>> ", selectColumn.value, val, data);
  if (selectColumn.value.includes(data.field)) {
    let matchNum = 0;
    groupFlatColumns.value.map((items: any) => {
      items.list.map((item: any) => {
        let hasIdx = selectColumn.value.indexOf(item.field);
        if (hasIdx > -1) {
          item.basicinfo[attr] = val;
          matchNum++;
        }
        if (matchNum == selectColumn.value.length) {
          return;
        }
      });
    });
  }
};

/**
 * @description 按钮：开始编辑
 */
const gotoSetting = () => {
  collapsed.value = false;
  settingStatus.value = true;
  activeColumn.value = null;
  // console.log("props.columns :>> ", props.columns);
  flatColumns.value = cloneDeep(groupFlatColumns.value);
  console.log("flatColumns.value  :>> ", flatColumns.value);

  emit("toSetting");

  resetPublicAttr();
  console.log("gotoSetting flatColumns.value :>> ", flatColumns.value);

  // 监听特定的键盘事件，例如 'Escape'
  // unsubscribe = whenever(ctrl, () => {
  //   console.log("Escape key was pressed");
  // });
  nextTick(() => {
    initDragSelect();

    ElMessage({
      dangerouslyUseHTMLString: true,
      message: '<span class="keyboard-shortcut">Shift</span>' + t("common.table.basicinfo.settingTips"),
      type: "info"
    });
  });
};

/**
 * @description 整理保存数据
 */
const saveLayoutFunc = () => {
  publicAttr.value.basicGroup = groupFlatColumns.value.map((item: any) => {
    return {
      label: item.label,
      ...(item.span && { span: item.span }),
      ...(item.row && { row: item.row })
    };
  });

  let _oriBase = cloneDeep(props.layoutAttrDefine);
  if (!_oriBase.basicGroup) _oriBase.basicGroup = [];

  // 补充默认分组中，差异的部分
  publicAttr.value.basicGroup.forEach((item: any) => {
    let idx = _oriBase.basicGroup.findIndex((i: any) => i.label === item.label);
    if (idx == -1) {
      _oriBase.basicGroup.push({ label: item.label });
    }
  });

  console.log("_oriBase :>> ", _oriBase);
  console.log("publicAttr.value :>> ", publicAttr.value);

  let diff = getDifference(_oriBase, publicAttr.value, TABLE_LAYOUT_BASICINFO_ATTR, "label");

  let hasSpan = diff.basicGroup.findIndex((item: any) => item.span != undefined);
  console.log("hasSpan :>> ", hasSpan);
  console.log("diff :>> ", diff);
  console.log("_oriBase :>> ", _oriBase);
  if (hasSpan == -1) {
    let sortDiff = diff.basicGroup.map((item: any) => item.label);
    let sortOri = _oriBase.basicGroup.map((item: any) => item.label);
    console.log(sortDiff);
    console.log(sortOri);
    console.log(sortDiff.join(",") == sortOri.join(","));
    if (sortDiff.join(",") == sortOri.join(",")) {
      // 与原始配置相同，不进行任何操作
      diff.basicGroup = [];
    }
  }
  console.log("after diff :>> ", diff);
  return diff;
};
/**
 * @description 按钮：设置窗口，保存事件
 */
const settingConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("flatColumns.value :>> ", groupFlatColumns.value);

      confirmBtnLoading.value = true;

      // publicAttr.value.basicGroup = groupFlatColumns.value.map((item: any) => {
      //   return {
      //     label: item.label,
      //     span: item.span
      //   };
      // });

      // let _oriBase = cloneDeep(props.layoutAttrDefine);
      // if (!_oriBase.basicGroup) _oriBase.basicGroup = [];

      // // 补充默认分组中，差异的部分
      // publicAttr.value.basicGroup.forEach((item: any) => {
      //   let idx = _oriBase.basicGroup.findIndex((i: any) => i.label === item.label);
      //   if (idx == -1) {
      //     _oriBase.basicGroup.push({ label: item.label });
      //   }
      // });

      // console.log("_oriBase :>> ", _oriBase);
      // console.log("publicAttr.value :>> ", publicAttr.value);

      // let _detailLayoutAttr = ["labelPosition", "labelWidth", "basicGroup", "label", "span"];
      // let diff = getDifference(_oriBase, publicAttr.value, _detailLayoutAttr, "label");

      // let hasSpan = diff.basicGroup.findIndex((item: any) => item.span != undefined);
      // console.log("diff :>> ", diff);
      // console.log("_oriBase :>> ", _oriBase);
      // if (hasSpan == -1) {
      //   let sortDiff = diff.basicGroup.map((item: any) => item.label);
      //   let sortOri = _oriBase.basicGroup.map((item: any) => item.label);
      //   console.log(sortDiff);
      //   console.log(sortOri);
      //   console.log(sortDiff.join(",") == sortOri.join(","));
      //   if (sortDiff.join(",") == sortOri.join(",")) {
      //     // 与原始配置相同，不进行任何操作
      //     diff = {};
      //   }
      // }

      let diff = saveLayoutFunc();
      console.log("settingConfirm diff :>> ", diff);

      emit("confirm", groupFlatColumns.value, diff, () => {
        settingStatus.value = false;
        confirmBtnLoading.value = false;
        searchField.value = "";

        toDefaultValue();
        emit("beforeClose");
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const toDefaultValue = () => {
  selectColumn.value = [];
  activeColumn.value = null;
  newGroupName.value = "";
  visibleNewGroup.value = false;

  drag.value && drag.value.stop();
  drag.value = null;
};

/**
 * @description 按钮：取消设置
 */
const cancelSetting = () => {
  settingStatus.value = !settingStatus.value;
  searchField.value = "";

  resetPublicAttr();

  groupFlatColumns.value = cloneDeep(flatColumns.value);

  toDefaultValue();

  emit("beforeClose");

  console.log("cancelSetting unsubscribe :>> ", unsubscribe);
  if (unsubscribe) {
    unsubscribe();
  }
};

/**
 * @description 按钮：重置设置
 */
const resetSetting = () => {
  emit("reset", (data: any) => {
    if (!data?.columns.length) return;
    let dafine = defaultsDeep(data.tableprop?.basicinfo ?? {}, props.layoutAttrDefine);
    resetPublicAttr(dafine);

    groupFlatColumns.value = getInfoBaseForm(data.columns);
    console.log("groupFlatColumns.value  :>> ", groupFlatColumns.value);
    searchField.value && searchEvent();
    toClearSelect();

    nextTick(() => {
      initDragSelect();
    });

    ElMessage.success(t("sys.api.operationSuccess"));
  });
};

const BasicInfoSelectRef = ref();
/**
 * @description 按钮：新增显示字段
 */
const toAddField = () => {
  // settingBtnLoading.value = true;
  setTimeout(() => {
    let _columns = cloneDeep(props.columns);
    console.log("toAddField _columns bf :>> ", _columns);
    console.log("toAddField groupFlatColumns.value bf :>> ", groupFlatColumns.value);

    // 根据groupFlatColumns.value里对应的field字段，反向更新_columns里对应的basicinfo.visible字段
    groupFlatColumns.value.map((items: any) => {
      items.list.map((item: any) => {
        _columns.forEach((column: any) => {
          if (column.field === item.field) {
            column.basicinfo = item.basicinfo;
          }
        });
      });
    });
    console.log("toAddField _columns :>> ", _columns);

    let _groupName = "";
    if (curGroup.value) {
      _groupName = curGroup.value.label;
    } else if (activeColumn.value) {
      groupFlatColumns.value.map((items: any) => {
        let _itm = items.list.find((item: any) => item.field === activeColumn.value.field);
        if (_itm) {
          _groupName = items.label;
        }
      });
    }

    BasicInfoSelectRef.value?.open(_columns, _groupName);
    // settingBtnLoading.value = false;
  }, 1);
};

/**
 * @description 新增显示字段: 确认反馈
 */
const toAddFieldsConfirm = (fields: string[], group: any, cb: any) => {
  console.log("groupFlatColumns.value :>> ", groupFlatColumns.value);
  funcChangeGroup(fields, group);
  cb && cb();
};

/**
 * @description 转移目标字段
 * @param {Array} fields 目标字段名称集合
 * @param {String\Undefined} groupName 分组名称
 * @param {Number} newIndex 插入索引, 默认为末尾
 */
const funcChangeGroup = (fields: string[], groupName: any, newIndex?: number) => {
  // 提取其他组中的目标
  let _tgArr: any = [];
  groupFlatColumns.value.map((items: any) => {
    items.list.map((item: any) => {
      if (fields.includes(item.field)) {
        item.basicinfo?.visible === false && delete item.basicinfo.visible;
        item.basicinfo.group = groupName;
        _tgArr.push(item);
      }
    });
  });
  console.log(_tgArr);

  // 排序
  let columnIndexMap = new Map();
  fields.forEach((field: any, index: number) => {
    columnIndexMap.set(field, index);
  });

  // 更新排序
  _tgArr = _tgArr.sort((a: any, b: any) => {
    return columnIndexMap.get(a.field) - columnIndexMap.get(b.field);
  });

  let ifNewGroup = groupFlatColumns.value.findIndex((items: any) => items.label === groupName) === -1;
  let countBefore = 0;
  if (ifNewGroup) {
    groupFlatColumns.value.push({
      label: groupName,
      list: []
    });
  }
  if (newIndex != undefined) {
    // 提取目标组
    groupFlatColumns.value.forEach(items => {
      if (groupName === items.label) {
        fields.map((item: any) => {
          let insideIdx = items.list.findIndex(i => i.field === item);
          if (insideIdx > -1) {
            insideIdx <= newIndex && countBefore++;
          }
        });
      }
      items.list = items.list.filter((item: any) => !fields.includes(item.field));
    });

    // 插入目标组
    let spIdx = newIndex - countBefore + 1;
    groupFlatColumns.value.forEach((items: any) => {
      if (groupName === items.label) {
        _tgArr.reverse().forEach((item: any) => {
          items.list.splice(spIdx, 0, item);
        });
      }
    });
  } else {
    groupFlatColumns.value.forEach(items => {
      items.list = items.list.filter((item: any) => !fields.includes(item.field));
    });
    // 插入目标组
    groupFlatColumns.value.forEach((items: any) => {
      if (groupName === items.label) {
        items.list = items.list.concat(_tgArr);
      }
    });
  }
};

/**
 * @description 按钮：清空选中列
 */
const toClearSelect = () => {
  selectColumn.value = [];
  drag.value.clearSelection();
  visibleNewGroup.value = false;
};

/**
 * @description 按钮：批量切换显示/隐藏
 */
const toToggleShowHideBatch = (event: any) => {
  let _field = event.target.getAttribute("data-field");
  console.log("toToggleShowHideBatch !!!!:>> ", _field, event);
  if (_field) {
    groupFlatColumns.value = groupFlatColumns.value.map((items: any) => {
      let idx = items.list.findIndex((itm: any) => itm.field === _field);
      if (idx > -1) {
        items.list[idx].basicinfo.ishidden = !items.list[idx].basicinfo?.ishidden;
      }
      return items;
    });
  } else {
    selectColumn.value.forEach((field: any) => {
      groupFlatColumns.value = groupFlatColumns.value.map((items: any) => {
        let idx = items.list.findIndex((itm: any) => itm.field === field);
        if (idx > -1) {
          items.list[idx].basicinfo.ishidden = !items.list[idx].basicinfo?.ishidden;
        }
        return items;
      });
    });
  }

  // 重新排序，隐藏的字段排后面
  groupFlatColumns.value.map((item: any) => {
    item.list.sort((a: any, b: any) => {
      let aIsHidden = Number(a.basicinfo.ishidden ?? false);
      let bIsHidden = Number(b.basicinfo.ishidden ?? false);
      return aIsHidden - bIsHidden;
    });
  });
};

/**
 * @description 按钮：删除字段显示
 */
const toDeleteShow = () => {
  groupFlatColumns.value.forEach((items: any) => {
    items.list.forEach((itm: any) => {
      if (selectColumn.value.includes(itm.field)) {
        itm.basicinfo.visible = false;
      }
    });
  });

  toClearSelect();
};

/**
 * @description 字段按钮：切换显示/隐藏
 */
const toToggleShowItem = (item: any, index: number) => {
  let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
  drag.value && drag.value.toggleSelection([oDiv], true);

  item.basicinfo.ishidden = !item.basicinfo?.ishidden;
  console.log("toToggleShow item :>> ", item);

  console.log("index :>> ", index);
  console.log("groupFlatColumns.value[index].list :>> ", groupFlatColumns.value[index].list);
  groupFlatColumns.value[index].list.sort((a: any, b: any) => {
    let aIsHidden = Number(a.basicinfo.ishidden ?? false);
    let bIsHidden = Number(b.basicinfo.ishidden ?? false);
    return aIsHidden - bIsHidden;
  });
  console.log("toToggleShow groupFlatColumns.value :>> ", groupFlatColumns.value[index].list);
};

const formRef = ref<FormInstance>();

/**
 * @description 格式化展示数据
 */
const formatFunc: any = computed((text: string, item: any) => (text: string, item: any): string => {
  if (item?.format) {
    return handleRowAccordingToProp(props.searchParam, item.field!, item?.format);
  }
  return text;
});

/**
 * @description 获取字段是否可编辑
 */
const getIfCanEditable = (item: any) => {
  if (item.hasOwnProperty("basicinfo") && item?.basicinfo.hasOwnProperty("editable")) {
    if (isArray(item.basicinfo?.editable)) {
      return item.basicinfo?.editable.includes(orderStatus.value);
    } else if (isFunction(item.basicinfo?.editable)) {
      return item.basicinfo?.editable({ item: item, searchParam: props.searchParam, status: orderStatus.value });
    }
  } else {
    return false;
  }
};

/**
 * @description 编辑时，获取字段是否可见
 */
const getIfcanEditVisible = (item: any) => {
  if (
    item.hasOwnProperty("basicinfo") &&
    item?.basicinfo.hasOwnProperty("editvisible") &&
    isFunction(item.basicinfo?.editvisible)
  ) {
    return item.basicinfo?.editvisible({ item: item, searchParam: props.searchParam, status: orderStatus.value });
  }
  return true;
};

const getGroup = (list: any) => {
  let arr: any = [];
  list.forEach((item: any) => {
    if (!item.basicinfo) {
      item.basicinfo = {
        order: 9999
      };
    } else if (!item.basicinfo?.order) {
      item.basicinfo.order = 9999;
    }
  });
  list.sort((a: any, b: any) => {
    return a.basicinfo.order - b.basicinfo.order;
  });
  list.forEach((item: any) => {
    if (item.basicinfo.group) {
      arr.push(item.basicinfo.group);
    } else {
      // undefined or "" 划分同一类，“”：标识之前是其他group的，转移至未分组
      arr.push(undefined);
    }
  });
  arr = uniq(arr);
  return arr;
};

/**
 * @description 计算出分组后的数据
 * @param data columns
 */
const getInfoBaseForm = (data: any) => {
  let result: any = [];
  let _data = cloneDeep(data);
  // _data = _data.filter((itm: any) => itm?.basicinfo?.visible !== false);
  let groups = getGroup(_data);

  groups.forEach((item: any) => {
    let list = _data.filter((i: any) => {
      if (!item && (!i.basicinfo || i.basicinfo?.group === item || i.basicinfo?.group === "" || i.field == "pid")) {
        return true;
      }
      return i.basicinfo?.group === item;
    });
    result.push({
      label: item ?? "",
      list: list,
      collapsed: true,
      edit: false
    });
  });

  result.forEach((item: any) => {
    item.list.sort((a: any, b: any) => {
      return a.basicinfo.order - b.basicinfo.order;
    });
  });

  /**如：已定义分组属性，读取并赋值 */
  if (isArray(publicAttr.value?.basicGroup) && publicAttr.value?.basicGroup.length) {
    let sortStr = publicAttr.value.basicGroup.map((item: any) => item.label);

    result = result.map((item: any) => {
      let getItm = publicAttr.value.basicGroup!.find((itm: any) => item.label == itm.label);
      console.log(getItm);
      let _item = {
        ...getItm,
        ...item
      };
      return _item;
    });

    result.sort((a: any, b: any) => {
      return sortStr.indexOf(a.label) - sortStr.indexOf(b.label);
    });
  }

  return result;
};

/**
 * @description 过滤转换失败的标题
 * @param col column
 */
const filterTitle = (item: any) => {
  let _title = item.title;
  let _tableJson: any = tableJson;
  if (item.basicinfo?.labelHidden) {
    return "";
  }
  if (Object.keys(_tableJson).includes(item.table)) {
    if (item.basicinfo?.titleKey) {
      Object.keys(_tableJson[item.table]).includes(item.basicinfo?.titleKey) &&
        (_title = t(`table.${item.table}.${item.basicinfo?.titleKey}`));
    } else if (item.basicinfo?.key) {
      Object.keys(_tableJson[item.table]).includes(item.basicinfo?.key) &&
        (_title = t(`table.${item.table}.${item.basicinfo?.key}`));
    } else {
      Object.keys(_tableJson[item.table]).includes(item.field) && (_title = t(`table.${item.table}.${item.field}`));
    }
  }
  return _title;
};

watch(
  () => props.columns,
  val => {
    if (!val.length) return;
    // publicAttr = ref({
    //   labelPosition: val[0].basicinfo?.labelPosition,
    //   labelWidth: val[0].basicinfo?.labelWidth
    // });

    resetPublicAttr();

    groupFlatColumns.value = getInfoBaseForm(val);

    console.log(" watch onMounted groupFlatColumns.value :>> ", groupFlatColumns.value, val);
  },
  { deep: true, immediate: true }
);

watch(
  () => props.formProps,
  val => {
    resetPublicAttr(val);

    groupFlatColumns.value = getInfoBaseForm(props.columns);

    console.log(" watch onMounted formProps groupFlatColumns.value :>> ", groupFlatColumns.value);
  },
  { deep: true }
);

const target = ref();

/**
 * @description 处理form标题过长，
 */
const resetLabel = () => {
  let _define = FORM_LINE_HEIGHT[globalStore.assemblySize];
  let elLabelArr = document.getElementsByClassName("el-form-item__label");
  (Array.from(elLabelArr) || []).forEach((ele: any) => {
    let currenNOde: any = ele.children[0];
    if (currenNOde) {
      currenNOde.style.cssText += `;line-height:${_define}px!important`;
      let rate = currenNOde.offsetHeight / _define;
      currenNOde.style.cssText += `;line-height:${rate > 1 ? _define / rate : _define}px!important;`;
    }
  });
};

const refresh = () => {
  gridRef.value &&
    gridRef.value.resize({ target: { innerWidth: window.innerWidth } } as unknown as UIEvent, () => {
      resetLabel();
    });
};

onMounted(() => {
  target.value = document.getElementById(props.formid);

  /**
   * @description 监听DOM变化，重新计算label高度
   */
  const observeDom = new MutationObserver((mutations, observe) => {
    nextTick(() => {
      resetLabel();
    });
  });
  observeDom.observe(target.value, { childList: true, subtree: true });

  let gridTaget: any = document.getElementById(props.formid + "-basicform-groups");
  /**
   * @description 监听DOM变化，重新计算label高度
   */
  const observeDomGird = new MutationObserver((mutations, observe) => {
    nextTick(() => {
      // console.log("gridTaget.offsetWidth :>> ", props.formid + "-basicform-groups", gridTaget.offsetWidth);
      refresh();
    });
  });
  observeDomGird.observe(gridTaget, { childList: true, subtree: true });
});
provide("gridTarget", target);

const showGroup = (list: any) => {
  return list.filter(
    (item: any) =>
      item.field !== "pid" &&
      item.basicinfo?.visible !== false &&
      (!item.basicinfo.hasOwnProperty("ishidden") || !item.basicinfo?.ishidden)
  );
};

const hideGroup = (list: any) => {
  return list.filter((item: any) => item.field !== "pid" && item.basicinfo.ishidden && item.basicinfo?.visible !== false);
};

/**
 * @description 字段: 拖拽排序
 */
const handleSortDragStart = (ev: any) => {
  console.log("handleSortDragStart start ev :>> ", ev);
  if (ev.item.children) {
    let _field = ev.item.children[0].getAttribute("data-field");
    console.log("_field :>> ", _field);
    let oDiv = document.querySelector(`div[data-field="${_field}"]`);
    drag.value && drag.value.toggleSelection([oDiv], true);
  }
};
/**
 * @description 字段: 拖拽排序
 */
const handleSortDrag = (ev: any) => {
  console.log("handleSortDrag ev :>> ", ev);
  let { to, from, target, newIndex, item } = ev;

  let targetInMatch = false;
  if (item.children) {
    let _field = item.children[0].getAttribute("data-field");
    console.log("_field :>> ", _field);
    targetInMatch = selectColumn.value.includes(_field);
  }
  console.log("targetInMatch :>> ", targetInMatch);

  if (to.id == target.id && targetInMatch) {
    console.log("handleSortDrag newIndex :>> ", newIndex);
    // 只处理目标组变化
    // 批量拖拽
    if (selectColumn.value.length > 1) {
      funcChangeGroup(selectColumn.value, to.id, newIndex);
      toClearSelect();

      nextTick(() => {
        initDragSelect();
      });
    }
  }
};

const settingFooterRef = ref();
/**
 * @description 分组: 拖拽排序
 */
const handleSortGroup = (event: any) => {
  console.log("handleSortGroup event :>> ", event);

  publicAttr.value.basicGroup = groupFlatColumns.value.map((item: any) => {
    return {
      label: item.label,
      span: item.span
    };
  });

  // settingFooterRef.value?.updateRoot();
};

// 修改模板别名
const labelInput = ref("");
const aliaseInputRef = ref();
const toEditAliase = (item: any) => {
  labelInput.value = item.label;
  console.log("toEditAliase", item);
  item.edit = true;
  // isEditAliase.value = !isEditAliase.value;
  nextTick(() => {
    console.log("aliaseInputRef.value :>> ", aliaseInputRef.value);
    aliaseInputRef.value?.focus();
    aliaseInputRef.value?.select();
  });
};
const toSaveBaceGroupLabel = (item: any, index: number) => {
  console.log("toEditAliase", item);
  let _label = htmlEncodeByRegExp(labelInput.value);

  let idx = groupFlatColumns.value.findIndex((i: any) => i.label === _label);
  if (idx == -1) {
    item.label = _label;

    item.list.forEach((itm: any) => {
      itm.basicinfo.group = item.label;
    });
  } else {
    console.log("idx, index :>> ", idx, index);
    idx != index && ElMessage.error(t("sys.api.operationFailed") + ":" + t("sys.errorLog.sameName"));
  }
  item.edit = false;
  console.log("groupFlatColumns.value :>> ", groupFlatColumns.value);

  nextTick(() => {
    initDragSelect();
  });
};

const visibleNewGroup = ref(false);
const newGroupName = ref("");
const newGroupNameRef = ref();
const newGroupSpan = ref(props.searchCol[breakPoint.value]);

const handleOpenAddGroupPopo = () => {
  visibleNewGroup.value = true;
  nextTick(() => {
    newGroupNameRef.value?.focus();
    newGroupNameRef.value?.select();
  });
};
/**
 * @description 新建属性分组
 */
const toAddGroup = () => {
  let _label = "";
  _label = htmlEncodeByRegExp(newGroupName.value);

  let idx = groupFlatColumns.value.findIndex((i: any) => i.label === _label);
  if (idx > -1) {
    ElMessage.error(t("sys.api.operationFailed") + ":" + t("sys.errorLog.sameName"));
    return;
  }

  let cols: any = [];

  groupFlatColumns.value = groupFlatColumns.value.map((item: any) => {
    cols = cols.concat(item.list.filter((col: any) => selectColumn.value.includes(col.field)));
    item.list = item.list.filter((col: any) => !selectColumn.value.includes(col.field));
    return item;
  });

  cols.sort((a: any, b: any) => {
    return selectColumn.value.indexOf(a.field) - selectColumn.value.indexOf(b.field);
  });

  let newGroup: GroupBasicProps = {
    label: _label,
    // span: props.searchCol[breakPoint.value],
    list: cols,
    collapsed: true,
    edit: false,
    span: newGroupSpan.value
  };

  groupFlatColumns.value.push(newGroup);

  drag.value.clearSelection();
  toDefaultValue();

  nextTick(() => {
    initDragSelect();
  });
};

/**
 * @description 删除属性分组
 */
const toDelGroup = (element: any) => {
  // let _index = groupFlatColumns.value.findIndex((item: any) => item.label == element.label);

  // let cols = cloneDeep(element.list);
  // cols.forEach((col: any) => {
  //   col.basicinfo.group = "";
  //   col.basicinfo.visible = false;
  // });

  // let hasConcat = false;
  groupFlatColumns.value.forEach((item: any) => {
    if (item.label == element.label) {
      // item.list = item.list.concat(cols);
      item.list.forEach((col: any) => {
        col.basicinfo.group = "";
        col.basicinfo.visible = false;
      });
      // hasConcat = true;
    }
  });
  // groupFlatColumns.value.splice(_index, 1);

  // if (!hasConcat) {
  //   groupFlatColumns.value.push({
  //     label: "",
  //     list: cols,
  //     collapsed: true,
  //     edit: false
  //     // span: props.searchCol[breakPoint.value]
  //   });
  // }
};

/**
 * @description 计算当前最小span
 */
const getSpan = (span: any, size: any) => {
  console.log("getSpan span, size :>> ", span, size);
  let _size = size ?? "xl";
  if (span) {
    return Math.min(span, props.searchCol[_size]);
  } else {
    return props.searchCol[_size];
  }
};

/**
 * @description 计算baseform数据源
 */
const getBaseFormCol = (item: any) => {
  let obj: any = {};
  // if (editable.value) {
  // console.log("getBaseFormCol item :>> ", item);
  if (item?.basicinfo) {
    obj = { ...item };
    if (item.basicinfo.el) {
      obj = { ...item, ...item.basicinfo };
      obj.render = item.basicinfo?.render;
    } else {
      item.basicinfo?.render && (obj.render = item.basicinfo?.render);
    }
  } else if (item?.render) {
    obj = { ...item };
  }
  // } else {
  // if (item?.basicinfo && item.basicinfo?.render) {
  //   obj = { ...item, render: item.basicinfo?.render };
  // } else if (item?.render) {
  //   obj = { ...item };
  // }
  // }
  return obj;
};

/**
 * @description 重置列排序等数据
 */
// const saveDfBtnLoading = ref(false);
/**
 * @description 设置系统默认布局
 */
const saveDefaultClick = () => {
  // saveDfBtnLoading.value = true;
  confirmBtnLoading.value = true;

  let diff = saveLayoutFunc();
  emit("saveDefault", groupFlatColumns.value, diff, (ifsuccess: boolean) => {
    confirmBtnLoading.value = false;
    ifsuccess &&
      ElNotification({
        title: t("sys.api.operationSuccess"),
        message: t("sys.layout.successToLayout"),
        type: "success"
      });
  });
};

/**
 * @description 搜索栏
 */
const searchField = ref("");
const matchSearchNum = ref(0);
const searchProps = ["field", "title", "table"];
const searchEvent = () => {
  matchSearchNum.value = 0;
  const filterVal = String(searchField.value).trim().toLowerCase();
  if (filterVal) {
    // const filterRE = new RegExp(filterVal, "gi");
    groupFlatColumns.value.map((items: any) => {
      if (curGroup.value && items.label != curGroup.value.label) {
        items.list.map((item: any) => {
          item.isMatch = false;
        });
      } else {
        items.list.map((item: any) => {
          if (searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1)) {
            matchSearchNum.value++;
            item.isMatch = true;
          } else {
            item.isMatch = false;
          }
        });
      }
    });
  } else {
    groupFlatColumns.value.map((items: any) => {
      items.list.map((item: any) => {
        item.isMatch = false;
      });
    });
  }
};
// 节流
const disshow = throttle((val: any) => {
  searchEvent();
}, 500);

const handleSelectMatch = () => {
  let addNodes: any = [];
  // let oriSel = cloneDeep(selectColumn.value)
  console.log("handleSelectMatch bf selectColumn.value :>> ", selectColumn.value);
  groupFlatColumns.value.map((items: any) => {
    items.list.map((item: any) => {
      let hasIdx = selectColumn.value.indexOf(item.field);
      if (hasIdx > -1) {
        let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
        addNodes.push(oDiv);
      } else if (item.isMatch && hasIdx == -1) {
        // hasIdx = selectColumn.value.indexOf(item.field);
        // // hasIdx == -1 && selectColumn.value.push(item.field);
        // if (hasIdx == -1) {
        // selectColumn.value.push(item.field);
        let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
        console.log("oDiv :>> ", oDiv);
        // drag.value.addSelection(oDiv, true);
        addNodes.push(oDiv);
        // }
        // console.log("selectColumn.value :>> ", selectColumn.value);
      }
    });
  });
  console.log("handleSelectMatch addNodes :>> ", addNodes);
  drag.value.addSelection(addNodes, true);
  console.log("selectColumn.value :>> ", selectColumn.value);
};

/**
 * @description 全选
 * @param element
 */
const handleSelectAll = (element: any) => {
  let { label } = element;
  let addNodes: any = [];
  console.log("handleSelectMatch bf selectColumn.value :>> ", selectColumn.value);
  let _group = groupFlatColumns.value.find(items => items.label == label);

  if (_group) {
    let ifAll = true;
    _group.list.map((item: any) => {
      let hasIdx = selectColumn.value.indexOf(item.field);
      if (hasIdx == -1) {
        ifAll = false;
      }
    });

    if (ifAll) {
      _group.list.map((item: any) => {
        let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
        addNodes.push(oDiv);
        if (activeColumn.value && activeColumn.value.field == item.field) {
          activeColumn.value = null;
        }
      });
      drag.value.removeSelection(addNodes, true);
    } else {
      _group.list.map((item: any) => {
        let hasIdx = selectColumn.value.indexOf(item.field);
        if (hasIdx == -1) {
          selectColumn.value.push(item.field);
          let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
          addNodes.push(oDiv);
        }
      });
      drag.value.addSelection(addNodes, true);
    }
    console.log("handleSelectMatch addNodes :>> ", addNodes);
    console.log("selectColumn.value :>> ", selectColumn.value);
  }
};

const isGroupAllSelect = (gourp: any) => {
  if (!gourp) return false;
  if (gourp.list && gourp.list.length) {
    return gourp.list.every((item: any) => selectColumn.value.includes(item.field));
  }
  return false;
};

/**
 * @description 补充元素属性
 * @param item column数据列
 */
const cpBasicinfoAttr = (item: any) => {
  let attr: any = {};
  if (item.basicinfo && item.basicinfo?.el == "input") {
    if (item.basicinfo?.props?.type == "textarea") {
      if (item.basicinfo.row <= 2) {
        attr.rows = item.basicinfo.row;
        return attr;
      }
      let rowHeight = FORM_LINE_HEIGHT[globalStore.assemblySize];
      let oDiv = document.querySelector(`div[data-field="${item.field}"]`);
      if (oDiv) {
        // 获取元素的父元素
        let oDivH = oDiv?.parentElement?.clientHeight ?? oDiv.clientHeight;
        // 根据父元素高度计算行数
        let newRows = Math.ceil(oDivH / rowHeight);
        attr.rows = newRows;
      }
    }
  }
  return attr;
};

const getVisibleLength = (data: any) => {
  return data.list.filter((item: any) => item.basicinfo.visible).length;
};

const handleKeyDown = (event: KeyboardEvent) => {
  if (event.key === "Enter") {
    let inputs = formRef.value?.$el.querySelectorAll("input, textarea");
    inputs = Array.from(inputs).filter((input: any) => !input.disabled);

    const currentIndex = inputs.indexOf(event.target);
    if (currentIndex < inputs.length - 1) {
      inputs[currentIndex + 1].focus();
    }
  }
};

defineExpose({
  element: formRef,
  refresh
});
</script>

<style lang="scss" scoped>
.setting-grid-item {
  position: relative;
  height: 100%;

  &:not(.is-hidden)::before {
    content: "";
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    border: 2px dashed $color-primary-000;
    border-radius: $br-sm;
    z-index: 10;
  }
  &.is-active::before,
  &:hover::before {
    content: "";
    position: absolute;
    top: -2px;
    left: -2px;
    right: -2px;
    bottom: -2px;
    // left: -10px;
    // right: -10px;
    border: 2px solid $color-primary-400;
    border-radius: $br-sm;
    z-index: 10;
    cursor: pointer;
  }
  &.is-active {
    position: relative;
    // background-color: $color-primary-200 !important;
  }
  &:not(.is-active):hover::before {
    border-style: dashed;
    border-color: $color-primary-500;
  }
  &.is-dragselect {
    background-color: $color-geek-blue-2 !important;
    :deep(.el-input) {
      .el-input__wrapper {
        background-color: $color-geek-blue-2 !important;
      }
    }
  }
  &.to-dragselect {
    background-color: $color-geek-blue-2 !important;
  }

  .hidden-btn {
    position: absolute;
    right: 8px;
    display: none;
  }

  &__field {
    position: absolute;
    right: $space-a4;
    color: $color-gray-6;
    display: none;
  }
  &:hover {
    .hidden-btn {
      position: absolute;
      right: 8px;
      display: block;
    }
    .setting-grid-item__field {
      display: block;
    }
  }
  &.is-hidden {
    background-color: $color-gray-5;
    border-radius: $br-sm;
    opacity: 0.4;
    :deep(.el-input) {
      .el-input__wrapper {
        background-color: $color-gray-5 !important;
      }
    }
  }
  &.is-hidden.is-dragselect {
    opacity: 0.7;
    :deep(.el-input) {
      .el-input__wrapper {
        background-color: $color-geek-blue-2 !important;
      }
    }
  }
  &.is-match {
    position: relative;
    &::after {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      // background-color: $color-primary-200;
      border-radius: $br-sm;
      overflow: hidden;
      opacity: 0.5;
      z-index: 1;
      background: linear-gradient(345deg, rgba(0, 0, 0, 0) 60%, rgba(255, 236, 61, 0.8) 100%);
    }
    .el-form-item__label {
      z-index: 10;
    }
  }
}

// .setting-main {
//   .setting-main_private,
//   .setting-main_public {
//     position: relative;
//   }
//   .setting-main_private::before,
//   .setting-main_public::before {
//     content: attr(data-title);
//     position: absolute;
//     top: -16px;
//     left: 0;
//     @include text-style-footnote-description;
//     color: $color-text-disable;
//   }
//   .setting-main_private::after,
//   .setting-main_public::after {
//     content: "";
//     position: absolute;
//     top: -4px;
//     bottom: -4px;
//     left: -8px;
//     right: -8px;
//     background-color: $color-gray-3;
//     border-radius: $br-md;
//     border: 2px solid $color-gray-1;
//     z-index: -1;
//     box-shadow: $shadow-1-down;
//   }
//   .setting-main_private {
//     height: 32px;
//     &::before {
//       color: $color-primary-400;
//     }
//     &::after {
//       background-color: $color-primary-100;
//     }
//     &.is-group,
//     &.is-match {
//       &::after {
//         background-color: $color-geek-blue-3;
//       }
//       &::before {
//         color: $color-geek-blue-5;
//       }

//       :deep(.el-form-item__content) {
//         .el-radio-button__inner:hover {
//           --el-color-primary: var(--lj-color-geek-blue-5);
//         }
//         .el-radio-button__original-radio:checked + .el-radio-button__inner {
//           --el-radio-button-checked-bg-color: var(--lj-color-geek-blue-4);
//           --el-radio-button-checked-border-color: var(--lj-color-geek-blue-4);
//         }
//       }
//     }
//   }
// }
.setting-part {
  // height: 240px;
  // background-color: $color-gray-4;
  // border-radius: $br-md;
  margin-top: $space-b2;
  // padding: $space-b2 $space-a2;

  .setting-main_public,
  .setting-main_private {
    display: inline-block;
    background-color: $color-gray-3;
    border-radius: $br-md;
    padding: $space-b2 $space-a2;
  }

  .setting-main_private {
    // color: $color-primary-400;
    background-color: $color-primary-100;

    &.is-group {
      background-color: $color-geek-blue-4;
    }
    &.is-match {
      background-color: $color-geek-blue-2;
    }

    &.is-group,
    &.is-match {
      :deep(.el-form-item__content) {
        .el-radio-button__inner:hover {
          --el-color-primary: var(--lj-color-geek-blue-6);
        }
        .el-radio-button__original-radio:checked + .el-radio-button__inner {
          --el-radio-button-checked-bg-color: var(--lj-color-geek-blue-5);
          --el-radio-button-checked-border-color: var(--lj-color-geek-blue-5);
        }
      }
    }
  }
}
.detail__info {
  .basicform-groups.setting {
    position: relative;
    border: 2px dashed $color-primary-100;
    border-radius: $br-md;
    padding: $space-a3;
    user-select: none;

    &::before {
      content: "";
      position: absolute;
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background-color: $color-primary-000;
      opacity: 0.2;
      z-index: 0;
    }

    .detail__info-group {
      position: relative;
      background-color: $color-gray-2;

      &.is-active::before {
        content: "";
        position: absolute;
        top: -2px;
        left: -4px;
        right: -2px;
        bottom: -2px;
        border: 2px solid $color-geek-blue-4;
        z-index: 0;
        border-radius: $br-md;
      }

      .group_handle {
        background-color: $color-gray-3;
      }
    }

    #settingSearchInput {
      position: absolute;
      top: 0;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);

      :deep(.el-input__wrapper) {
        background: $color-gray-1;
      }
    }
  }
  :deep(.el-form-item__label) {
    color: $color-text-primary-text;
    padding-right: $space-b1;
  }
  :deep(.el-form-item) {
    &.is-required {
      .el-form-item__label {
        color: var(--lj-color-dust-red-5) !important;
      }
    }
  }
  // &:not(.is-editable) {
  //   :deep(.el-form-item) {
  //     .el-form-item__label {
  //       color: $color-text-secondary-text;
  //     }
  //     .el-form-item__content {
  //       color: $color-text-title;

  //     }
  //     .el-input.is-disabled .el-input__inner {
  //       color: $color-text-title;
  //       -webkit-text-fill-color: $color-text-title;
  //     }
  //   }
  // }
  :deep(.el-form-item) {
    // align-items: center;
    &:not(.is-label-top) .el-form-item__label {
      display: block;
      justify-content: unset;
      align-items: unset;

      /* 过于长的label分两行展示样式 */
      white-space: pre-line;
      text-align-last: justify;
      text-align: justify;
      text-justify: distribute-all-lines;
    }
    .el-input.is-disabled .el-input__inner,
    .el-select__wrapper.is-disabled .el-select__selected-item {
      color: $color-text-title;
      -webkit-text-fill-color: $color-text-title;
    }

    .el-form-item__label {
      color: $color-text-secondary-text;
    }
    &.is-editable .el-form-item__label {
      color: $color-geek-blue-5;
    }
    .el-form-item__content {
      color: $color-text-title;

      .el-input-number {
        width: unset;
        .el-input__inner {
          text-align: right;
        }
        .el-input__wrapper {
          padding-right: 40px;
        }
      }
      .error-box {
        position: absolute;
        right: 24px;
        color: $color-dust-red-5;
        top: 0;
        bottom: 0;
        margin: auto;
        font-size: 16px;
      }
    }
    .el-input.is-disabled .el-input__inner {
      color: $color-text-title;
      -webkit-text-fill-color: $color-text-title;
    }
    // &.is-textright {
    //   text-align: right;
    // }

    &.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label-wrap > .el-form-item__label,
    &.is-required:not(.is-no-asterisk).asterisk-left > .el-form-item__label {
      position: relative;
      &::before {
        content: "*";
        position: absolute;
        left: -$space-b2;
        top: 50%;
        transform: translateY(-50%);
        font-size: $space-a3;
        height: $space-b2;
        line-height: $space-b3;
      }
    }
    &:hover {
      .el-form-item__label {
        color: $color-primary-700;
      }
    }
  }
  :deep(.el-form-item--label-top) {
    .el-form-item__label {
      margin-bottom: 0;
    }
  }
  // :deep(.el-form-item__content) {
  //   color: $color-text-secondary-text;
  //   // line-height: 22px !important;
  //   // align-items: stretch;
  //   // & > * {
  //   //   line-height: 32px !important;
  //   // }
  // }
  // .to-search {
  //   :deep(.el-form-item__label) {
  //     color: $color-primary-700;
  //   }
  // }

  :deep(.el-form-item) {
    margin-bottom: 0;

    // .el-select,
    // .el-autocomplete,
    // .el-date-editor.el-input,
    // .el-date-editor.el-input__wrapper {
    // display: flex;
    // width: 100%;
    // }
    .el-select .select-trigger {
      flex: 1;
    }
    .el-input__wrapper {
      padding: 0 8px;
    }
    &.is-error {
      .el-input__wrapper {
        background-color: $color-dust-red-1;
      }
    }
  }

  &-group {
    .group_handle .header-right {
      display: none;
    }
    &:hover {
      // background-color: $color-gray-2;
      // border-radius: $br-md;

      // :deep(.el-divider__text) {
      //   background-color: $color-gray-2;
      // }
      .group_handle {
        cursor: move;
        // background-color: $color-gray-3;

        .header-right {
          display: block;
          position: absolute;
          right: $space-b2;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
    :deep(.el-divider) {
      margin: $space-b2 0;
    }

    & .group-header {
      border-top-left-radius: $br-md;
      border-top-right-radius: $br-md;
      padding-bottom: $space-a1;
      margin-bottom: $space-b1;
      border-bottom: 1px solid $color-gray-3;
      & > .title {
        z-index: 1;
        // padding: $space-b1 $space-b1 $space-b2 $space-b1;
        // margin: 0 $space-b1 $space-a1 $space-b1;

        &.has-hidden {
          cursor: pointer;
        }

        .header-title {
          position: relative;
          &::before {
            content: "";
            position: absolute;
            top: 50%;
            bottom: -4px;
            left: -6px;
            right: -120%;
            border-top-left-radius: 12px;
            border-bottom-left-radius: 12px;
            color: $color-text-disable;
            background: linear-gradient(190deg, rgba(0, 0, 0, 0) 40%, rgba(255, 194, 102, 0.8) 100%);
            z-index: -1;
          }
        }
        // &.has-hidden:hover {
        // background-color: $color-gray-4;
        // }
      }
    }

    &-list {
      padding: 0 $space-b2 $space-b1 0;
    }

    // & + .detail__info-group {
    //   margin-top: $space-b2;
    // }

    // .lj-grid-layout {
    // padding: 0 $space-b2;
    // }
  }
  // .btn-group-clear {
  //   color: $color-geek-blue-5 !important;
  //   border-color: $color-geek-blue-3 !important;
  //   background-color: $color-geek-blue-2 !important;
  //   &:hover {
  //     color: $color-gray-1 !important;
  //     background-color: $color-geek-blue-6 !important;
  //   }
  // }
}
.btn-group {
  // border-color: $color-geek-blue-5 !important;
  // background-color: $color-geek-blue-5 !important;
  // &:hover {
  //   border-color: $color-geek-blue-6 !important;
  //   background-color: $color-geek-blue-6 !important;
  // }
  color: $color-geek-blue-5 !important;
  border-color: $color-geek-blue-3 !important;
  background-color: $color-geek-blue-1 !important;
  &:not(.is-disabled):hover {
    color: $color-gray-1 !important;
    border-color: $color-geek-blue-6 !important;
    background-color: $color-geek-blue-6 !important;
  }
  &.is-disabled {
    color: var(--lj-color-text-disable) !important;
  }
}
</style>
