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";
import piniaPersistConfig from "@/config/piniaPersist";

export const useLayoutLocalStore = defineStore({
  id: "longjoe-layout-local",
  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;
    },
    findUserLayout() {
      const { userInfo } = useUserStore();
      console.log("userInfo.userid :>> ", userInfo.empid);
      console.log("this.dwlayout :>> ", this.dwlayout);
      let dwIdx = this.dwlayout.findIndex(item => item.empid == userInfo.empid);
      console.log("dwIdx :>> ", dwIdx);
      let userLayout = { empid: userInfo.empid ?? 0, layoutList: <any>[] };
      if (dwIdx > -1) {
        userLayout = this.dwlayout[dwIdx];
        console.log("findUserLayoutuserLayout userLayout:>> ", userLayout);
      } else {
        this.dwlayout.push(userLayout);
        dwIdx = this.dwlayout.length - 1;
      }
      this.setUserIdx(dwIdx);
      console.log("findUserLayoutuserLayout :>> ", userLayout);
      return { layoutList: userLayout.layoutList };
    },
    // /**
    //  * @description 获取窗口布局
    //  * @return {Object} fx_user_dwlayout
    //  * */
    // getLocalDwLayout(dwname: string) {
    //   try {
    //     const { layoutList } = this.findUserLayout();
    //     const { userInfo } = useUserStore();
    //     console.log("userLayout userLayout:>> ", layoutList);
    //     let dwItem = layoutList.find((item: any) => item.itemname == dwname);
    //     console.log("dwItem :>> ", dwItem);
    //     if (dwItem) {
    //       return Promise.resolve(dwItem);
    //     }
    //     return this.getDwLayout(dwname);
    //   } catch (error) {
    //     ElMessage.error("获取布局失败：" + dwname);
    //   }
    // },
    /**
     * @description 获取窗口布局
     * @return {Object} fx_user_dwlayout
     * */
    async getDwLayout(dwname: string) {
      const { userInfo } = useUserStore();
      try {
        const { layoutList } = this.findUserLayout();
        let dwItem = layoutList.find((item: any) => item.itemname == dwname);
        console.log("dwItem :>> ", dwItem);
        if (dwItem) {
          return Promise.resolve(dwItem);
        }
        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, empid?: number) {
      try {
        const { layoutList } = this.findUserLayout();
        console.log("setDwLayout layoutList :>> ", layoutList);
        const { userInfo } = useUserStore();
        let layout = {
          empid: empid ?? userInfo.empid,
          dwname: import.meta.env.VITE_GLOB_PRODUCT_CODE,
          itemname: dwname,
          itemvalue: JSON.stringify(value),
          ifcompress: 0
        };
        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);

        console.log("setDwLayout  t :>>>>>>>>>>>>>>>>>>>>>", JSON.stringify(t));
        if (t) {
          ElMessage({
            message: t("sys.api.successToLayout"),
            type: "success"
          });
        }

        return Promise.resolve();
      } catch (error) {
        ElMessage.error("设置布局失败：" + dwname);
        return Promise.reject(error);
      }
    },
    /**
     * @description 快速获取页面布局参数
     * @argument string dwname 页面标识
     */
    async getLayoutAttr(dwname: string) {
      let layout = await this.getDwLayout(dwname);
      console.log("getLayoutStore layout :>> ", layout);
      let localLayout = {};
      if (layout?.itemvalue) {
        localLayout = JSON.parse(layout.itemvalue.replace(/'/g, '"'));
      }
      return localLayout;
    }
  },
  persist: piniaPersistConfig("longjoe-layout-local")
});
