<template>
  <div :class="`${prefixCls} card ${edit ? 'is-edit' : ''}`" ref="QuickEnterRef">
    <header>
      <LjHeader class="flx-1" :title="$t('business.home.quickEnter.title')" />
      <div class="control flx-center">
        <template v-if="!edit">
          <el-button class="hide default-btn" :icon="RefreshRight" text round @click="onRefresh">{{
            $t("common.redo")
          }}</el-button>
          <el-button class="hide default-btn" text round @click="edit = true">{{ $t("common.manage") }} </el-button>
        </template>
        <template v-else>
          <template v-if="empid == 0">
            <el-button class="hide default-btn" type="default" @click="saveDefault"> {{ $t("sys.layout.settings") }} </el-button>
            <el-divider direction="vertical" />
          </template>
          <el-button class="hide default-btn" type="default" @click="cancel">{{ $t("common.cancelText") }} </el-button>
          <el-button class="hide default-btn" type="primary" @click="save">{{ $t("common.saveText") }} </el-button>
        </template>
        <el-button class="default-btn" text round :icon="Plus" @click="toSelectTree"></el-button>
      </div>
    </header>
    <main>
      <!-- <el-empty image="" description="添加常用功能" /> -->
      <div v-if="!funcList.length" class="empty text-disable" @click="toSelectTree">添加常用功能</div>
      <template v-else>
        <draggable v-if="edit" :list="funcList" animation="300" forceFallback="true" item-key="key" style="display: contents">
          <template #item="{ element, index }">
            <EnterItem v-bind="element" :edit="edit" :size="size" @todelect="toDelect(element, index)" />
          </template>
        </draggable>
        <template v-else>
          <EnterItem v-for="item in funcList" :key="item.key" :size="size" v-bind="item" @toclick="toRouter(item)" />
        </template>
        <!-- <EnterItem class="func_add" icon="iconPlus_light" @toclick="toSelectTree" /> -->
      </template>

      <SelectTree
        ref="SelectTreeRef"
        :title="$t('business.selector.tree.title')"
        :data="functionTree"
        :defaultCheckedKeys="defaultCheckedKeys"
        @confirm="toConfirm"
      />
    </main>
  </div>
</template>

<script setup lang="ts" name="home_widget-quick_enter">
import { ref, onMounted, watch, nextTick } from "vue";
import { ElLoading } from "element-plus";
import LjHeader from "@/components/LjHeader/index.vue";
import SelectTree from "@/components/Selector/Tree/index.vue";
import EnterItem from "./components/enterItem.vue";
import draggable from "vuedraggable";
import { useDesign } from "@/hooks/useDesign";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { useGlobalStore } from "@/stores/modules/global";
import { RefreshRight, Plus } from "@element-plus/icons-vue";
import { homeWidgetProps } from "../../interface";
import { useAuthStore } from "@/stores/modules/auth";
import { useUserStore } from "@/stores/modules/user";

const authStore = useAuthStore();

interface QuickEnterProps extends homeWidgetProps {
  size?: "small" | "default" | "large" | "" | undefined;
}

const prop = withDefaults(defineProps<QuickEnterProps>(), {
  id: "",
  initParam: {},
  size: "default"
});

const globalStore = useGlobalStore();
const router = useRouter();
const { prefixCls } = useDesign("home-quick-enter");
const { t } = useI18n();
const edit = ref(false);
const QuickEnterRef = ref();
const SelectTreeRef = ref();
const loading = ref();
const funcList = ref<any>([]);
const emit = defineEmits(["refreshQuickEnter", "saveQuickEnter"]);
const userStore = useUserStore();

const { empid } = userStore.userInfo;

const defaultCheckedKeys = ref<any>([]);

const functionTree = ref<any>([]);
functionTree.value = authStore.quickEnterFuncTreeGet;
console.log("functionTree functionTree :>> ", functionTree.value);

const funcRouter: Map<string, { [key: string]: any }> = authStore.quickEnterFuncTreeRouter;
console.log("funcRouter funcRouter :>> ", funcRouter);
// const funcRouter = new Map<string, { [key: string]: any }>([
//   [
//     "quote",
//     {
//       path: "/quote",
//       name: t("business.home.quickEnter.quote"),
//       icon: "iconconsult-price"
//     }
//   ],
//   [
//     "outware",
//     {
//       path: "/outware",
//       name: t("business.home.quickEnter.outware"),
//       icon: "icontruck-01"
//     }
//   ],
//   [
//     "outware.add",
//     {
//       path: "/outware/new",
//       name: t("business.home.quickEnter.outwareNew"),
//       badge: t("common.add"),
//       icon: "icontruck-01"
//     }
//   ],
//   [
//     "saletask",
//     {
//       path: "/saletask/sale/index",
//       name: "销售订单",
//       icon: "icontruck-01"
//     }
//   ]
// ]);

const setDefaultFunc = (val: any) => {
  // 监听参数变化,并从简化数据还原模型(即:添加path,name,badge属性)
  if (val?.fnlist && val?.fnlist.length) {
    defaultCheckedKeys.value = [];
    let arr = JSON.parse(JSON.stringify(val?.fnlist));
    console.log("setDefaultFunc bf arr :>> ", arr, funcRouter);
    arr.forEach((item: any) => {
      let obj = funcRouter.get(item.funid) || {};
      item = Object.assign(item, obj);
      defaultCheckedKeys.value.push(item.key);
    });
    console.log("setDefaultFunc arr :>> ", arr);
    funcList.value = arr;

    authStore.setCommonMenu(val?.fnlist);
  }
};

watch(
  () => prop.initParam,
  v => {
    console.log("watch v :>> ", v);
    setDefaultFunc(v);
  },
  { immediate: true, deep: true }
);

// 刷新
const onRefresh = () => {
  loading.value = ElLoading.service({
    target: QuickEnterRef.value
  });
  emit("refreshQuickEnter", (v: any) => {
    setDefaultFunc(v);
    nextTick(() => {
      loading.value.close();
    });
  });
};

/**
 * @description 保存
 */
const save = () => {
  edit.value = false;
  emit("saveQuickEnter", prop.id, funcList.value);
};
/**
 * @description 取消
 */
const cancel = () => {
  edit.value = false;
  onRefresh();
};
/**
 * @description 保存默认
 */
const saveDefault = () => {
  emit("saveQuickEnter", prop.id, funcList.value, -1);
};

// 删除
const toDelect = (item: any, idx: number) => {
  funcList.value.splice(idx, 1);
  defaultCheckedKeys.value = [];
  funcList.value.forEach((item: any) => {
    defaultCheckedKeys.value.push(item.key);
  });
  // 更新SelectTree勾选节点
  console.log("toDelect SelectTreeRef.value :>> ", SelectTreeRef.value, SelectTreeRef.value.element);
  SelectTreeRef.value.element && SelectTreeRef.value.element.setCheckedKeys(defaultCheckedKeys.value);
};

// 跳转
const toRouter = (item: any) => {
  if (globalStore.detailBlank) {
    const routeUrl = router.resolve({
      path: item.path
    });
    window.open(routeUrl.href, "_blank");
  } else {
    router.push(item.path);
  }
};

// 选择功能
const toSelectTree = () => {
  SelectTreeRef.value?.show();
};

// 确定选择
const toConfirm = (ref: any) => {
  console.log("ref.getCheckedNodes :>> ", ref?.getCheckedNodes(true, true));
  console.log("ref.getCheckedKeys :>> ", ref?.getCheckedKeys(true));
  let checkedKeys = ref?.getCheckedKeys(true);

  for (let i = funcList.value.length - 1; i >= 0; i--) {
    let keyIdx = checkedKeys?.indexOf(funcList.value[i].key) ?? -1;
    if (keyIdx > -1) {
      // 已勾选的, 忽略
      checkedKeys.splice(keyIdx, 1);
    } else {
      // 未勾选的, 删除
      funcList.value.splice(i, 1);
    }
  }
  console.log("checkedKeys.value :>> ", checkedKeys);

  if (checkedKeys.length > 0) {
    checkedKeys.forEach((item: any) => {
      let obj = funcRouter.get(item) || {};
      let _obj = Object.assign({ key: item }, obj);
      funcList.value.push(_obj);
    });
  }
  console.log("funcList.value :>> ", funcList.value);

  if (!edit.value) {
    emit("saveQuickEnter", prop.id, funcList.value);
  }
  SelectTreeRef.value?.close();
};

onMounted(() => {
  console.log("完成渲染 home_saletask_mx:>> ", prop.initParam);
});

defineExpose({
  onRefresh
});
</script>

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