import { defineStore } from "pinia";
import { DwLayout } from "@/stores/interface";
import { DwLayout as userLayout } from "@/api/interface/index";
import { GetDwLyoutApi, SetDwLyoutApi } from "@/api/modules/common";
import { ElMessage } from "element-plus";
import { useUserStore } from "./user";

export const useLayoutStore = defineStore({
  id: "longjoe-layout",
  state: (): DwLayout.LayoutState => ({
    // 布局列表
    dwlayout: [],
    userIdx: 0
  }),
  getters: {
    // 布局列表
    dwlayoutGet: state => state.dwlayout
  },
  actions: {
    /**
     * 记录当前用户的布局数据
     * @param data 布局数组
     */
    setLayoutList(data: DwLayout.LayoutItem["layoutList"]) {
      this.dwlayout[this.userIdx].layoutList = data;
    },
    /**
     * 记录当前用户在dwlayout的索引值
     * @param idx 索引
     */
    setUserIdx(idx: DwLayout.LayoutState["userIdx"]) {
      this.userIdx = idx;
    },
    /**
     * @description 本地布局缓存列表
     */
    findUserLayout() {
      const { userInfo } = useUserStore();
      console.log("userInfo.userid :>> ", userInfo);
      console.log("this.dwlayout :>> ", this.dwlayout);
      let dwIdx = this.dwlayout.findIndex(item => item.empid == userInfo.empid && item.account == userInfo.account);
      console.log("dwIdx :>> ", dwIdx);
      let userLayout = { empid: userInfo.empid ?? 0, account: userInfo.account ?? "", layoutList: <any>[] };
      if (dwIdx > -1) {
        userLayout = this.dwlayout[dwIdx];
      } else {
        this.dwlayout.push(userLayout);
        dwIdx = this.dwlayout.length - 1;
      }
      this.setUserIdx(dwIdx);
      console.log("findUserLayoutuserLayout :>> ", userLayout);
      return { layoutList: userLayout.layoutList };
    },
    /**
     * @description 获取窗口布局
     * @param {string} dwname 布局名称
     * @param {boolean} autoDownload 是否自动获取布局信息
     * @param {number} ifdel 是否删除token.empid的布局信息
     * @return {Object} fx_user_dwlayout
     */
    async getDwLayout_online(empid: number, dwname: string, ifdel = 0) {
      let layout: userLayout.ReqSetDwLayout = {
        empid,
        dwname: import.meta.env.VITE_GLOB_PRODUCT_CODE,
        itemname: dwname,
        ifcompress: 0,
        ifdel: ifdel
      };
      let { itemvalue } = await GetDwLyoutApi(layout);
      console.log("getDwLayout layout :>> ", itemvalue);
      if (itemvalue) {
        layout.itemvalue = itemvalue;
        console.log("getDwLayout this.dwlayout :>> ", this.dwlayout);

        return Promise.resolve(layout);
      } else {
        return Promise.resolve({});
      }
    },
    /**
     * @description 获取窗口布局
     * @param {string} dwname 布局名称
     * @param {boolean} autoDownload 是否自动获取布局信息
     * @return {Object} fx_user_dwlayout
     * */
    async getDwLayout(dwname: string, autoDownload: boolean = true) {
      try {
        const { layoutList } = this.findUserLayout();
        const { userInfo } = useUserStore();
        console.log("userLayout userLayout:>> ", layoutList);
        let dwItem = layoutList.find((item: any) => item.itemname == dwname);
        console.log("getDwLayout dwItem :>> ", dwItem);
        if (dwItem) {
          return Promise.resolve(dwItem);
        }
        if (!autoDownload) return Promise.resolve({});

        let layout: userLayout.ReqSetDwLayout = {
          empid: userInfo.empid,
          dwname: import.meta.env.VITE_GLOB_PRODUCT_CODE,
          itemname: dwname,
          ifcompress: 0
        };
        let { itemvalue } = await GetDwLyoutApi(layout);
        console.log("getDwLayout layout :>> ", itemvalue);
        if (itemvalue) {
          layout.itemvalue = itemvalue;
          layoutList.push(layout);
          this.setLayoutList(layoutList);
          console.log("getDwLayout this.dwlayout :>> ", this.dwlayout);

          return Promise.resolve(layout);
        } else {
          return Promise.resolve({});
        }
      } catch (error) {
        ElMessage.error("获取布局失败：" + dwname);
      }
    },
    /**
     * @description 保存窗口布局
     * @return void
     * */
    async setDwLayout(dwname: string, value: any, t: any, autoUpload: boolean = true) {
      try {
        const { layoutList } = this.findUserLayout();
        const { userInfo } = useUserStore();
        let layout = {
          empid: userInfo.empid,
          dwname: import.meta.env.VITE_GLOB_PRODUCT_CODE,
          itemname: dwname,
          itemvalue: JSON.stringify(value),
          ifcompress: 0
        };
        autoUpload && (await SetDwLyoutApi(layout));
        let dwItemIdx = layoutList.findIndex((item: any) => item.itemname == dwname);
        if (dwItemIdx > -1) {
          layoutList.splice(dwItemIdx, 1);
        }
        layoutList.push(layout);
        this.setLayoutList(layoutList);

        autoUpload &&
          ElMessage({
            message: t("sys.api.operationSuccess"),
            type: "success"
          });
      } catch (error) {
        ElMessage.error("设置布局失败：" + dwname);
      }
    },
    /**
     * @description 获取窗口布局
     * @param {string} dwname 布局名称
     * @param {boolean} autoDownload 是否自动获取布局信息
     * @return {Object} fx_user_dwlayout
     */
    async saveDwLayout_online(empid: number, dwname: string, value: any) {
      try {
        let layout = {
          empid: empid,
          dwname: import.meta.env.VITE_GLOB_PRODUCT_CODE,
          itemname: dwname,
          itemvalue: JSON.stringify(value),
          ifcompress: 0
        };
        await SetDwLyoutApi(layout);
      } catch (error) {
        ElMessage.error("设置布局失败：" + dwname);
      }
    }
  }
  // persist: piniaPersistConfig("longjoe-layout")
});
