<template>
  <div class="h-full flx-col">
    <div class="flx-justify-between mb-4">
      <div></div>
      <el-button type="default" text size="small" @click="handleResetLayout">
        <template #icon>
          <i class="iconfont iconflip-backward text-disable"></i>
        </template>
        <span class="text-disable"> 重置布局 </span>
      </el-button>
    </div>
    <el-container class="home-box w-full flx-1 ml-6">
      <el-row class="home-container w-full" :gutter="12">
        <el-col :span="leftLayoutSpan" class="relative" id="home-layout-left">
          <div class="flx-col h-full home-layout" v-if="JSON.stringify(dwLayout) != '{}'">
            <template v-for="(item, idx) in dwLayout.layoutLeft" :key="idx">
              <keep-alive include="WorkPlan">
                <component
                  :ref="(el:any) => setItemRef(el, item.id + 'Ref')"
                  :is="AsyncComp(item.component)"
                  v-bind="{ ...item, initParam: initParam[item.id] }"
                  v-on="comEvent"
                />
              </keep-alive>
            </template>
          </div>
          <!-- <el-tooltip effect="dark" :content="homeLayoutCollapse ? $t('common.table.expand') : $t('common.table.putAway')">
            <el-button
              class="layout-fold-btn"
              :class="{ 'is-fold': homeLayoutCollapse }"
              @click="handleToggleFoldLayout(!homeLayoutCollapse)"
            >
              <template #icon>
                <i class="iconfont iconArrow-Right2"></i>
              </template>
            </el-button>
          </el-tooltip> -->
        </el-col>
        <el-col :span="rightLayoutSpan" style="overflow: auto" :style="rightLayoutStyle">
          <div class="home-layout flx-col h-full" v-if="JSON.stringify(dwLayout) != '{}'">
            <template v-for="(item, idx) in dwLayout.layoutRight" :key="idx">
              <component
                :ref="(el:any) => setItemRef(el, item.id + 'Ref')"
                :is="AsyncComp(item.component)"
                v-bind="{ ...item, initParam: initParam[item.id] }"
                v-on="comEvent"
                class="flx-1"
              />
            </template>
          </div>
        </el-col>
      </el-row>
      <LayoutSetting
        ref="LayoutSettingRef"
        :defaultLayout="defaultLayout"
        :layout="dwLayout"
        @confirm="SaveSettingHomeWidget"
        @refresh="comEvent.refreshLayout"
      />
      <!-- <DragBall ref="DragBallRef" @setting="OpenSettingHomeWidget" /> -->
    </el-container>
  </div>
</template>

<script setup lang="ts" name="home">
import {
  ref,
  reactive,
  provide,
  nextTick,
  defineAsyncComponent,
  onMounted,
  onUnmounted,
  onDeactivated,
  onActivated,
  computed,
  watch,
  inject
} from "vue";
import { ElMessage } from "element-plus";
import { streamlineFunc } from "@/utils";
import { useLayoutLocalStore } from "@/stores/modules/layoutLocal";
import { useLayoutStore } from "@/stores/modules/layout";
import { formatToDateTime, formatToDate } from "@/utils/dateUtil";
import { isArray } from "@/utils/is";
import { useI18n } from "vue-i18n";
// import draggable from "vuedraggable";
import loadingCom from "./components/Base/loading.vue";
import errorCom from "./components/Base/error.vue";
import DragBall from "./components/Base/DragBall.vue";
import LayoutSetting from "./components/Setting/index.vue";
import { cloneDeep } from "lodash-es";
import { useGlobalStore } from "@/stores/modules/global";
import { CommonDynamicSelect } from "@/api/modules/common";
import { useUserStore } from "@/stores/modules/user";
import type { Menu } from "@/typings/global";
import { useAuthStore } from "@/stores/modules/auth";

const authStore = useAuthStore();

interface LayoutItem {
  id: string;
  /**
   * @argument string 组件名称
   */
  component?: string;
  /**
   * @argument any 初始化请求参数 ==> 非必传（默认为{}）
   */
  initParam?: any;
  [key: string]: any;
}

interface LayoutProps {
  /**
   * @argument string 修改时间
   */
  modifydate?: string;
  /**
   * @argument LayoutItem[] 左布局
   */
  layoutLeft?: LayoutItem[];
  /**
   * @argument LayoutItem[] 右布局
   */
  layoutRight?: LayoutItem[];
}

const modules: any = import.meta.glob("./components/**/*.vue");
const { t } = useI18n();
const dwname = "web_home_layout";
const { userInfo } = useUserStore();
// 布局暂存数据
const layoutLocalStore = useLayoutLocalStore();
const layoutStore = useLayoutStore();
const globalStore = useGlobalStore();
const dwLayout = ref<any>({});
const LayoutSettingRef = ref();
// const dialogOutwareRef = ref();
const DragBallRef = ref();
const iframeRefs: any = {};
const setItemRef = (el: any, key: string) => {
  if (el) {
    iframeRefs[key] = el;
  }
};

const homeLayoutCollapse = computed(() => globalStore.homeLayoutCollapse);
const handleToggleFoldLayout = (bool: boolean) => {
  globalStore.setGlobalState("homeLayoutCollapse", bool);
  leftLayoutSpan.value = bool ? 24 : 18;
  rightLayoutSpan.value = bool ? 0 : 6;
};

const leftLayoutSpan = ref(18);
const rightLayoutSpan = ref(6);

const sysPostList = ref<any>([]);
provide("sysPostList", sysPostList);

const initComponetList = ["QuickEnter", "SysPost", "UserPost"];
/**
 * @description 功能展示布局,默认设置
 */
const defaultLayout: LayoutProps = {
  modifydate: "",
  layoutLeft: [
    {
      id: "QuickEnter",
      component: "QuickEnter/index",
      heightType: "auto"
    }
    // {
    //   id: "WorkPlan",
    //   component: "WorkPlan/index",
    //   heightType: "auto"
    // }
  ],
  layoutRight: [
    {
      id: "SysPost",
      component: "SysPost/index"
    },
    {
      id: "UserPost",
      component: "UserPost/index"
    }
  ]
};

let initParam: any = {};

const AsyncComp = (path: string) => {
  console.log("path :>> ", path);
  let _path = `./components/${path}.vue`;
  return defineAsyncComponent({
    // 加载函数
    // loader: () => import(/* @vite-ignore */ _path),
    loader: modules[_path],
    // 加载异步组件时使用的组件
    loadingComponent: loadingCom,
    // 展示加载组件前的延迟时间，默认为 200ms
    delay: 200,
    // 加载失败后展示的组件
    errorComponent: errorCom,
    // 如果提供了一个 timeout 时间限制，并超时了
    // 也会显示这里配置的报错组件，默认值是：Infinity
    timeout: 3000,
    onError(error, retry, fail, attempts) {
      if (error.message.match(/fetch/) && attempts <= 3) {
        retry();
      } else {
        fail();
      }
    }
  });
};

onMounted(async () => {
  let layout = await layoutLocalStore.getDwLayout(dwname);
  console.log("111 layout :>> ", layout);
  init(layout);
});

const init = (layout: any, reset = false) => {
  let localLayout = {};
  if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
    layout.itemvalue = layout.itemvalue.replace(/'/g, '"');
    localLayout = JSON.parse(layout.itemvalue);
  }
  console.log("localLayout :>> ", localLayout);
  console.log("cloneDeep(defaultLayout) :>> ", cloneDeep(defaultLayout));

  if (JSON.stringify(localLayout) != "{}") {
    localLayout = !reset ? Object.assign(cloneDeep(defaultLayout), localLayout) : Object.assign(localLayout);
  } else {
    localLayout = cloneDeep(defaultLayout);
  }
  console.log("after localLayout :>> ", localLayout);
  dwLayout.value = LayoutSettingRef.value?.setDefaultFunc(localLayout);
  console.log("onMounted 111 dwLayout.value :>> ", dwLayout.value);
  for (const key in dwLayout.value) {
    if (isArray(dwLayout.value[key])) {
      let arr = dwLayout.value[key];
      for (let i = 0; i < arr.length; i++) {
        console.log("arr[i] :>> ", arr[i]);
        if (!initComponetList.includes(arr[i].id)) {
          dwLayout.value[key].splice(i, 1);
        } else if (arr[i].hasOwnProperty("initParam")) {
          initParam[arr[i].id] = arr[i].initParam;
        }
      }
    }
  }
  console.log("initParam :>> ", initParam);
};

/**
 * @description 保存自定义模板
 */
const saveLayoutFunc = async (funid: string, data: any, empid?: number) => {
  let _dwLayout = cloneDeep(dwLayout.value);
  console.log("saveLayoutFunc _dwLayout :>> ", _dwLayout);
  for (const key in _dwLayout) {
    if (isArray(_dwLayout[key])) {
      let arr = _dwLayout[key];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === funid) {
          if (isArray(data)) {
            arr[i].initParam = { fnlist: data };
          } else {
            let _cur = authStore.commonMenu.map(item => item.funid);
            console.log("_cur :>> ", _cur, _cur.includes(data.funid));
            let commonMenu = authStore.commonMenu;
            if (_cur.includes(data.funid)) {
              commonMenu = commonMenu.filter((itm: any) => itm.funid !== data.funid);
            } else {
              commonMenu.push(data);
            }
            console.log("commonMenu :>> ", commonMenu);
            arr[i].initParam = { fnlist: commonMenu };
          }
          console.log("arr[i].initParam.fnlist :>> ", arr[i].initParam.fnlist);
          authStore.setCommonMenu(arr[i].initParam.fnlist);
          break;
        }
      }
    }
  }
  _dwLayout.modifydate = formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss");
  console.log("_dwLayout :>> ", _dwLayout);
  console.log("authStore.commonMenu :>> ", authStore.commonMenu);
  // 保存布局
  await layoutLocalStore.setDwLayout(dwname, _dwLayout, t, empid);
};

const addMenuToHomeList = inject("addMenuToHomeList", ref<any>({}));
watch(
  () => addMenuToHomeList.value,
  async (newVal: Menu.MenuOptions) => {
    if (newVal && Object.keys(newVal).length) {
      console.log("initParam :>> ", initParam);
      console.log("addMenuToHomeList newVal :>> ", newVal);
      let item = {
        funid: newVal.name,
        icon: newVal.meta.icon,
        key: newVal.name,
        name: t(`menu.${newVal.name}`),
        path: newVal.path
      };
      await saveLayoutFunc("QuickEnter", item);
      iframeRefs["QuickEnterRef"].onRefresh();
    }
  },
  { immediate: true, deep: true }
);

/**
 * @description 回调事件集合
 */
const comEvent = {
  /**
   * @description 常用功能:保存
   */
  saveQuickEnter(funid: string, data: any, empid?: number) {
    // 保存常用功能
    let _data = cloneDeep(data);
    _data = _data.map(t => {
      t.funid = t.key;
      return t;
    });
    // 精简储存数据
    let layoutAttr = ["funid"];
    console.log("saveQuickEnter funid, data :>> ", funid, _data);
    let saveData = streamlineFunc(_data, layoutAttr, {});
    console.log("saveData :>> ", saveData);
    saveLayoutFunc(funid, saveData, empid);
  },
  /**
   * @description 常用功能:刷新,刷新本地缓存数据
   */
  async refreshQuickEnter(callback: any) {
    let layout: any = await layoutLocalStore.getDwLayout(dwname);
    console.log("layout :>> ", layout);
    let localLayout = {};
    if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
      typeof layout.itemvalue == "string" && (localLayout = JSON.parse(layout.itemvalue.replace(/'/g, '"')));
    }
    console.log("refreshLayout localLayout :>> ", localLayout);
    if (JSON.stringify(localLayout) != "{}") {
      let _layout = LayoutSettingRef.value?.setDefaultFunc(localLayout);
      let oObj: any = {};
      let oIdx = _layout.layoutLeft?.findIndex((item: any) => item.id == "QuickEnter");
      if (oIdx > -1) {
        oObj = _layout.layoutLeft[oIdx];
      } else {
        oIdx = _layout.layoutRight?.findIndex((item: any) => item.id == "QuickEnter");
        oObj = _layout.layoutRight[oIdx];
      }

      initParam["QuickEnter"] = cloneDeep(oObj?.initParam);
      console.log("refreshQuickEnter dwLayout.value :>> ", dwLayout.value);
      console.log("refreshQuickEnter initParam :>> ", initParam);

      ElMessage({
        message: t("sys.api.operationSuccess"),
        type: "success"
      });
    }
    // setTimeout(() => {
    callback && callback(initParam["QuickEnter"]);
    // }, 2000);
  },
  /**
   * @description 刷新首页布局,刷新本地缓存数据
   */
  async refreshLayout() {
    let layout: any = await layoutLocalStore.getDwLayout(dwname);
    console.log("layout :>> ", layout);
    let localLayout = {};
    if (layout?.hasOwnProperty("itemvalue") && layout.itemvalue) {
      typeof layout.itemvalue == "string" && (localLayout = JSON.parse(layout.itemvalue.replace(/'/g, '"')));
    }
    console.log("refreshLayout localLayout :>> ", localLayout);
    if (JSON.stringify(localLayout) != "{}") {
      dwLayout.value = LayoutSettingRef.value?.setDefaultFunc(localLayout);
      // dwLayout.value = localLayout;
      ElMessage({
        message: t("sys.api.operationSuccess"),
        type: "success"
      });
    }
  },
  /**
   * @description 点击采购明细,获取当前明细的发货单记录
   */
  saletaskTableCurrentChanged(data: any) {
    console.log("saletaskTableCurrentChanged data :>> ", data);
    let _target = "outwareOverviewRef";

    console.log("iframeRefs :>> ", iframeRefs);
    if (iframeRefs.hasOwnProperty(_target)) {
      iframeRefs[_target].onRefresh(
        {
          saletaskid: data.taskid,
          saletaskprintid: data.printid
        },
        data.mxcode
      );
    }
  },
  /**
   * @description 空,打开设置
   */
  emptyClick(id: string) {
    DragBallRef.value?.toShow();
    nextTick(() => {
      LayoutSettingRef.value?.handleSelFunc(id);
    });
  },
  /**
   * @description 获取公告栏信息
   * @param callback 回调函数
   */
  async getSysPostList(callback?: any) {
    // let data = await getSysPostData();
    // sysPostList.value = data.datatable ?? [];
    callback && callback();
  },
  /**
   * @description 发送公告栏
   */
  async sendSysPost() {
    alert("功能维护中,敬请期待!");
  }
};

const getSysPostData = () => {
  let newParams = {
    dsname: "L1WEB_GetSysPostList",
    queryParams: {
      scid: userInfo.scid,
      deptid: userInfo.deptid
    }
  };
  return CommonDynamicSelect(newParams);
};

/**
 * @description 点击设置按钮
 */
const OpenSettingHomeWidget = (callback: any) => {
  LayoutSettingRef.value?.show(callback);
};

/**
 * @description 保存首页布局
 */
const SaveSettingHomeWidget = (data: any, callback: any) => {
  data.modifydate = formatToDate(new Date(), "YYYY-MM-DD HH:mm:ss");
  let _layout = LayoutSettingRef.value?.omitFunc(data);
  console.log("SaveSettingHomeWidget dwLayout.value :>> ", dwLayout.value);
  console.log("dwLayout.value :>> ", _layout);
  // 保存布局
  layoutLocalStore.setDwLayout(dwname, _layout, t).then(() => {
    console.log("SaveSettingHomeWidget data :>> ", data);
    callback && callback();
    dwLayout.value = data;
  });
};

/**
 * @description 刷新相关组件
 */
const widgetGotoRefresh = () => {
  let _target = ["toOutStatisticRef", "saletaskMxStatisticRef", "saletaskMxRef", "outwareOverviewRef"];

  console.log("widgetGotoRefresh iframeRefs :>> ", iframeRefs);
  for (const key of _target) {
    if (iframeRefs.hasOwnProperty(key)) {
      if (key == "outwareOverviewRef") {
        iframeRefs[key].refreshOutwareFunc(false);
      } else {
        iframeRefs[key].onRefresh();
      }
    }
  }
};
provide("widgetGotoRefresh", widgetGotoRefresh);

const handleResetLayout = async () => {
  let layout = await layoutStore.getDwLayout_online(-1, dwname, 1);
  init(layout, true);
};

/**
 * @description 动态赋值布局右模块高度
 */
// const homeLayoutRightHeight = ref(0);
const rightLayoutStyle = ref({});
// 监听屏幕变化
const resize = (target: any) => {
  nextTick(() => {
    // homeLayoutRightHeight.value = document.getElementById("home-layout-left")?.offsetHeight ?? 0;
    // console.log("homeLayoutRightHeight.value :>> ", homeLayoutRightHeight.value);

    let _height = document.getElementById("home-layout-left")?.offsetHeight ?? 0;
    let key = "saletaskMx";
    let idx = target.layoutLeft?.findIndex((item: any) => item.id == key && item.heightType == "auto");
    if (idx == -1) {
      idx = target.layoutRight?.findIndex((item: any) => item.id == key && item.heightType == "auto");
    }
    console.log("idx :>> ", idx);
    if (idx > -1) {
      rightLayoutStyle.value = {
        height: _height + "px"
      };
    } else {
      rightLayoutStyle.value = {};
    }
  });
};
watch(
  dwLayout,
  val => {
    resize(val);
  },
  {}
);

onMounted(() => {
  resize(dwLayout.value);
  window.addEventListener("resize", resize);
});
onActivated(() => {
  resize(dwLayout.value);
  window.addEventListener("resize", resize);
});
onUnmounted(() => {
  window.removeEventListener("resize", resize);
});
onDeactivated(() => {
  window.removeEventListener("resize", resize);
});
</script>

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