<template>
  <div class="card table-search vxetable-search" v-if="columns.length" id="searchForm" ref="searchFormRef">
    <el-form
      ref="formRef"
      :model="searchParam"
      :label-position="publicAttr.labelPosition"
      :label-width="publicAttr.labelWidth"
      @submit.prevent="search"
    >
      <div class="flx">
        <!-- <div class="my-search-project__dropdown"> -->
        <div class="flx-center" :class="isOperationCls" v-if="collapsed">
          <!-- <el-tooltip effect="dark" :content="$t('business.searchProject.title')" placement="top" :show-after="8"> -->
          <el-dropdown placement="bottom-start" id="searchForm_searchProject">
            <el-button plain circle size="small" text bg @click="handleSelProject(0)">
              <template #icon>
                <i class="iconfont" :class="oriProject.length ? 'iconstar-01-fill' : 'iconstar-01'"></i>
              </template>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) in oriProject" :key="index" @click="handleSelProject(index)">
                  {{ item.name }}
                  <i class="ml-4 iconfont iconstar-01-fill" style="font-size: 12px" v-if="index == 0"></i>
                </el-dropdown-item>
                <el-dropdown-item :divided="!!oriProject.length" @click="handelAddSearchProject">
                  {{ $t("business.searchProject.new") }}
                </el-dropdown-item>
                <el-dropdown-item divided @click="gotoSetting">
                  {{ $t("common.table.searchSetting") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <!-- </el-tooltip> -->
          <el-divider direction="vertical" />
        </div>
        <!-- </div> -->
        <Grid
          id="searchForm_grid"
          ref="gridRef"
          class="flx-1"
          :collapsed="collapsed"
          :gap="isGap"
          :cols="searchCol"
          :setting="settingStatus"
          target="searchForm_grid"
        >
          <template #default="scope">
            <draggable
              v-if="settingStatus"
              :list="flatColumns"
              :style="scope?.style"
              item-key="field"
              animation="300"
              forceFallback="true"
            >
              <template #item="{ element, index }">
                <GridItem :key="index" v-bind="getResponsive(element)" :index="index" @click="handleSelFormItem(element)">
                  <el-form-item
                    :label="searchBtnSizeExtent.includes(breakPoint) ? '' : `${titleFilter(element)}`"
                    class="setting-grid-item"
                    :class="{ 'is-active': activeColumn && activeColumn.field == element.field }"
                  >
                    <SearchFormItem :column="element" :search-param="searchParam" :size-extent="searchBtnSizeExtent" />
                  </el-form-item>
                </GridItem>
              </template>
            </draggable>
            <template v-else>
              <GridItem v-for="(item, index) in columns" :key="item.field" v-bind="getResponsive(item)" :index="index">
                <el-form-item
                  :label="searchBtnSizeExtent.includes(breakPoint) ? '' : `${titleFilter(item)}`"
                  :class="{'to-search': ![undefined, ''].includes(searchParam[item.search?.key ?? handleProp(item.field!)])}"
                >
                  <SearchFormItem :column="item" :search-param="searchParam" :size-extent="searchBtnSizeExtent" />
                </el-form-item>
              </GridItem>
            </template>

            <GridItem
              suffix
              :span="settingStatus || !collapsed ? scope.gridCols : 1"
              :class="
                settingStatus || !collapsed ? `flx-start-end ${globalStore.assemblySize == 'small' ? 'mb-8' : 'mb-16'}` : 'flx'
              "
            >
              <template v-if="!settingStatus">
                <div class="flx-1" :class="!collapsed ? ' flx-justify-between flx ' : ''">
                  <div class="my-search-project flx-start flx-1" v-if="!collapsed" id="searchForm_searchProject_widget">
                    <div class="flx-shrink flx-center">
                      <span class="text-body-r flx-center">
                        {{ $t("business.searchProject.title") }}
                        <!-- <i class="ml-4 iconfont iconhelp-circle text-secondary-text" @click="goto"></i> -->
                        <el-icon style="cursor: pointer" @click="checkIfNeedGuide(true)"><Guide /></el-icon>
                      </span>

                      <div class="edit-box ml-12">
                        <template v-if="!editSearchProject">
                          <el-button-group>
                            <el-popover :visible="addVisible" placement="bottom" :width="240" @hide="addVisible = false">
                              <el-form @submit.prevent="gotoAddSearchProject">
                                <div class="text-h5-m mb-8">
                                  {{ $t("business.searchProject.confirm") }}
                                  <!-- <el-tooltip
                                  effect="dark"
                                  placement="top"
                                  :content="$t('business.searchProject.tips')"
                                  :show-after="8"
                                >
                                  <i class="ml-4 iconfont iconhelp-circle text-secondary-text"></i>
                                </el-tooltip> -->
                                </div>
                                <el-input
                                  ref="ProjectNameRef"
                                  v-model.trim="newProjectName"
                                  class="mb-12"
                                  :placeholder="$t('business.searchProject.placeholder')"
                                />
                                <div style="text-align: right; margin: 0">
                                  <el-button :size="globalStore.assemblySize" text @click="addVisible = false">{{
                                    $t("common.cancelText")
                                  }}</el-button>
                                  <el-button :size="globalStore.assemblySize" type="primary" native-type="submit">
                                    {{ $t("common.okText") }}
                                  </el-button>
                                </div>
                              </el-form>
                              <template #reference>
                                <el-button
                                  id="searchForm_searchProject_add"
                                  class="flx-1"
                                  :size="globalStore.assemblySize"
                                  :icon="Plus"
                                  circle
                                  @click="handelAddSearchProject"
                                >
                                </el-button>
                              </template>
                            </el-popover>

                            <el-button
                              v-if="oriProject.length"
                              id="searchForm_searchProject_setting"
                              :size="globalStore.assemblySize"
                              class="flx-1"
                              :icon="Setting"
                              circle
                              @click="editSearchProject = true"
                            >
                            </el-button>
                          </el-button-group>
                        </template>
                        <template v-else>
                          <el-button
                            class="enter-x flx-1"
                            :size="globalStore.assemblySize"
                            type="success"
                            round
                            @click="handelSaveSearchProject"
                          >
                            {{ $t("common.saveText") }}
                          </el-button>
                          <el-button
                            class="enter-x flx-1"
                            :size="globalStore.assemblySize"
                            round
                            @click="cancelEditSearchProject"
                          >
                            {{ $t("common.cancelText") }}
                          </el-button>
                        </template>
                      </div>
                      <el-divider direction="vertical" />
                    </div>
                    <draggable
                      class="project-list flx-1 flx overflow-auto mr-12"
                      style="width: 200px"
                      v-if="oriProject.length"
                      id="searchForm_searchProject_list"
                      :list="oriProject"
                      item-key="name"
                      animation="300"
                      forceFallback="true"
                      :disabled="!editSearchProject"
                    >
                      <template #item="{ element, index }">
                        <el-tag
                          :key="element.name"
                          :closable="editSearchProject"
                          :type="currentIndex == index ? '' : 'info'"
                          disable-transitions
                          :size="globalStore.assemblySize == 'small' ? 'default' : 'large'"
                          @click="handleSelProject(index)"
                          @close="handleDelProject(index)"
                        >
                          <div class="flx-center">
                            <i class="iconfont iconstar-01-fill mr-3" v-if="index == 0"></i>
                            {{ element.name }}
                            <span class="edit-btn" ref="ProjectRef" v-if="currentIndex == index" @click="editVisible = true">
                              <i class="iconfont iconedit-02"></i>
                            </span>
                          </div>
                        </el-tag>
                      </template>
                    </draggable>
                  </div>
                  <div class="operation flx-justify-between flx-shrink" :class="isOperationCls">
                    <el-button
                      v-if="showCollapse || !collapsed"
                      type="primary"
                      link
                      class="search-isOpen"
                      @click="collapsed = !collapsed"
                    >
                      {{ collapsed ? $t("common.table.expand") : $t("common.table.putAway") }}
                      <el-icon class="el-icon--right">
                        <component :is="collapsed ? ArrowDown : ArrowUp"></component>
                      </el-icon>
                    </el-button>
                    <div class="flx-end flx-1 ml-12">
                      <template v-if="searchBtnSizeExtent.includes(breakPoint)">
                        <!-- <el-dropdown
                          split-button
                          type="primary"
                          @click="search"
                          class="search-btn-dropdown"
                          placement="bottom-end"
                        >
                          {{ $t("common.searchText") }}
                          <template #dropdown>
                            <el-dropdown-menu>
                              <el-dropdown-item @click="reset">{{ $t("common.resetText") }}</el-dropdown-item>
                              <el-dropdown-item divided @click="gotoSetting">{{ $t("common.setText") }}</el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown> -->
                        <el-button
                          class="-enter-x"
                          circle
                          type="primary"
                          :icon="Search"
                          native-type="submit"
                          :title="$t('common.searchText')"
                        ></el-button>
                        <el-button
                          class="-enter-x"
                          circle
                          :icon="RefreshLeft"
                          @click="reset"
                          :title="$t('common.resetText')"
                        ></el-button>
                      </template>
                      <template v-else>
                        <el-button class="-enter-x flx-1" round type="primary" native-type="submit">{{
                          $t("common.searchText")
                        }}</el-button>
                        <el-button class="-enter-x flx-1" round @click="reset">
                          {{ $t("common.resetText") }}
                        </el-button>
                      </template>
                      <template v-if="!collapsed">
                        <el-divider direction="vertical" />
                        <el-button circle :icon="Operation" @click="gotoSetting"></el-button>
                      </template>
                    </div>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="operation flx-start flx-1">
                  <div class="flx-shrink flx-start mr-32 h-full">
                    <div class="setting-main flx-end w-full h-full">
                      <div class="setting-main_public flx-shrink flcx-enter -enter-y" :data-title="$t('sys.setting.publicAttr')">
                        <el-form :model="publicAttr" class="flx-center">
                          <el-form-item prop="labelWidth" class="mb-0 mr-16" 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.columnWidth") }}:</span
                              >
                              <el-input
                                class="w-full"
                                v-model="publicAttr.labelWidth"
                                placeholder="auto"
                                input-style="width:80px"
                              />
                            </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-24 -enter-y"
                        :data-title="$t('sys.setting.privateAttr') + ':' + titleFilter(activeColumn)"
                      >
                        <el-form :model="publicAttr" class="flx-center">
                          <el-form-item prop="labelWidth" class="mb-0 mr-16">
                            <div class="flx-center">
                              <span class="text-body-c text-secondary-text mr-8 white-nowrap-word"
                                >{{ $t("sys.setting.columnNum") }}:</span
                              >
                              <el-radio-group v-model="activeColumn.search.span" id="search.span">
                                <el-radio-button v-for="ritem in searchCol[breakPoint]" :key="ritem" :label="ritem">{{
                                  ritem
                                }}</el-radio-button>
                              </el-radio-group>
                            </div>
                          </el-form-item>
                        </el-form>
                      </div>
                    </div>
                  </div>
                  <div class="flx-1 flx-end">
                    <el-button class="enter-x" type="primary" :icon="Check" round @click="settingConfirm(formRef)">{{
                      $t("common.saveText")
                    }}</el-button>
                    <el-button class="enter-x" :icon="Close" round @click="cancelSetting">{{
                      $t("common.cancelText")
                    }}</el-button>
                  </div>
                </div>
              </template>
            </GridItem>
          </template>
        </Grid>
      </div>
    </el-form>

    <el-popover
      ref="editPopoverRef"
      :visible="editVisible"
      :virtual-ref="ProjectRef"
      trigger="click"
      virtual-triggering
      placement="bottom"
      :width="240"
    >
      <div class="text-h5-m mb-8">
        {{ $t("business.searchProject.eidtName") }}
      </div>
      <el-input
        ref="ProjectEditNameRef"
        v-model.trim="editProjectName"
        class="mb-12"
        :placeholder="$t('business.searchProject.placeholder')"
      />
      <div style="text-align: right; margin: 0">
        <el-button :size="globalStore.assemblySize" text @click="handleCancelEdit">{{ $t("common.cancelText") }}</el-button>
        <el-button :size="globalStore.assemblySize" type="primary" @click="handleOkEdit"> {{ $t("common.okText") }} </el-button>
      </div>
    </el-popover>
  </div>
</template>
<script setup lang="ts" name="VxwTableSearchForm">
import { computed, ref, inject, watch, reactive, nextTick } from "vue";
import { ColumnProps, SearchProps, searchProjectItem } from "../interface";
import { BreakPoint } from "@/components/Grid/interface";
import {
  Delete,
  Search,
  ArrowDown,
  ArrowUp,
  Operation,
  Check,
  Close,
  RefreshLeft,
  StarFilled,
  Plus,
  Setting,
  Guide
} from "@element-plus/icons-vue";
import SearchFormItem from "./SearchFormItem.vue";
import Grid from "@/components/Grid/index.vue";
import GridItem from "@/components/Grid/components/GridItem.vue";
import draggable from "vuedraggable";
import { cloneDeep, omit } from "lodash-es";
import { handleProp } from "@/utils";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { useI18n } from "vue-i18n";
import { useGlobalStore } from "@/stores/modules/global";
import tableJson from "@/languages/modules/zh-cn/table.json";
import { isArray } from "@/utils/is";
import { onClickOutside } from "@vueuse/core";
import { TourEnum } from "@/enums/tourEnum";
import { useTour } from "@/hooks/useTour";

interface SearchFormProps {
  columns?: ColumnProps[]; // 搜索配置列
  searchParam?: { [key: string]: any }; // 搜索参数
  searchCol: number | Record<BreakPoint, number> | any;
  search: (params?: any) => void; // 搜索方法
  reset: (params: any) => void; // 重置方法
  // /**
  //  * @argument string[] 布局读取/保存时，赋值的属性
  //  */
  // layoutAttr?: string[];
  /**
   * @argument Object 布局默认设置，保存时移除，的属性
   */
  layoutAttrDefine?: any;
  /**
   * @argument any form表单属性
   */
  formProps: any;
  /**
   * @description 搜索方案列表
   */
  project?: searchProjectItem[];
  /**
   * @description 搜索栏按钮需要缩小尺寸的屏幕尺寸，eg: ["xs", "sm"]
   */
  searchBtnSizeExtent?: string[];
}

const { t } = useI18n();
const globalStore = useGlobalStore();
const emit = defineEmits(["confirm", "saveProject", "updataParams"]);
// 默认值
const props = withDefaults(defineProps<SearchFormProps>(), {
  columns: () => [],
  searchParam: () => ({}),
  // layoutAttr: () => [],
  layoutAttrDefine: () => ({}),
  project: () => [],
  searchBtnSizeExtent: () => []
});

/**
 * @description 指引步骤
 */
const TourSteps = [
  {
    element: "#searchForm_searchProject_widget",
    popover: {
      title: t("business.guide.tableSearch.step1.title"),
      description: t("business.guide.tableSearch.step1.description"),
      side: "bottom"
    }
  },
  {
    element: "#searchForm_grid",
    popover: {
      title: t("business.guide.tableSearch.step2.title"),
      description: t("business.guide.tableSearch.step2.description"),
      side: "bottom"
    }
  },
  {
    element: "#searchForm_searchProject_add",
    popover: {
      title: t("business.guide.tableSearch.step3.title"),
      description: t("business.guide.tableSearch.step3.description"),
      side: "bottom"
    }
  },
  {
    element: "#searchForm_searchProject_setting",
    popover: {
      title: t("business.guide.tableSearch.step4.title"),
      description: t("business.guide.tableSearch.step4.description"),
      side: "bottom"
    }
  },
  {
    element: "#searchForm_searchProject_list",
    popover: {
      title: t("business.guide.tableSearch.step5.title"),
      description: t("business.guide.tableSearch.step5.description")
    }
  }
];
// 新手指导
const { checkIfNeedGuide } = useTour(t, TourEnum.table, TourSteps);

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

const isGap = computed(() => {
  let _rsl: [number, number] = [12, 0];
  switch (globalStore.assemblySize) {
    case "small":
      _rsl = [8, 0];
      break;
    default:
      break;
  }
  return _rsl;
});

const isOperationCls = computed(() => {
  return {
    "flx-justify-between": !settingStatus.value && collapsed.value,
    // "flx-start flx-1": !settingStatus.value && !collapsed.value,
    "mb-8": globalStore.assemblySize === "small" && collapsed.value,
    "mb-12": globalStore.assemblySize != "small" && collapsed.value
  };
});

const formRef = ref<FormInstance>();

// 是否默认折叠搜索项
const collapsed = ref(true);
// const collapsed = ref(false);

// 是否正在编辑
const settingStatus = ref(false);

// 获取响应式断点
const gridRef = ref();
const breakPoint = computed<BreakPoint>(() => gridRef.value?.breakPoint);

// 判断是否显示 展开/合并 按钮
const showCollapse = computed(() => {
  let show = false;
  props.columns.reduce((prev, current) => {
    prev +=
      (current.search![breakPoint.value]?.span ?? current.search?.span ?? 1) +
      (current.search![breakPoint.value]?.offset ?? current.search?.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;
});

// 记录当前编辑的column
let activeColumn = ref<any>(null);
/**
 * 编辑状态，点击某个column
 * @param item 搜索项item
 */
const handleSelFormItem = (item: any) => {
  activeColumn.value = item;
  console.log("handleSelFormItem activeColumn :>> ", activeColumn.value);
  // activeBaseColMsg.value = getBaseCol(item) ?? {};
};

// 初始化 columns
const flatColumns = ref<ColumnProps[]>();
// const flatColumnsFunc = (columns: ColumnProps[], flatArr: ColumnProps[] = []) => {
//   // columns.forEach(async (col: any) => {
//   //   // 给每一项 column 添加默认属性
//   //   col.search.labelPosition = col.search.labelPosition ?? props.layoutAttrDefine.labelPosition; // "top"
//   //   col.search.labelWidth = col.search.labelWidth ?? props.layoutAttrDefine.labelWidth; // 120
//   //   col.search.span = col.search.span ?? props.layoutAttrDefine.span; // 1

//   //   flatArr.push(col);
//   //   // col.isFilterEnum = col.isFilterEnum ?? true;
//   // });

//   // 取第一个column作为公共参数
//   publicAttr.value = {
//     labelPosition: flatArr[0].search?.labelPosition,
//     labelWidth: flatArr[0].search?.labelWidth
//   };
//   // // 读取个性设置后，排序，
//   // if (dwFieldMap.size) {
//   //   flatArr.sort((a, b) => {
//   //     return a.order! - b.order!;
//   //   });
//   // }
//   return flatArr;
// };
let publicAttr = ref<any>({});
const resetPublicAttr = () => {
  publicAttr.value.labelPosition = props.formProps.labelPosition ?? props.layoutAttrDefine.labelPosition;
  publicAttr.value.labelWidth = props.formProps.labelWidth ?? props.layoutAttrDefine.labelWidth;
};

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

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

/**
 * @description 设置窗口，保存事件
 */
const settingConfirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    console.log("flatColumns.value :>> ", flatColumns.value);
    if (!flatColumns.value) return;

    let _params: any = cloneDeep(publicAttr.value);
    if (props.layoutAttrDefine) {
      let nodiff = true;
      for (const key in props.layoutAttrDefine) {
        if (props.layoutAttrDefine[key] != _params[key]) {
          nodiff = false;
          break;
        }
      }
      nodiff && (_params = {});
    }

    flatColumns.value.map((item: any, index: number) => {
      item.search.order = index;
    });

    console.log("settingConfirm bff_params :>> ", flatColumns.value, _params);
    emit("confirm", flatColumns.value, _params, () => {
      settingStatus.value = false;
    });
  });
};

const cancelSetting = () => {
  settingStatus.value = !settingStatus.value;

  resetPublicAttr();
};

const titleFilter = (item: any) => {
  let _title = item.title;
  let _tableJson: any = tableJson;
  if (Object.keys(_tableJson).includes(item.table)) {
    if (item.search?.titleKey) {
      Object.keys(_tableJson[item.table]).includes(item.search?.titleKey) &&
        (_title = t(`table.${item.table}.${item.search?.titleKey}`));
    } else if (item.search?.key) {
      Object.keys(_tableJson[item.table]).includes(item.search?.key) && (_title = t(`table.${item.table}.${item.search?.key}`));
    } else {
      Object.keys(_tableJson[item.table]).includes(item.field) && (_title = t(`table.${item.table}.${item.field}`));
    }
  }
  // console.log("typeof t(`table.${item.table}.${item.search?.key}`) :>> ", typeof t(`table.${item.table}.${item.search?.key}`));
  // console.log("t(`table.${item.table}.${item.search?.key}`) :>> ", t(`table.${item.table}.${item.search?.key}`));
  // let _search = t(`table.${item.table}.${item.search?.key}`);

  // if (item.search?.titleKey) {
  //   let tit = t(`table.${item.table}.${item.search?.titleKey}`);
  //   tit.indexOf("table.") !== 0 && (_title = tit);
  // } else if (item.search?.key) {
  //   let tit = t(`table.${item.table}.${item.search?.key}`);
  //   tit.indexOf("table.") !== 0 && (_title = tit);
  // }

  return _title;
};

/**
 * @description 编辑搜索方案
 */
const editSearchProject = ref(false);
const addVisible = ref(false);
const editVisible = ref(false);
const newProjectName = ref("");
const editProjectName = ref("");
const ProjectEditNameRef = ref();
const ProjectNameRef = ref();
const editPopoverRef = ref();
const ProjectRef = ref();
const currentIndex = ref(-1);

/**
 * @description 搜索方案：排除字段
 */
const searchProjectExcludeField = ["pageNum", "pageSize"];

/**
 * @description 新增搜索方案
 */
const handelAddSearchProject = () => {
  if (oriProject.value.length > 10) {
    ElMessage.error(t("business.searchProject.excess"));
  } else {
    collapsed.value = false;
    nextTick(() => {
      addVisible.value = true;
      ProjectNameRef.value.focus();
    });
  }
};

const funcToDefine = () => {
  editSearchProject.value = false;
  addVisible.value = false;
  currentIndex.value = -1;
};

/**
 * @description 新增搜索方案
 */
const gotoAddSearchProject = () => {
  if (!newProjectName.value) {
    ElMessage.error(t("business.searchProject.emptyTip"));
    return;
  }
  let sameIdx = oriProject.value.findIndex((item: any) => item.name === newProjectName.value);
  if (sameIdx != -1) {
    ElMessage.error(t("business.searchProject.sameName"));
    return;
  }

  let _params = cloneDeep(props.searchParam);
  // 排除字段
  _params = omit(_params, searchProjectExcludeField);
  let _project: searchProjectItem = {
    name: newProjectName.value,
    value: _params
  };

  oriProject.value.push(_project);

  emit("saveProject", flatColumns.value, oriProject.value, () => {
    funcToDefine();
    newProjectName.value = "";
  });
};

/**
 * @description 编辑前的搜索方案
 */
const oriProject = ref<searchProjectItem[]>([]);
watch(
  () => props.project,
  (newVal: any) => {
    // console.log("warch project newVal :>> ", newVal);
    let _data = newVal ?? [];

    oriProject.value = cloneDeep(_data);
  },
  { deep: true }
);

const cancelEditSearchProject = () => {
  console.log("cancelEditSearchProject :>> ", settingStatus.value, props.project);
  oriProject.value = cloneDeep(props.project ?? []);
  funcToDefine();
};

const updateProject = () => {
  if (currentIndex.value != -1) {
    let _params = cloneDeep(props.searchParam);
    // 排除字段
    _params = omit(_params, searchProjectExcludeField);
    let _project: searchProjectItem = {
      name: oriProject.value[currentIndex.value].name,
      value: _params
    };

    oriProject.value[currentIndex.value] = _project;
  }
};

/**
 * @description 保存搜索方案
 */
const handelSaveSearchProject = () => {
  updateProject();

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

  emit("saveProject", flatColumns.value, oriProject.value, () => {
    funcToDefine();
  });
};

/**
 * @description 编辑时，点击搜索方案
 * @param index 索引
 */
const handleSelProject = (index: number) => {
  console.log(
    "handleSelProject ProjectRef.value :>> ",
    index,
    ProjectRef.value,
    oriProject.value,
    editSearchProject.value,
    currentIndex.value
  );
  if (!oriProject.value.length) {
    return;
  }
  if (editSearchProject.value) {
    if (currentIndex.value == index) {
      editProjectName.value = oriProject.value[index].name;
    } else {
      editVisible.value = false;

      updateProject();

      currentIndex.value = index;
    }
  }
  emit("updataParams", oriProject.value[index].value);
  !editSearchProject.value && props.search();
};

const handleDelProject = (index: number) => {
  oriProject.value.splice(index, 1);
  currentIndex.value = -1;
};

const handleCancelEdit = () => {
  editVisible.value = false;
  console.log("handleCancelEdit editVisible.value :>> ", editVisible.value);
};
const handleOkEdit = () => {
  oriProject.value[currentIndex.value].name = editProjectName.value;
  editVisible.value = false;
};

const searchFormRef = ref();
/**
 * @description 点击外部，折叠搜索栏
 */
onClickOutside(searchFormRef, event => {
  console.log("onClickOutside event :>> ", event);
  console.log(
    "onClickOutside showCollapse.value, collapsed.value, addVisible.value editVisible.value :>> ",
    showCollapse.value,
    collapsed.value,
    addVisible.value,
    editVisible.value
  );
  if (
    showCollapse.value &&
    !collapsed.value &&
    !addVisible.value &&
    !editVisible.value &&
    !editSearchProject.value &&
    !settingStatus.value
  ) {
    collapsed.value = !collapsed.value;
  }
});

/**
 * @description 缩小搜索栏，breakPoint的范围
 */
// const sizeExtent = ["xs", "sm", "md"];

watch(
  () => props.columns,
  val => {
    if (!val.length) return;
    resetPublicAttr();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.setting-grid-item {
  position: relative;
  &::before {
    position: absolute;
    inset: -4px;
    z-index: 10;
    content: "";
    border: 2px dashed $color-primary-100;
    border-radius: $br-sm;
  }
  &.is-active::before,
  &:hover::before {
    position: absolute;
    inset: -4px;
    z-index: 10;
    cursor: pointer;
    content: "";

    // 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-color: $color-primary-500;
    border-style: dashed;
  }
}
.setting-main {
  .setting-main_private,
  .setting-main_public {
    position: relative;
  }
  .setting-main_private::before,
  .setting-main_public::before {
    position: absolute;
    top: -16px;
    left: 0;
    color: $color-text-disable;
    content: attr(data-title);

    @include text-style-footnote-description;
  }
  .setting-main_private::after,
  .setting-main_public::after {
    position: absolute;
    inset: -4px -8px;
    z-index: -1;
    content: "";
    background-color: $color-gray-3;
    border: 2px solid $color-gray-1;
    border-radius: $br-md;
    box-shadow: $shadow-1-down;
  }
  .setting-main_private::before {
    color: $color-primary-400;

    // opacity: 0.5;
  }
  .setting-main_private::after {
    background-color: $color-primary-100;
  }
  .setting-main_private {
    height: 32px;
  }
}
.vxetable-search {
  position: relative;

  :deep(.el-form-item__label) {
    color: $color-text-secondary-text;
    padding: 0 8px 0 0;
  }
  .to-search {
    :deep(.el-form-item__label) {
      color: $color-primary-700;
    }
  }
  :deep(.el-form-item) {
    margin-bottom: 12px;
    &.el-form-item--small {
      margin-bottom: 8px;

      .el-form-item__label {
        padding: 0 4px 0 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;
    }
  }
}

.table-search {
  padding: 12px 18px 0;
}
.lj-main-body.small .table-search {
  padding: 8px 8px 0;
}
.my-search-project {
  .project-list {
    .el-tag {
      cursor: pointer;
      user-select: none;
      &:hover {
        color: $color-primary-500;
        background-color: $color-primary-200;
        border-color: $color-primary-300;
      }
      &:active {
        transform: translateY(2px);
      }
      &.is-active {
        color: $color-primary-500;
        background-color: $color-primary-100;
        border-color: $color-primary-200;
      }

      .edit-btn {
        margin: auto;
        text-align: center;
        display: inline-block;
        border-radius: 50%;
        cursor: pointer;
        height: var(--el-icon-size);
        width: var(--el-icon-size);

        &:hover {
          background-color: $color-primary-500;
          color: $color-primary-200;
        }
      }
      .iconfont {
        font-size: calc(var(--el-icon-size) - 4px);
      }
    }
    .el-tag + .el-tag {
      margin-left: $space-b1;
    }
  }
}
.search-btn-dropdown {
  :deep(.el-button-group) {
    .el-button:first-child {
      border-top-left-radius: 16px;
      border-bottom-left-radius: 16px;
    }
    .el-button:last-child {
      border-top-right-radius: 16px;
      border-bottom-right-radius: 16px;
    }
  }
}
</style>
