<template>
  <el-dialog
    :title="$t('business.home.setting.title')"
    :class="`${prefixCls}`"
    width="80%"
    draggable
    v-model="drawerVisible"
    align-center
    :modal="false"
    @close="close"
  >
    <el-row :gutter="12" :class="`${prefixCls}__select-part enter-x flx-1`">
      <el-col :span="19">
        <div class="flx h-full">
          <div class="tree h-full mr-12 flx-shrink card">
            <header class="flx-start mb-8">
              <div class="flx-start flx-1">
                <span v-if="!ifSearch" class="ml-8 text-h5-m">{{ $t("business.home.setting.treeTitle") }}</span>
                <el-input
                  v-else
                  ref="filterInputRef"
                  v-model="filterText"
                  class="flx-1 ml-12 mr-12"
                  :placeholder="$t('business.home.setting.placeholder')"
                ></el-input>
              </div>
              <div class="flx-shrink">
                <el-button :icon="!ifSearch ? Search : Close" circle @click.stop="searchCompany" />
              </div>
            </header>
            <el-collapse v-model="activeNames" class="func-menu">
              <el-collapse-item
                class="func-group"
                :title="item.label"
                :name="item.id"
                v-for="(item, index) in homeFunctionTree"
                :key="index"
              >
                <draggable
                  class="func-group-content"
                  v-model="item.children"
                  item-key="id"
                  :scroll="true"
                  animation="300"
                  forceFallback="true"
                  :group="funcMenuGroup"
                  draggable=".move"
                >
                  <template #item="{ element }">
                    <div
                      class="func-item user-sel-none flx-col"
                      :class="{ move: defaultCheckedKeys.indexOf(element.id) == -1 }"
                      v-if="matchFunctionKeys.indexOf(element.id) > -1"
                    >
                      <el-button
                        class="del-btn"
                        circle
                        plain
                        size="small"
                        :type="defaultCheckedKeys.indexOf(element.id) > -1 ? 'warning' : 'success'"
                        :icon="defaultCheckedKeys.indexOf(element.id) > -1 ? Minus : Plus"
                        @click.stop="onAddOrDelFunc(element)"
                      ></el-button>
                      <i class="iconfont iconMoreSquare_light"></i>
                      <div class="title">
                        {{ element.label }}
                      </div>
                    </div>
                  </template>
                </draggable>
              </el-collapse-item>
            </el-collapse>
          </div>
          <el-row :gutter="12" :class="`${prefixCls}__layout-part enter-x flx-1 h-full`">
            <el-col :span="16">
              <draggable
                class="left h-full"
                v-model="dwLayout.layoutLeft"
                item-key="id"
                animation="300"
                :scroll="true"
                forceFallback="true"
                group="layout"
                ghost-class="ghost-item"
                @add="onCloneFunc"
              >
                <template #item="{ element, index }">
                  <div
                    class="func-item user-sel-none"
                    :class="{ 'is-current': layoutAttrName == 'layoutLeft' && currentIndex == index }"
                    @click="handleSelFunc(element.id, 'layoutLeft')"
                  >
                    <el-button
                      class="del-btn"
                      circle
                      plain
                      size="small"
                      type="danger"
                      :icon="Close"
                      @click.stop="onAddOrDelFunc(element)"
                    ></el-button>
                    <loadingCom :label="element.label" :type="element.type" :animated="false" />
                  </div>
                </template>
              </draggable>
            </el-col>
            <el-col :span="8">
              <draggable
                class="right h-full"
                v-model="dwLayout.layoutRight"
                item-key="id"
                :scroll="true"
                animation="300"
                forceFallback="true"
                group="layout"
                ghost-class="ghost-item"
                @add="onCloneFunc"
              >
                <template #item="{ element, index }">
                  <div
                    class="func-item user-sel-none"
                    :class="{ 'is-current': layoutAttrName == 'layoutRight' && currentIndex == index }"
                    @click="handleSelFunc(element.id, 'layoutRight')"
                  >
                    <el-button
                      class="del-btn"
                      circle
                      plain
                      size="small"
                      type="danger"
                      :icon="Close"
                      @click.stop="onAddOrDelFunc(element)"
                    ></el-button>
                    <loadingCom :label="element.label" :type="element.type" :animated="false" />
                  </div>
                </template>
              </draggable>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <el-col :span="5">
        <div :class="`${prefixCls}__aside-menu card content enter-x h-full`">
          <el-tabs v-model="rightAsignActive" :class="` flx-col h-full `" stretch>
            <el-tab-pane
              :label="
                (currentFunctionKey != '' ? dwLayout[layoutAttrName][currentIndex].label + ':' : '') +
                $t('business.home.setting.customProperties')
              "
              name="style"
              class="h-full"
            >
              <template v-if="currentFunctionKey == ''">
                <el-empty :description="$t('sys.empty.tableColSet')" />
              </template>
              <template v-else>
                <el-scrollbar>
                  <CellGroup :title="$t('sys.setting.attributes')">
                    <el-form
                      :label-position="['toOutStatistic'].includes(currentFunctionKey) ? 'top' : 'right'"
                      :model="dwLayout[layoutAttrName][currentIndex]"
                      label-width="100"
                    >
                      <template v-if="homeFunctionAttr[currentFunctionKey]">
                        <el-form-item
                          v-for="(item, index) in homeFunctionAttr[currentFunctionKey]"
                          :key="'ArrtSetting' + index"
                          :label="item.label"
                          :prop="item.key"
                        >
                          <ArrtSetting :data="item" :param="dwLayout[layoutAttrName][currentIndex]" />
                        </el-form-item>
                      </template>
                      <el-empty v-else description="暂无属性" />
                    </el-form>
                  </CellGroup>
                </el-scrollbar>
              </template>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>

    <template #footer>
      <div class="flx-justify-between">
        <div class="footer-tips flx-start">
          <el-button text bg @click="reset">{{ $t("common.resetDefault") }}</el-button>
          <el-button text @click="refresh" :icon="RefreshRight">{{ $t("common.redo") }}</el-button>
        </div>
        <div class="dialog-footer">
          <!-- <el-button @click="close">{{ $t("common.cancelText") }}</el-button> -->
          <el-button type="primary" plain @click="confirm">{{ $t("common.saveText") }}</el-button>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="HomeLayoutSetting">
import { ref, reactive, provide, watch, nextTick, computed } from "vue";
import { Delete, Plus, Search, Close, RefreshRight, Minus } from "@element-plus/icons-vue";
import { ElMessage, ElTree } from "element-plus";
import { isArray, isObject } from "@/utils/is";
import { pinyinFilter } from "@/utils/pinyin";
import { useDesign } from "@/hooks/useDesign";
import { useI18n } from "vue-i18n";
import { intersection, difference, cloneDeep, omit, flattenDeep, pick } from "lodash-es";
import { streamlineFunc } from "@/utils";
import draggable from "vuedraggable";
import loadingCom from "../Base/loading.vue";
import ArrtSetting from "./components/ArrtSetting/index.vue";
import dayjs from "dayjs";
import { getDiffToDate, setDateToDiff } from "../../interface/index";

const { t } = useI18n();

interface SelectorTreeProps {
  /**
   * @description 当前布局
   */
  layout: any;
  /**
   * @description 默认布局
   */
  defaultLayout: any;
}

interface dateStatisticProps {
  /**
   * @description 时间单位
   */
  unit: "day" | "week";
  /**
   * @description 开始时间差异
   */
  startDiff?: number;
  /**
   * @description 开始时间
   */
  startTime?: string;
  /**
   * @description 结束时间差异
   */
  endDiff?: number;
  /**
   * @description 结束时间
   */
  endTime?: string;
}

const prop = withDefaults(defineProps<SelectorTreeProps>(), {
  defaultLayout: []
});

const { prefixCls } = useDesign("home-layout-setting");
// const dwname = "web_fx_saletaskmx_sel";
const drawerVisible = ref(false);
const ifSearch = ref(false);
const emit = defineEmits(["confirm", "refresh"]);
const filterText = ref("");
const filterInputRef = ref();
const layoutRightKeys = ref<string[]>([]);
const dwLayout = ref<any>({
  layoutLeft: [],
  layoutRight: []
});
// const elTreeRef = ref<InstanceType<typeof ElTree>>();
/**
 * @description 移除字段
 */
// const layoutDelAttr = ["label"];
// const layoutDefaultAttr = ["component", "type"];
const funcMenuGroup = { name: "layout", pull: "clone", put: false };
const homeFunctionList = ref<any>([]);
const matchFunctionKeys = ref<string[]>([]);
const activeNames = ref<string[]>(["dataIndicators", "auxiliaryTools", "mainBusiness"]);
/**
 * @description 当前点击的模块,左还是右
 * @params layoutLeft Or layoutRight
 */
const layoutAttrName = ref<string>("");
/**
 * @description 当前点击的模块id值
 */
const currentFunctionKey = ref<string>("");
/**
 * @description 当前点击的模块id值
 */
const currentIndex = computed(() => {
  let index = -1;
  if (layoutAttrName.value != "") {
    index = dwLayout.value[layoutAttrName.value].findIndex((item: any) => item.id == currentFunctionKey.value);
  }
  console.log("currentIndex index :>> ", index);
  return index;
});
const rightAsignActive = ref("style");
// 定义 enumMap 存储 enum 值（避免异步请求无法格式化单元格内容 || 无法填充搜索下拉选择）
const enumMap = ref(new Map<string, { [key: string]: any }[]>());

/**
 * @description 默认选中keys
 */
const defaultCheckedKeys = ref<any>([]);

/**
 * @description 功能展示树, 出厂设置
 */
const homeFunctionTree = [
  {
    id: "dataIndicators",
    label: t("business.home.layout.dataIndicators"),
    children: [
      {
        id: "saletaskMxStatistic",
        label: t("business.home.layout.saletaskMxStatistic"),
        type: "dashboard",
        component: "Dashboard/index"
      },
      {
        id: "toOutStatistic",
        label: t("business.home.layout.toOutStatistic"),
        type: "dashboard",
        component: "Dashboard/ToOut",
        toOutType: []
      },
      {
        id: "outwareOverview",
        label: t("business.home.layout.outwareOverview"),
        type: "list",
        component: "Dashboard/outware",
        heightType: "fixed",
        height: 300
      },
      {
        id: "myCust",
        label: t("business.home.layout.myCust"),
        type: "list",
        component: "MyCust/index"
      }
    ]
  },
  {
    id: "auxiliaryTools",
    label: t("business.home.layout.auxiliaryTools"),
    children: [
      {
        id: "quickEnter",
        label: t("business.home.layout.commonFunctions"),
        type: "function",
        component: "QuickEnter/index",
        size: "default"
      }
    ]
  },
  {
    id: "mainBusiness",
    label: t("business.home.layout.mainBusiness"),
    children: [
      {
        id: "saletaskMx",
        label: t("business.home.layout.saletaskmx"),
        type: "table",
        component: "SaletaskMx/index",
        heightType: "auto",
        height: 300,
        minHeight: 300
      }
    ]
  }
];

/**
 * @description 功能展示树, 属性列表
 */
const homeFunctionAttr: any = {
  saletaskMx: [
    {
      el: "radio-group",
      key: "heightType",
      label: t("business.home.setting.attr.heightType"),
      enum: [
        {
          label: t("business.home.setting.attr.heightAuto"),
          value: "auto"
        },
        {
          label: t("business.home.setting.attr.heightFixed"),
          value: "fixed"
        }
      ]
    },
    {
      el: "input-number",
      key: "height",
      label: t("business.home.setting.attr.height"),
      props: {
        step: 100,
        min: 200,
        max: 2000
      },
      render: (scope: any) => {
        console.log("scope :>> ", scope);
        let _disabled = scope.param.heightType === "auto";
        return (
          <el-input-number
            class={"w-full"}
            v-model={scope.param.height}
            disabled={_disabled}
            step={scope.step}
            min={scope.min}
            max={scope.max}
          />
        );
      }
    },
    {
      el: "input-number",
      key: "minHeight",
      label: t("business.home.setting.attr.minHeight"),
      props: {
        step: 100,
        min: 200,
        max: 2000
      },
      render: (scope: any) => {
        console.log("scope :>> ", scope);
        return (
          <el-input-number class={"w-full"} v-model={scope.param.minHeight} step={scope.step} min={scope.min} max={scope.max} />
        );
      }
    }
  ],
  outwareOverview: [
    {
      el: "radio-group",
      key: "heightType",
      label: t("business.home.setting.attr.heightType"),
      enum: [
        {
          label: t("business.home.setting.attr.heightAuto"),
          value: "auto"
        },
        {
          label: t("business.home.setting.attr.heightFixed"),
          value: "fixed"
        }
      ]
    },
    {
      el: "input-number",
      key: "height",
      label: t("business.home.setting.attr.height"),
      props: {
        step: 100,
        min: 200,
        max: 1000
      },
      render: (scope: any) => {
        console.log("scope :>> ", scope);
        let _disabled = scope.param.heightType === "auto";
        return (
          <el-input-number
            class={"w-full"}
            v-model={scope.param.height}
            disabled={_disabled}
            step={scope.step}
            min={scope.min}
            max={scope.max}
          />
        );
      }
    }
  ],
  saletaskMxStatistic: [
    {
      el: "checkbox-group",
      key: "statistic",
      label: t("business.home.setting.attr.statistic"),
      props: {
        define: true
      },
      enum: [
        {
          label: t("business.home.saletaskMxStatistic.toReceive"),
          value: "toReceive"
        },
        {
          label: t("business.home.saletaskMxStatistic.toResponse"),
          value: "toResponse"
        },
        {
          label: t("business.home.saletaskMxStatistic.toOut"),
          value: "toOut"
        }
      ]
    }
  ],
  toOutStatistic: [
    {
      key: "toOutType",
      label: t("business.home.setting.attr.toOutType"),
      props: {
        define: true
      },
      enum: [
        {
          label: t("business.home.saletaskMxStatistic.today"),
          value: "today",
          unit: "day",
          startDiff: 0,
          endDiff: 0
        },
        {
          label: t("business.home.saletaskMxStatistic.next3Days"),
          value: "toRenext3Dayssponse",
          unit: "day",
          startDiff: 1,
          endDiff: 3
        },
        {
          label: t("business.home.saletaskMxStatistic.thisWeek"),
          value: "thisWeek",
          unit: "week",
          startDiff: 1,
          endDiff: 7
        },
        {
          label: t("business.home.saletaskMxStatistic.nextWeek"),
          value: "nextWeek",
          unit: "week",
          startDiff: 8,
          endDiff: 14
        },
        {
          label: t("business.home.saletaskMxStatistic.next30Days"),
          value: "next30Days",
          unit: "day",
          startDiff: 1,
          endDiff: 30
        }
      ],
      render: (scope: any) => {
        console.log("saletaskMxStatistic scope :>> ", scope);
        let _enumMap = enumMap.value.get("toOutType");
        console.log("enumMap.value :>> ", enumMap.value);
        console.log("_enumMap :>> ", _enumMap);

        const chidlrenSlot = {
          item: (data: any) => {
            return (
              <div class={"to-out_type-item flx-justify-between"}>
                <i class={"iconfont iconCategory handle mr-8"}></i>
                <el-button
                  class={"del-btn"}
                  type={"danger"}
                  icon={Delete}
                  circle
                  plain
                  size={"small"}
                  onClick={() => handelClickDelToOut("toOutType", data)}
                />
                <div class={"item-content flx-col flx-1"}>
                  <div class={"flx-start"}>
                    <span class={"title text-body-r pr-4 flx-shrink"}>{t("business.home.setting.attr.label")}:</span>
                    <el-input
                      v-model={data.element.label}
                      placeholder={t("business.home.setting.attr.label")}
                      maxlength={"10"}
                      showWordLimit={true}
                      class={"flx-1"}
                    />
                  </div>
                  <div class={"flx-start"}>
                    <span class={"title text-body-r pr-4 flx-shrink"}>{t("business.home.setting.attr.dateUnit")}:</span>
                    <el-select v-model={data.element.unit} style={"width: 70px"}>
                      <el-option label={t("business.home.setting.attr.day")} value={"day"} />
                      <el-option label={t("business.home.setting.attr.week")} value={"week"} />
                    </el-select>
                  </div>
                  <div class={"flx-start"}>
                    <span class={"title text-body-r pr-4 flx-shrink"}>{t("business.home.setting.attr.start")}:</span>
                    <el-date-picker
                      v-model={data.element.startTime}
                      type="date"
                      value-format={"YYYY-MM-DD"}
                      placeholder={t("business.home.setting.attr.start")}
                      class={"flx-1"}
                    />
                  </div>
                  <div class={"flx-start"}>
                    <span class={"title text-body-r pr-4 flx-shrink"}>{t("business.home.setting.attr.end")}:</span>
                    <el-date-picker
                      v-model={data.element.endTime}
                      type="date"
                      value-format={"YYYY-MM-DD"}
                      placeholder={t("business.home.setting.attr.end")}
                      class={"flx-1"}
                    />
                  </div>
                </div>
              </div>
            );
          }
        };

        const recommendRender = () => {
          return (
            <div class={"recommend-list mt-8"}>
              {_enumMap?.map((item: any) => {
                return (
                  <el-tag
                    class={"recommend-item"}
                    type={"info"}
                    effect={"plain"}
                    round={true}
                    onClick={() => handelClickAddToOut("toOutType", item)}
                  >
                    <el-icon class={"mr-2"} size={"small"}>
                      <Plus />
                    </el-icon>
                    {item.label}
                  </el-tag>
                );
              })}
            </div>
          );
        };

        return (
          <div class={"to_out_type flx-col w-full"}>
            <draggable
              v-model={scope.param.toOutType}
              item-key={"type"}
              animation={"300"}
              forceFallback={true}
              group={"saletaskMxStatistic"}
              handle={".handle"}
              v-slots={chidlrenSlot}
            ></draggable>
            <el-divider>{t("business.home.saletaskMxStatistic.recommend")}</el-divider>
            {recommendRender()}
          </div>
        );
      }
    }
  ],
  quickEnter: [
    {
      el: "radio-group",
      key: "size",
      label: t("business.home.setting.attr.size"),
      enum: [
        {
          label: t("common.small"),
          value: "small"
        },
        {
          label: t("common.default"),
          value: "default"
        },
        {
          label: t("common.large"),
          value: "large"
        }
      ]
    }
  ]
};

/**
 * 待发货属性面板:点击推荐列表,增加时间列表
 * @param data
 */
const handelClickAddToOut = (attr: string, data?: any) => {
  if (dwLayout.value[layoutAttrName.value][currentIndex.value][attr].length >= 5) {
    ElMessage.warning(t("business.home.saletaskMxStatistic.overTips"));
    return;
  }
  let _date = getDiffToDate(data);
  console.log("getDiffToDate Obj :>> ", _date);

  dwLayout.value[layoutAttrName.value][currentIndex.value][attr].push(_date);
  console.log("dwLayout.value :>> ", dwLayout.value);
};

/**
 * 待发货属性面板:删除时间列表
 * @param data
 */
const handelClickDelToOut = (attr: string, data: any) => {
  dwLayout.value[layoutAttrName.value][currentIndex.value][attr].splice(data.index, 1);
};

/**
 * 收集EnumMap,枚举数据
 * @param col
 */
const setEnumMap = async (col: any) => {
  if (!col.enum) return;
  if (enumMap.value.has(col.key)) return;
  // 如果当前 enum 为后台数据需要请求数据，则调用该请求接口，并存储到 enumMap
  if (typeof col.enum !== "function") return enumMap.value.set(col.key!, col.enum!);
  const data = await col.enum();
  enumMap.value.set(col.key!, data);
};
provide("homeAttrEnumMap", enumMap);

const getTail = (item: any) => (item.children && item.children.length > 0 ? item.children.map((m: any) => getTail(m)) : [item]);

// 关键字,筛选
watch(filterText, val => {
  partentFilter(val);
  console.log("matchFunctionKeys.value :>> ", matchFunctionKeys.value);
});

/**
 * 拼音筛选,父级符合,其自己,孙集均符合
 * @param value keyword
 * @param data 当前层级数据
 * @param node 节点
 */
const partentFilter = (value: string): any => {
  let oneArr = flattenDeep(homeFunctionTree.map(m => getTail(m)));
  oneArr = pinyinFilter(value, oneArr, ["label"]);
  console.log("oneArr :>> ", oneArr);
  matchFunctionKeys.value = streamlineFunc(oneArr, ["id"], {}).map(item => item.id);
};

/**
 * 将多维集合改写成一维集合
 * @param arr 多维数组
 */
const getOneArr = (arr: any) => {
  let data = cloneDeep(arr);
  let newData: any = [];
  const callback = (item: any) => {
    (item.children || (item.children = [])).map((v: any) => {
      callback(v);
    });
    delete item.children;
    newData.push(item);
  };
  data.map((v: any) => callback(v));
  return newData;
};

const treeProps = {
  children: "children",
  label: "label"
};

/**
 * @description 展示组件
 */
const show = (callback: any) => {
  dwLayout.value = {
    layoutLeft: [],
    layoutRight: []
  };
  drawerVisible.value = true;
  partentFilter(filterText.value);
  // homeFunctionList.value = partentFilter(filterText.value, homeFunctionTree);
  console.log("homeFunctionList.value :>> ", homeFunctionList.value);
  console.log("prop.layout :>> ", prop.layout);

  // 标记checkbox keys
  let _left = streamlineFunc(prop.layout.layoutLeft, ["id"], {});
  let _right = streamlineFunc(prop.layout.layoutRight, ["id"], {});
  layoutRightKeys.value = _right.map(item => item.id);
  defaultCheckedKeys.value = _left.concat(_right).map(item => item.id);
  dwLayout.value = cloneDeep(prop.layout);

  console.log("defaultCheckedKeys.value :>> ", defaultCheckedKeys.value);

  nextTick(() => {
    callback && callback();
  });
};

/**
 * @description 确认/保存
 */
const confirm = () => {
  emit("confirm", dwLayout.value, () => close());
};
/**
 * @description 刷新本地布局
 */
const refresh = () => {
  emit("refresh");
};

/**
 * @description 精简储存内容
 */
const omitFunc = (data: any) => {
  let defaultFuncArr = getOneArr(homeFunctionTree);
  let _dwLayout = cloneDeep(data);
  for (const key in _dwLayout) {
    if (key === "layoutLeft" || key === "layoutRight") {
      if (_dwLayout[key].length) {
        _dwLayout[key] = _dwLayout[key].map((item: any) => {
          let originItm = defaultFuncArr.find((itm: any) => itm.id === item.id);
          // 精简:收集与默认属性相同的字段名称,删除
          let delAttr = [];
          for (const key in originItm) {
            if (!["id", "label", "type", "component"].includes(key)) {
              console.log(key);
              if (item[key] == originItm[key]) {
                delAttr.push(key);
              }
            }
          }
          let result = omit(item, delAttr);
          // 特殊模块,转义属性
          if (item.id == "toOutStatistic") {
            result.toOutType = result.toOutType.map((item: any) => (item = setDateToDiff(item)));
          }
          return result;
        });
      }
    }
  }
  console.log("_dwLayout :>> ", _dwLayout);
  return _dwLayout;
};

/**
 * @description 补全默认内容
 */
const setDefaultFunc = (data: any) => {
  let _dwLayout = cloneDeep(data);

  let funcArr = getOneArr(homeFunctionTree);
  console.log("setDefaultFunc funcArr :>> ", JSON.stringify(funcArr));

  for (const key in _dwLayout) {
    if (key === "layoutLeft" || key === "layoutRight") {
      if (_dwLayout[key].length) {
        _dwLayout[key] = _dwLayout[key].map((item: any) => {
          let originItm = funcArr.find((itm: any) => itm.id === item.id);
          let result = item;
          if (originItm) {
            item.component = originItm.component;
            item.label = originItm.label;
            item.type = originItm.type;
            result = Object.assign(originItm, item);
          }
          // 特殊模块,转义属性
          if (item.id == "toOutStatistic") {
            result.toOutType = result.toOutType.map((item: any) => (item = getDiffToDate(item)));
          }
          return result;
        });
      }
    }
  }
  console.log("setDefaultFunc funcArr :>> ", JSON.stringify(funcArr));
  console.log("_dwLayout :>> ", _dwLayout);
  return _dwLayout;
};

const close = () => {
  filterText.value = "";
  ifSearch.value = false;
  drawerVisible.value = false;
};

/**
 * @description 重置
 */
const reset = () => {
  // 标记默认checkbox keys
  let _left = streamlineFunc(prop.defaultLayout.layoutLeft, ["id"], {});
  let _right = streamlineFunc(prop.defaultLayout.layoutRight, ["id"], {});
  layoutRightKeys.value = _right.map(item => item.id);
  defaultCheckedKeys.value = _left.concat(_right).map(item => item.id);

  dwLayout.value = setDefaultFunc(prop.defaultLayout);
  // dwLayout.value = cloneDeep(prop.defaultLayout);
  console.log("dwLayout.value.  :>> ", dwLayout.value);
  console.log("defaultCheckedKeys.value :>> ", defaultCheckedKeys.value);
  // elTreeRef.value?.setCheckedKeys(defaultCheckedKeys.value);

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

/**
 * @description 搜索
 */
const searchCompany = () => {
  if (!ifSearch.value) {
    ifSearch.value = true;
    nextTick(() => {
      filterInputRef.value.focus();
    });
  } else {
    ifSearch.value = false;
    filterText.value = "";
  }
};

/**
 * @description 复制后,更新已选keys
 */
const onCloneFunc = (data: any) => {
  nextTick(() => {
    console.log("onCloneFunc data :>> ", data);
    console.log("onCloneFunc data :>> ", data.item._underlying_vm_);
    console.log("onCloneFunc data :>> ", data.target.className);
    let _left = streamlineFunc(dwLayout.value.layoutLeft, ["id"], {});
    let _right = streamlineFunc(dwLayout.value.layoutRight, ["id"], {});
    defaultCheckedKeys.value = _left.concat(_right).map(item => item.id);
    console.log("onCloneFunc defaultCheckedKeys.value :>> ", defaultCheckedKeys.value);

    let _layout = data.target.className.indexOf("left") > -1 ? "layoutLeft" : "layoutRight";
    handleSelFunc(data.item._underlying_vm_.id, _layout);
  });
};

/**
 * 菜单栏,点击增加或删除
 * @param data 数据
 */
const onAddOrDelFunc = (data: any) => {
  let index = defaultCheckedKeys.value.findIndex((item: any) => item == data.id);
  if (index > -1) {
    // Del
    if (currentFunctionKey.value == data.id) {
      currentFunctionKey.value = "";
    }
    let idx = dwLayout.value.layoutLeft?.findIndex((item: any) => item.id == data.id);
    if (idx > -1) {
      console.log("idx :>> ", idx);
      dwLayout.value.layoutLeft.splice(idx, 1);
    } else {
      idx = dwLayout.value.layoutRight?.findIndex((item: any) => item.id == data.id);
      console.log("idx :>> ", idx);
      dwLayout.value.layoutRight.splice(idx, 1);
    }
    defaultCheckedKeys.value = defaultCheckedKeys.value.filter((item: any) => item != data.id);
  } else {
    // Add
    dwLayout.value.layoutLeft.push(data);
    defaultCheckedKeys.value.push(data.id);

    handleSelFunc(data.id, "layoutLeft");
  }
};

/**
 * @description 预览栏,点击,切换属性
 */
const handleSelFunc = (id: string, attr?: string) => {
  let _attr = attr ?? "";
  if (!attr) {
    // 设置时,点击empty,打开设置窗口,并切换至其属性页
    let index = defaultCheckedKeys.value.findIndex((item: any) => item == id);
    if (index > -1) {
      let idx = dwLayout.value.layoutLeft?.findIndex((item: any) => item.id == id);
      if (idx > -1) {
        _attr = "layoutLeft";
      } else {
        idx = dwLayout.value.layoutRight?.findIndex((item: any) => item.id == id);
        _attr = "layoutRight";
      }
    } else {
      return;
    }
  }
  layoutAttrName.value = _attr;
  currentFunctionKey.value = id;

  if (homeFunctionAttr.hasOwnProperty(id)) {
    console.log("homeFunctionAttr[data.id] :>> ", homeFunctionAttr[id]);
    homeFunctionAttr[id].forEach((item: any) => {
      setEnumMap(item);
    });
  }
};

defineExpose({
  // element: elTreeRef,
  homeFunctionTree,
  show,
  close,
  omitFunc,
  setDefaultFunc,
  handleSelFunc
});
</script>

<style lang="scss">
@import "./index.scss";
</style>
