<template>
  <LjDrawer
    ref="LjDrawerRef"
    :class="`${prefixCls}`"
    direction="rtl"
    size="80%"
    destroy-on-close
    append-to-body
    :show-close="false"
  >
    <template #header>
      <div class="flx-justify-between">
        <div class="">
          {{
            `${props.title ? props.title : $t("business.baseMsgSetting.title")}-${$t("sys.setting.displayColumn")}(${
              isVisibleCols.length
            }/${oriList.length})`
          }}
        </div>
        <div class="flx flx-center mr-4" id="settingSearchInput">
          <el-input
            v-model="searchField"
            :prefix-icon="Search"
            clearable
            style="width: 240px; height: 34px"
            :placeholder="$t('business.baseMsgSetting.searchPh')"
            @clear="searchEvent"
            @input="disshow(searchField)"
          >
            <template #suffix v-if="searchField.length">
              {{ matchSearchNum }}
            </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>
        <div class="flx-shrink">
          <!-- <el-button type="primary" :icon="Printer" @click="print" :loading="loadingPrinter">
            {{ $t("common.table.print") }}
          </el-button> -->
          <el-tooltip effect="dark" :content="$t('common.table.guide')" :show-after="200">
            <el-button class="default-btn mr-8" :icon="Guide" circle @click="checkIfNeedGuide(true, TourSteps)" />
          </el-tooltip>
          <el-dropdown :hide-on-click="false">
            <el-button :icon="MoreFilled" circle plain> </el-button>
            <template #dropdown>
              <el-dropdown-menu style="min-width: 250px" @mouseenter="visible = true" @mouseleave="visible = false">
                <template v-if="scrollY">
                  <el-dropdown-item
                    class="flx-justify-between"
                    @mouseover="scrollMoveoverTooltips"
                    :data-content="$t('common.table.virtualScrollTips')"
                  >
                    <!-- <el-checkbox v-model="scrollY.enabled" :label="$t('common.table.scrollYEnabled')" size="large" /> -->
                    <span class="mr-8 text-body-c text-secondary-text user-sel-none">
                      <!-- <el-icon><QuestionFilled /></el-icon> -->
                      {{ $t("common.table.scrollYEnabled") }}:
                    </span>
                    <el-switch v-model="scrollY.enabled" />
                  </el-dropdown-item>
                  <template v-if="scrollY.enabled">
                    <el-dropdown-item
                      class="flx-justify-between"
                      @mouseover="scrollMoveoverTooltips"
                      :data-content="$t('common.table.modeTips')"
                    >
                      <span class="mr-8 text-body-c text-secondary-text user-sel-none">滚动模式:</span>
                      <el-radio-group v-model="scrollY.mode" size="small">
                        <el-radio-button label="default" />
                        <el-radio-button label="wheel" />
                      </el-radio-group>
                    </el-dropdown-item>
                    <el-dropdown-item
                      class="flx-justify-between"
                      @mouseover="scrollMoveoverTooltips"
                      :data-content="$t('common.table.oSizeTips')"
                    >
                      <span class="mr-8 text-body-c text-secondary-text user-sel-none">
                        <!-- <el-icon><QuestionFilled /></el-icon> -->
                        偏移量:
                      </span>
                      <el-input-number
                        v-model="scrollY.oSize"
                        :min="0"
                        :step="10"
                        controls-position="right"
                        size="small"
                        class="user-sel-none"
                        style="width: 90px"
                      />
                    </el-dropdown-item>
                  </template>
                </template>
                <!-- <el-dropdown-item
                  class="flx-center"
                  divided
                  @click="resetClick"
                  @mouseover="scrollMoveoverTooltips"
                  :data-content="$t('common.table.resetTips')"
                >
                  {{ $t("common.resetText") }}
                </el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-tooltip
            placement="left"
            :visible="visible"
            :popper-options="{
              modifiers: [
                {
                  name: 'computeStyles',
                  options: {
                    adaptive: false,
                    enabled: false
                  }
                }
              ]
            }"
            :virtual-ref="buttonRef"
            virtual-triggering
            popper-class="singleton-tooltip"
          >
            <template #content>
              <span style="white-space: pre-wrap">{{ scrollTooltipsContent }}</span>
            </template>
          </el-tooltip>
          <el-divider direction="vertical" />
          <el-button type="danger" :icon="Close" text circle @click="cancelClick"></el-button>
        </div>
      </div>
    </template>
    <template #default="{ breakPoint }">
      <el-container :class="`${prefixCls}__body`" class="h-full">
        <el-main :class="`${prefixCls}__main`" class="h-full">
          <!-- <el-row :gutter="16" class="h-full">
            <el-col :span="18" class="h-full"> -->
          <div class="flx-2 pl-8 pr-8 affix-container h-full">
            <div class="flx-col h-full overflow-hidden">
              <!-- <LjHeader
                :class="`${prefixCls}__main-header flx-shrink`"
                :title="`${$t('sys.setting.displayColumn')}(${isVisibleCols.length}/${oriList.length})`"
              >
                <template #toolButton>
                  <div class="flx flx-center mr-4">
                    <el-input
                      v-model="searchField"
                      :prefix-icon="Search"
                      clearable
                      style="width: 240px"
                      @clear="searchEvent"
                      @input="disshow(searchField)"
                    >
                      <template #suffix v-if="searchField.length">
                        {{ matchSearchNum }}
                      </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"
                        @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>
                </template>
              </LjHeader> -->
              <el-row :gutter="16" class="flx-1 overflow-auto">
                <el-col>
                  <table class="lj-table w-full">
                    <thead class="thead-dark">
                      <tr>
                        <th style="width: 20px"></th>
                        <th style="width: 40%">{{ $t("common.table.col") }}</th>
                        <th style="width: 30%">{{ $t("common.table.field") }}</th>
                        <th>{{ $t("common.table.table") }}</th>
                        <th style="width: 85px !important">{{ $t("common.table.hideColumn") }}</th>
                      </tr>
                    </thead>

                    <draggable
                      :list="list"
                      item-key="field"
                      animation="300"
                      forceFallback="true"
                      tag="tbody"
                      handle=".handle"
                      chosen-class="table-td-chosen"
                      :disabled="ifSearchFilter && searchField.length"
                      @update="handleDragUpdate"
                    >
                      <template #item="{ element, index }">
                        <tr
                          @click="handleSelFormItem(element, index)"
                          :class="{
                            'main_table-tr': true,
                            'is-active': activeColumn.field == element.field,
                            'is-notvisible': !element.visible
                          }"
                        >
                          <td style="text-align: center" @click.stop>
                            <i
                              class="iconfont handle"
                              :class="ifSearchFilter && searchField.length ? 'is-disable iconmove-off' : 'iconmove'"
                            ></i>
                          </td>
                          <td>
                            <div class="flx-justify-between">
                              <span v-html="element?.title_html || element.title"></span>
                              <div class="col-more-tag">
                                <el-tag
                                  v-if="element.fixed"
                                  effect="plain"
                                  round
                                  size="small"
                                  disable-transitions
                                  :title="$t('sys.setting.fixed')"
                                >
                                  {{ $t(`sys.setting.fixed${element.fixed}`) }}
                                </el-tag>
                                <el-tag
                                  v-if="element.sortable && element.order"
                                  type="danger"
                                  effect="plain"
                                  round
                                  size="small"
                                  disable-transitions
                                  :title="$t('sys.setting.sortDefault')"
                                >
                                  {{ $t(`sys.setting.${element.order}`) }}
                                </el-tag>
                                <el-tag
                                  type="success"
                                  effect="plain"
                                  round
                                  size="small"
                                  disable-transitions
                                  :title="$t('sys.setting.align')"
                                >
                                  {{ $t(`sys.setting.${element.align}`) }}
                                </el-tag>
                                <el-tag
                                  type="info"
                                  effect="plain"
                                  round
                                  size="small"
                                  disable-transitions
                                  :title="$t('sys.setting.columnWidth')"
                                >
                                  {{ element.width }}px
                                </el-tag>
                              </div>
                            </div>
                          </td>
                          <td>
                            <div class="flx-justify-between">
                              <span v-html="element?.field_html || element.field"></span>
                              <el-tag
                                v-if="element.datatype"
                                size="small"
                                disable-transitions
                                :title="$t('common.table.dataType')"
                                >{{ $t(`common.table.${fnGetType(element)}`) }}</el-tag
                              >
                              <!-- <span v-if="element.format" class="text-disable">{{ element.format }}</span> -->
                            </div>
                          </td>
                          <td>{{ element.table }}</td>
                          <td style="width: 85px">
                            <div class="flx-justify-between">
                              <el-switch
                                class="hide-switch"
                                v-model="element.visible"
                                inline-prompt
                                :active-value="false"
                                :active-icon="Hide"
                                :inactive-value="true"
                                :inactive-icon="View"
                                @click.stop
                                @change="handleSwitchVisible(element)"
                              />
                              <el-button-group class="hover-btn" size="small">
                                <el-tooltip
                                  effect="dark"
                                  :content="$t('common.table.location')"
                                  placement="top"
                                  :show-after="200"
                                  v-if="element.visible"
                                >
                                  <el-button circle :icon="Location" @click.stop="toScrollCol(element)"></el-button>
                                </el-tooltip>
                              </el-button-group>
                            </div>
                          </td>
                        </tr>
                      </template>
                    </draggable>
                  </table>
                  <template v-if="!list.length">
                    <el-empty description="暂无匹配数据列" />
                  </template>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-main>
        <el-aside :class="`${prefixCls}__aside-menu card`" v-if="!['sm', 'md'].includes(breakPoint)">
          <ColAside :value="activeColumn" :enum-map="props.enumMap" />
        </el-aside>
        <LjDrawer ref="LjDrawerAsideRef" size="30%" v-else :with-header="false">
          <ColAside :value="activeColumn" :enum-map="props.enumMap" />
        </LjDrawer>
      </el-container>
    </template>
    <template #footer>
      <div class="flx-justify-between" style="flex: auto">
        <div class="flx-shrink flx-center">
          <el-button
            v-if="userInfo.usercode?.trim().toLocaleLowerCase() == 'super'"
            id="settingBtnSetDefault"
            class="enter-x"
            type="primary"
            plain
            :loading="saveDfBtnLoading"
            @click="saveDefaultClick"
          >
            <template #icon>
              <i class="iconfont iconsave-01"></i>
            </template>
            {{ $t("sys.layout.settings") }}
          </el-button>
          <el-divider direction="vertical" v-if="userInfo.usercode?.trim().toLocaleLowerCase() == 'super'" />
          <el-button id="settingBtnReset" class="enter-x" :icon="Refresh" :loading="resetBtnLoading" @click="resetClick">{{
            $t("common.resetText")
          }}</el-button>
          <!-- <el-button text bg @click="resetClick" :loading="resetBtnLoading">{{ $t("common.resetText") }}</el-button> -->
          <!-- <div class="flx-center">
            <el-divider direction="vertical" />
            <el-checkbox
              v-model="scrollY.enabled"
              :label="$t('common.table.scrollYEnabled')"
              size="large"
              @mouseover="scrollMoveoverTooltips"
              :data-content="$t('common.table.virtualScrollTips')"
            />
            <template v-if="scrollY.enabled">
              <div class="flx-center ml-16" @mouseover="scrollMoveoverTooltips" :data-content="$t('common.table.oSizeTips')">
                <span class="mr-8 text-body-c text-secondary-text">
                  <el-icon><QuestionFilled /></el-icon>
                  偏移量:
                </span>
                <el-input-number
                  v-model="scrollY.oSize"
                  :min="0"
                  :step="10"
                  controls-position="right"
                  size="small"
                  style="width: 100px"
                />
              </div>
              <div class="flx-center ml-16" @mouseover="scrollMoveoverTooltips" :data-content="$t('common.table.modeTips')">
                <span class="mr-8 text-body-c text-secondary-text">滚动模式:</span>
                <el-radio-group v-model="scrollY.mode" size="small">
                  <el-radio-button label="default" />
                  <el-radio-button label="wheel" />
                </el-radio-group>
              </div>
            </template>

            <el-tooltip
              placement="left"
              :visible="visible"
              :popper-options="{
                modifiers: [
                  {
                    name: 'computeStyles',
                    options: {
                      adaptive: false,
                      enabled: false
                    }
                  }
                ]
              }"
              :virtual-ref="buttonRef"
              virtual-triggering
              popper-class="singleton-tooltip"
            >
              <template #content>
                <span style="white-space: pre-wrap">{{ scrollTooltipsContent }}</span>
              </template>
            </el-tooltip>
          </div> -->
        </div>
        <div>
          <el-button type="primary" :loading="confirmBtnLoading" @click="confirmClick">{{ $t("common.saveText") }}</el-button>
          <el-button @click="cancelClick">{{ $t("common.cancelText") }}</el-button>
        </div>
      </div>
    </template>
  </LjDrawer>
</template>

<script setup lang="ts">
import { ref, reactive, computed, inject, onMounted, onUnmounted, onDeactivated, onActivated, nextTick, watch } from "vue";
// import Grid from "@/components/Grid/index.vue";
// import GridItem from "@/components/Grid/components/GridItem.vue";
import { BreakPoint } from "@/components/Grid/interface";
import { ColumnProps } from "../interface";
import draggable from "vuedraggable";
import { useDesign } from "@/hooks/useDesign";
import { useGlobalStore } from "@/stores/modules/global";
import { storeToRefs } from "pinia";
import LjHeader from "@/components/LjHeader/index.vue";
import CellGroup from "@/components/CellGroup/index.vue";
import ColAside from "./ColAside.vue";
import {
  Plus,
  Minus,
  QuestionFilled,
  Close,
  MoreFilled,
  Refresh,
  Location,
  Search,
  View,
  Hide,
  Guide
} from "@element-plus/icons-vue";
import { ElMessage, ElNotification, type TabsPaneContext } from "element-plus";
import { useI18n } from "vue-i18n";
import { cloneDeep, throttle, defaultsDeep } from "lodash-es";
import { useUserStore } from "@/stores/modules/user";
import LjDrawer from "@/components/LjDrawer/index.vue";
import { TourEnum } from "@/enums/tourEnum";
import { useTour } from "@/hooks/useTour";

const { t } = useI18n();
const { prefixCls } = useDesign("table-col-setting");
const globalStore = useGlobalStore();
const { userInfo } = useUserStore();
const { globalAlign, globalLabelWidth } = storeToRefs(globalStore);
/**
 * @description 滚动模式
 */
const scrollY = ref<scrollYProps>({});
const buttonRef = ref();
const LjDrawerRef = ref();
const LjDrawerAsideRef = ref();
const scrollTooltipsContent = ref();
const visible = ref(false);
/**
 * @description 当前列索引
 */
const currentIndex = ref(0);
const scrollMoveoverTooltips = (e: any) => {
  buttonRef.value = e.currentTarget;
  scrollTooltipsContent.value = e.currentTarget.getAttribute("data-content");
};

const emit = defineEmits(["confirm", "reset", "saveDefault", "toScrollCol"]);

interface ProTableProps {
  title?: string;
  data?: ColumnProps[]; // 数据列
  // /**
  //  * @description 数据列原型, 用于重置列排序等数据
  //  */
  // prototype?: ColumnProps[];
  searchParam?: { [key: string]: any }; // 搜索参数
  // searchCol: number | Record<BreakPoint, number>;
  enumMap?: Map<string, { [key: string]: any }[]>;
  scrollYDefault?: any;
  // updateColumns: Function;
  // search: (params: any) => void; // 搜索方法
  // reset: (params: any) => void; // 重置方法
}

interface BaseMseSettingColumns {
  prop: string;
  label: string;
  table: string;
  // search: SearchProps | undefined; // 搜索项配置
  span: number;
  lableWidth: number;
  // invisible: false,
}

interface scrollYProps {
  /**
   * @description 是否启用虚拟滚动
   */
  enabled?: boolean;
  /**
   * @description 偏移值
   */
  oSize?: number;
  /**
   * @description 滚动模式
   */
  mode?: "default" | "wheel";
  [key: string]: any;
}

// 默认值
const props = withDefaults(defineProps<ProTableProps>(), {
  data: () => [],
  // prototype: () => [],
  searchParam: () => ({}),
  scrollYProps: {}
});

// 选项值列表
// const attrList = reactive([
//   {
//     label: "列宽",
//     field: "width",
//     type: "el-input-number",
//     defineConfig: {
//       step: 1,
//       min: 50,
//       max: 900
//     }
//   },
//   {
//     label: "对齐方式",
//     field: "align",
//     type: "el-radio-group",
//     childType: "el-radio-button",
//     children: [
//       {
//         label: "居左",
//         value: "left"
//       },
//       {
//         label: "居左",
//         value: "left"
//       },
//       {
//         label: "居左",
//         value: "left"
//       }
//     ]
//   },
//   {
//     label: "格式",
//     field: "formatter",
//     type: "el-select",
//     childType: "el-option",
//     children: () => props.enumMap?.get(activeColumn.field)
//   },
//   {
//     label: "隐藏表头",
//     field: "visible",
//     type: "el-switch",
//     defineConfig: {
//       inlinePrompt: true,
//       activeText: "是",
//       inactiveText: "否"
//     }
//   }
// ]);

/**
 * @description 指引步骤
 */
const TourSteps = computed(() => {
  let arr = [
    {
      element: `.${prefixCls}__main .main_table-tr:nth-child(${currentIndex.value + 1}) td:nth-child(1)`,
      popover: {
        title: t("business.guide.tableSetting.step2.title"),
        description: t("business.guide.tableSetting.step2.description"),
        side: "bottom"
      }
    },
    {
      element: `.${prefixCls}__main .main_table-tr:nth-child(${currentIndex.value + 1})`,
      popover: {
        title: t("business.guide.tableSetting.step3.title"),
        description: t("business.guide.tableSetting.step3.description"),
        side: "bottom"
      }
    }
  ];
  if (userInfo.usercode?.trim().toLocaleLowerCase() == "super") {
    arr.push({
      element: "#settingBtnSetDefault",
      popover: {
        title: t("business.guide.tableSetting.step4.title"),
        description: t("business.guide.tableSetting.step4.description"),
        side: "top"
      }
    });
  }
  arr.push({
    element: "#settingBtnReset",
    popover: {
      title: t("business.guide.tableSetting.step5.title"),
      description: t("business.guide.tableSetting.step5.description"),
      side: "top"
    }
  });
  return arr;
});

// 新手指导
const { checkIfNeedGuide } = useTour(t, TourEnum.tableSetting, TourSteps.value);

const cancelClick = () => {
  searchField.value = "";
  LjDrawerRef.value.hide();
};
const confirmBtnLoading = ref(false);

/**
 * @description 整理保存数据
 */
const saveLayoutFunc = () => {
  let arr = cloneDeep(oriList.value);

  let _scroll: any = cloneDeep(scrollY.value);
  if (props.scrollYDefault) {
    let nodiff = true;
    for (const key in props.scrollYDefault) {
      if (_scroll && props.scrollYDefault[key] != _scroll[key]) {
        nodiff = false;
        break;
      }
    }
    nodiff && (_scroll = {});
  }
  return {
    layout: arr,
    scroll: _scroll
  };
};
/**
 * @description 点击保存
 */
const confirmClick = () => {
  confirmBtnLoading.value = true;
  setTimeout(() => {
    let { layout, scroll } = saveLayoutFunc();

    console.log("colsetting confirmClick { scrollY: scroll } :>> ", { scrollY: scroll });

    emit("confirm", layout, { scrollY: scroll }, true, () => {
      confirmBtnLoading.value = false;
      cancelClick();
    });
  }, 1);
};

// const handleClick = (tab: TabsPaneContext, event: Event) => {
//   console.log(tab, event);
// };

/**
 * @description 显示组件
 */
const openColSetting = (param?: scrollYProps, column?: any) => {
  LjDrawerRef.value.show();
  scrollY.value = param ?? {};

  list.value = cloneDeep(props.data);
  oriList.value = cloneDeep(props.data);

  nextTick(() => {
    let _index = -1;
    if (column) {
      _index = list.value.findIndex(item => item.field === column.field);
    } else {
      // 默认点击第一行
      _index = 0;
    }
    currentIndex.value = _index;
    handleSelFormItem(list.value[_index], _index);

    setTimeout(() => {
      const el = document.querySelector(`.${prefixCls}__main .main_table-tr:nth-child(${_index + 1})`);
      if (el) {
        el.scrollIntoView();
      }

      setTimeout(() => {
        checkIfNeedGuide(false, TourSteps.value);
      }, 300);
    }, 200);
  });
};

let activeColumn = ref<any>({});
/**
 * @description 更新当前列的配置信息至缓存数组
 */
watch(
  () => activeColumn.value,
  newVal => {
    console.log("activeColumn.value newVal :>> ", newVal);

    let _idx = oriList.value.findIndex(item => item.field === newVal.field);
    if (_idx > -1) {
      oriList.value[_idx] = newVal;
    }
  },
  {
    deep: true
  }
);
// let activeBaseColMsg = ref<any>({});
const rightAsignActive = ref("style");
const handleSelFormItem = (item: any, index: number) => {
  let breakPoint = LjDrawerRef.value.breakPoint;

  if (["sm", "md"].includes(breakPoint)) {
    LjDrawerAsideRef.value && LjDrawerAsideRef.value.show();
  }
  activeColumn.value = item;
  currentIndex.value = index;
  rightAsignActive.value = "style";
  console.log("item :>> ", item);
  // activeBaseColMsg.value = getBaseCol(item) ?? {};
};

// 全局设置
let _globalAlign: any = globalAlign;
const handeChange = (arg: any, name: string) => {
  console.log("name :>> ", name);
  console.log("arg :>> ", arg);
};

// // 全局设置
// let _globalLabelWidth: any = globalLabelWidth;

// 样式
// inject("updateSettingColumn", )
// const handeChangeStyle: any = inject("updateSettingColumn");

// 判断数据类型
const fnGetType = (item: ColumnProps) => {
  return item?.datatype ?? (item?.field && item.field?.indexOf("date") > -1 ? "date" : "string");
};

/**
 * @description 重置列排序等数据
 */
const resetBtnLoading = ref(false);
/**
 * @description 重置布局，获取系统默认布局
 */
const resetClick = () => {
  resetBtnLoading.value = true;
  // emit("reset", (columns: any, scrollYDefault?: any) => {
  //   if (columns.length) {
  //     console.log("resetClick columns :>> ", columns);
  //     console.log("resetClick scrollYDefault :>> ", scrollYDefault);

  //     list.value = cloneDeep(columns);
  //     oriList.value = cloneDeep(columns);
  //     scrollY.value = scrollYDefault;
  //     ElMessage.success(t("sys.api.operationSuccess"));
  //   }

  //   resetBtnLoading.value = false;
  // });
  emit("reset", (data: any) => {
    if (data?.columns.length) {
      list.value = cloneDeep(data.columns);
      oriList.value = cloneDeep(data.columns);
      scrollY.value = defaultsDeep(data.tableprop.scrollY, props.scrollYDefault);
      ElMessage.success(t("sys.api.operationSuccess"));
    }

    resetBtnLoading.value = false;
  });
};

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

  let { layout, scroll } = saveLayoutFunc();
  emit("saveDefault", layout, { scrollY: scroll }, () => {
    saveDfBtnLoading.value = false;
    ElNotification({
      title: t("sys.api.operationSuccess"),
      message: t("sys.layout.successToLayout"),
      type: "success"
    });
  });
};

const searchField = ref("");
/**
 * @description 是否过滤筛选结果
 */
const ifSearchFilter = ref(false);
const matchSearchNum = ref();
const toScrollCol = (item: any) => {
  console.log("toScrollCol item :>> ", item);
  cancelClick();
  nextTick(() => {
    emit("toScrollCol", item);
  });
};

/**
 * @description 当前编辑数据源（包括搜索）
 */
const list = ref<ColumnProps[]>([]);
/**
 * @description 暂存数据源
 */
const oriList = ref<ColumnProps[]>([]);
const searchEvent = () => {
  matchSearchNum.value = 0;
  const filterVal = String(searchField.value).trim().toLowerCase();
  if (filterVal) {
    const filterRE = new RegExp(filterVal, "gi");
    const searchProps = ["field", "title", "table"];
    if (ifSearchFilter.value) {
      const rest = oriList.value.filter((item: any) =>
        searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1)
      );
      matchSearchNum.value = rest.length;
      list.value = rest.map(row => {
        const item: any = Object.assign({}, row);
        searchProps.forEach(key => {
          item[key + "_html"] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
        });
        return item;
      });
    } else {
      list.value = oriList.value.map(row => {
        const item: any = Object.assign({}, row);
        if (searchProps.some(key => String(item[key]).toLowerCase().indexOf(filterVal) > -1)) {
          matchSearchNum.value++;
          searchProps.forEach(key => {
            item[key + "_html"] = String(item[key]).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`);
          });
        }
        return item;
      });
    }
  } else {
    // table 排列
    list.value = cloneDeep(oriList.value);
  }
};
// 节流
const disshow = throttle((val: any) => {
  searchEvent();
}, 500);

const handleDragUpdate = (data: any) => {
  // 每次排序都更新暂存数组
  oriList.value = cloneDeep(list.value);
};

/**
 * @description 按钮: 控制显隐
 * @param item
 */
const handleSwitchVisible = (item: any) => {
  console.log("handleSwitchVisible item :>> ", item);
  let _idx = oriList.value.findIndex(itm => itm.field === item.field);
  oriList.value[_idx].visible = item.visible;
};

const isVisibleCols = computed(() => {
  return oriList.value.filter(item => item.visible);
});

defineExpose({
  openColSetting
});
</script>

<style lang="scss" scoped>
$prefix-cls: "#{$namespace}-table-col-setting";

.#{$prefix-cls} {
  // :deep(.el-dialog__body) {
  //   background-color: var(--el-bg-color-page) !important;
  // }
  // &__body {
  //   height: 50vh;
  // }
  &__menu {
    background-color: unset !important;
    padding: $space-a2 $space-b2;
    width: 256px !important;
  }
  &__main {
    padding: 0;
    overflow: hidden;
    .card {
      padding: $space-a2 $space-b2;
    }
    .#{$prefix-cls}__grid-item {
      cursor: pointer;
      // .el-form-item {
      position: relative;
      &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        // left: -10px;
        // right: -10px;
        border: 2px dashed $color-primary-100;
        border-radius: $br-sm;
      }
      // }
      &.is-active::before,
      &:hover::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        // left: -10px;
        // right: -10px;
        border: 2px solid $color-primary-400;
        border-radius: $br-sm;
      }
      &.is-active {
        position: relative;
        // background-color: $color-primary-200 !important;
      }
      &:not(.is-active):hover::before {
        border-style: dashed;
        border-color: $color-primary-500;
      }
      :deep(.el-scrollbar__view) {
        overflow-x: hidden;
      }
      .right-btn {
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(50%, -50%);
        transition: all 0.2s ease-in-out;
      }
      &:not(.more) .right-btn {
        opacity: 0;
      }
      &:hover {
        .right-btn {
          opacity: 1;
        }
      }
    }

    :deep(.el-scrollbar__view) {
      display: flex;
      flex-direction: column;
      height: 100%;
    }
    .drag-list {
      min-height: 80px;
      padding: 0 16px;
    }
    .col-more-tag {
      .el-tag {
        // margin-top: 2px;
        & + .el-tag {
          margin-left: 4px;
        }
      }
    }
    &-header {
      background-color: $color-gray-1;
    }
  }
  &__aside-menu {
    background-color: $color-gray-2;
    overflow: hidden;
    width: 360px;

    :deep(.el-tabs__content) {
      // height: 100%;
      flex: 1;
    }
    &.absolute {
      position: absolute;
      right: 0;
    }
  }
}
</style>
