<template>
  <el-dialog
    :title="$t('business.home.setting.title')"
    :class="`${prefixCls}`"
    width="50%"
    draggable
    v-model="drawerVisible"
    align-center
    :modal="false"
    @close="close"
  >
    <el-steps :active="active" finish-status="success" process-status="finish" simple class="flx-shrink">
      <el-step title="选择模块" :icon="Finished" />
      <el-step title="布局设置" :icon="Grid" />
    </el-steps>
    <template v-if="active == 0">
      <el-row :gutter="12" :class="`${prefixCls}__select-part mt-8 enter-x flx-1`">
        <el-col :span="8">
          <div class="tree h-full">
            <header class="flx-start">
              <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-tree
              ref="elTreeRef"
              :data="homeFunctionTree"
              nodeKey="id"
              show-checkbox
              default-expand-all
              :default-checked-keys="defaultCheckedKeys"
              :expand-on-click-node="false"
              :props="treeProps"
              :filter-node-method="filterNode"
              @node-click="handleClickNode"
            ></el-tree>
          </div>
        </el-col>
        <el-col :span="16">
          <div class="content h-full"></div>
        </el-col>
      </el-row>
    </template>
    <template v-else-if="active == 1">
      <el-row :gutter="12" :class="`${prefixCls}__layout-part mt-8 -enter-x flx-1`">
        <el-col :span="16">
          <draggable
            class="left h-full"
            v-model="dwLayout.layoutLeft"
            item-key="id"
            animation="300"
            forceFallback="true"
            group="layout"
          >
            <template #item="{ element }">
              <loadingCom :label="element.label" :type="element.type" :animated="false" />
            </template>
          </draggable>
        </el-col>
        <el-col :span="8">
          <draggable
            class="right h-full"
            v-model="dwLayout.layoutRight"
            item-key="id"
            animation="300"
            forceFallback="true"
            group="layout"
          >
            <template #item="{ element }">
              <loadingCom :label="element.label" :type="element.type" :animated="false" />
            </template>
          </draggable>
        </el-col>
      </el-row>
    </template>
    <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 v-if="active == 0" type="primary" plain @click="toNextStep">{{ $t("common.next") }}</el-button>
          <template v-else>
            <el-button @click="toPrevious">{{ $t("common.previous") }}</el-button>
            <el-button type="primary" @click="confirm">
              {{ $t("common.okText") }}
            </el-button>
          </template>
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="tsx" name="HomeLayoutSetting">
import { ref, reactive, provide, watch, nextTick } from "vue";
import { Finished, Grid, Search, Close, RefreshRight } from "@element-plus/icons-vue";
import { 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 } from "lodash-es";
import { streamlineFunc } from "@/utils";
import draggable from "vuedraggable";
import loadingCom from "../Base/loading.vue";

const { t } = useI18n();

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

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 active = ref(0);
const filterText = ref();
const filterInputRef = ref();
const layoutRightKeys = ref<string[]>([]);
const dwLayout = ref();
const elTreeRef = ref<InstanceType<typeof ElTree>>();
/**
 * @description 移除字段
 */
const layoutDelAttr = ["label"];
// const layoutDefaultAttr = ["component", "type"];

/**
 * @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/aside"
      },
      {
        id: "outwareOverview",
        label: t("business.home.layout.outwareOverview"),
        type: "dashboard",
        component: "Dashboard/aside"
      },
      {
        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"
      }
    ]
  },
  {
    id: "mainBusiness",
    label: t("business.home.layout.mainBusiness"),
    children: [
      {
        id: "saletaskMx",
        label: t("business.home.layout.saletaskmx"),
        type: "table",
        component: "SaletaskMx/index"
      }
    ]
  }
];

// 关键字,筛选
watch(filterText, val => {
  ifSearch.value && elTreeRef.value!.filter(val);
});

// 筛选钩子
const filterNode = (value: string, data: any, node: any) => {
  if (!value) return true;
  return partentFilter(value, data, node);
};

/**
 * 拼音筛选,父级符合,其自己,孙集均符合
 * @param value keyword
 * @param data 当前层级数据
 * @param node 节点
 */
const partentFilter = (value: string, data: any, node: any): boolean => {
  let arr = pinyinFilter(value, [data], ["label"]);
  console.log("arr :>> ", arr);
  console.log("data :>> ", data);
  console.log("node.parent level :>> ", node.parent.level);
  if (arr.length > 0) {
    return true;
  } else if (node.parent.level > 0) {
    return partentFilter(value, node.parent.data, node.parent);
  } else {
    return false;
  }
};

/**
 * 将多维集合改写成一维集合
 * @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 = () => {
  dwLayout.value = null;
  active.value = 0;
  drawerVisible.value = true;
  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);
};

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

/**
 * @description 精简储存内容
 */
const omitFunc = (data: any) => {
  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) => {
          return omit(item, layoutDelAttr);
        });
      }
    }
  }
  console.log("_dwLayout :>> ", _dwLayout);
  // 去除默认值
  // let saveCol = streamlineFunc(column, props.layoutAttr, props.layoutAttrDefine);
  return _dwLayout;
};

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

  let funcArr = getOneArr(homeFunctionTree);
  // console.log("setDefaultFunc funcArr :>> ", 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);
          return Object.assign(item, originItm);
        });
      }
    }
  }
  // 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);
};

const handleClickNode = (data: any) => {
  console.log("data :>> ", data);
};

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

/**
 * @description 下一步:布局设置
 */
const toNextStep = () => {
  active.value++;
  console.log("dwLayout.value bf :>> ", dwLayout.value);
  dwLayout.value = dwLayout.value ?? cloneDeep(prop.layout);
  let checkedKeys = elTreeRef.value?.getCheckedKeys(true);
  let checkedNodes = elTreeRef.value?.getCheckedNodes(true, true);
  defaultCheckedKeys.value = checkedKeys;
  console.log("checkedKeys :>> ", checkedKeys);
  console.log("ref.getCheckedNodes :>> ", elTreeRef.value?.getCheckedNodes(true, true));

  // 检查还在右侧布局列表的模块是否还在(取多数组中,重复部分)
  let _right = intersection(layoutRightKeys.value, checkedKeys);
  console.log("_right :>> ", _right);

  let _left = difference(checkedKeys, _right);
  console.log("_left :>> ", _left);

  console.log("checkedNodes :>> ", checkedNodes);
  let leftPart = checkedNodes?.filter(item => _left.includes(item.id));
  console.log("leftPart :>> ", leftPart);
  leftPart?.forEach(item => {
    let originItm = dwLayout.value.layoutLeft.find((itm: any) => itm.id === item.id);
    console.log("originItm :>> ", originItm);
    item = Object.assign(item, originItm);
  });
  console.log("leftPart :>> ", leftPart);
  dwLayout.value.layoutLeft = leftPart;

  let rightPart = dwLayout.value.layoutRight?.filter((item: any) => _right.includes(item.id));
  let _rightPart: any = [];
  rightPart.forEach((item: any) => {
    let checkItem = checkedNodes?.find((itm: any) => itm.id === item.id) ?? {};
    console.log("checkItem :>> ", checkItem);
    console.log("item :>> ", item);
    let obj = Object.assign({}, checkItem, item);
    console.log("item aff:>> ", obj);
    _rightPart.push(obj);
  });
  console.log("_rightPart :>> ", _rightPart);
  dwLayout.value.layoutRight = _rightPart;

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

/**
 * @description 上一步
 */
const toPrevious = () => {
  active.value--;
  console.log("toPrevious dwLayout.value :>> ", dwLayout.value);

  // 记录当前在右侧keys
  let _right = streamlineFunc(dwLayout.value.layoutRight, ["id"], {});
  layoutRightKeys.value = _right.map(item => item.id);
};

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

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