import { defineStore } from "pinia";
import { UserState, historyAccountProps } from "@/stores/interface";
import piniaPersistConfig from "@/config/piniaPersist";
import { Login } from "@/api/interface";
import { loginApi, logoutApi, getTokenApi, getL1APPUserInfoApi } from "@/api/modules/login";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { HOME_URL, LOGIN_URL, DEFAULT_FUNCIDS } from "@/config";
import { sysOptionEnumArray } from "@/enums/sysOptionEnum";
import router from "@/routers";
import i18n from "@/languages/index";
import { useLockStore } from "./lock";
import { ElNotification } from "element-plus";
import { getDiffToDate, setDateToDiff } from "@/utils";
import { cloneDeep } from "lodash-es";

export const useUserStore = defineStore({
  id: "longjoe-user",
  state: (): UserState => ({
    token: "",
    userInfo: { usercode: "", username: "" },
    queryHabit: [],
    accounts: [],
    historyAccount: [],
    currentAccount: "",
    statusname: "",
    woodcodename: "",
    pcodename: ""
  }),
  getters: {},
  actions: {
    // Set Token
    setToken(token: string) {
      this.token = token;
    },
    // Set setUserInfo
    setUserInfo(userInfo: UserState["userInfo"] | null) {
      if (userInfo) {
        this.userInfo = Object.assign(this.userInfo, userInfo);
        // this.statusname = userInfo?.statusname ?? "";
        // this.woodcodename = userInfo?.woodcodename ?? "";
        // this.pcodename = userInfo?.pcodename ?? "";
      } else {
        this.userInfo = {
          usercode: "",
          username: ""
        };
      }
    },
    // Set userqueryHabit
    setQueryHabit(queryHabit: UserState["queryHabit"] | null) {
      this.queryHabit = queryHabit || [];
    },
    setHistoryAccount(data: historyAccountProps) {
      console.log("data :>> ", data);
      console.log("setHistoryAccount this.historyAccount :>> ", this.historyAccount);
      this.delAccountFunc(data);
      this.historyAccount?.unshift(data);
    },
    setCurrentAcount(params: Login.ReqLoginForm) {
      // this.currentAccount = params.account;
      this.userInfo.usercode = params.usercode;
      // this.userInfo.account = params.account;
    },
    /**
     * @description: login
     */
    async login(params: Login.ReqLoginForm, callback?: any, refresh: boolean = true) {
      try {
        const lockStore = useLockStore();
        // 1.执行登录接口
        const data = await loginApi(params);
        // const data = await loginApiTest({ usercode: loginForm.username, psw: loginForm.password });
        console.log("data :>> ", data);
        this.setCurrentAcount(params);

        // 2.是否被锁，先解锁
        console.log("lockStore :>> ", lockStore);
        if (lockStore.lockInfo?.isLock) {
          this.setToken(data.token);
          return data;
        }

        this.setUserInfo(data);
        // this.userInfo.usercode = data.usercode;
        // this.userInfo.username = data.username;
        // this.userInfo.empid = data.empid;
        // this.userInfo.usermode = data.usermode;
        // if (!data.ifERPUser) {
        //   let _comInfo = {
        //     comid: data.comid,
        //     comname: data.comname,
        //     tele: data.comtele,
        //     address: data.address
        //   };
        //   this.setComInfo(_comInfo);
        // } else {
        // return Promise.resolve(data);
        // }
        this.setToken(data.token);

        if (callback) {
          console.time("login后，用时间");
          await callback();
          console.timeEnd("login后，用时间");

          if (refresh) {
            let res = await this.fnSuccessLogin();
            return Promise.resolve(res);
          } else {
            return Promise.resolve();
          }
        } else {
          if (refresh) {
            let res = await this.fnSuccessLogin();
            return Promise.resolve(res);
          } else {
            return Promise.resolve();
          }
        }
      } catch (error) {
        return Promise.reject(error);
      }
    },
    // async afterLoginAction(goHome?: boolean): Promise<GetUserInfoModel | null> {
    //   if (!this.getToken) return null;
    //   // get user info
    //   const userInfo = await this.getUserInfoAction();

    //   const sessionTimeout = this.sessionTimeout;
    //   if (sessionTimeout) {
    //     this.setSessionTimeout(false);
    //   } else {
    //     const permissionStore = usePermissionStore();
    //     if (!permissionStore.isDynamicAddedRoute) {
    //       const routes = await permissionStore.buildRoutesAction();
    //       routes.forEach((route) => {
    //         router.addRoute(route as unknown as RouteRecordRaw);
    //       });
    //       router.addRoute(PAGE_NOT_FOUND_ROUTE as unknown as RouteRecordRaw);
    //       permissionStore.setDynamicAddedRoute(true);
    //     }
    //     goHome && (await router.replace(userInfo?.homePath || PageEnum.BASE_HOME));
    //   }
    //   return userInfo;
    // },
    // async getUserInfoAction(): Promise<UserInfo | null> {
    //   if (!this.getToken) return null;
    //   const userInfo = await getUserInfo();
    //   const { roles = [] } = userInfo;
    //   if (isArray(roles)) {
    //     const roleList = roles.map((item) => item.value) as RoleEnum[];
    //     this.setRoleList(roleList);
    //   } else {
    //     userInfo.roles = [];
    //     this.setRoleList([]);
    //   }
    //   this.setUserInfo(userInfo);
    //   return userInfo;
    // },
    /**
     * @description: 成功登录后台记录与跳转
     */
    async fnSuccessLogin() {
      const tabsStore = useTabsStore();
      const keepAliveStore = useKeepAliveStore();

      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.closeMultipleTab();
      keepAliveStore.setKeepAliveName();

      // const userInfo = await getUserInfo();
      // const { roles = [] } = userInfo;
      // if (isArray(roles)) {
      //   const roleList = roles.map((item) => item.value) as RoleEnum[];
      //   this.setRoleList(roleList);
      // } else {
      //   userInfo.roles = [];
      //   this.setRoleList([]);
      // }

      // 4.跳转重定向或首页
      let goPath: string = (router.currentRoute.value.query?.redirect as string) ?? HOME_URL;
      goPath = goPath.replace(/\$and\$/g, "&");
      router.push(goPath);

      return this.userInfo;
    },
    /**
     * @description: logout
     */
    async logout(goLogin = false, callback?: Function) {
      // 1.执行退出登录接口
      // await logoutApi();

      // 2.重定向到登陆页
      goLogin && router.replace(LOGIN_URL);

      // 3.清除 Token
      this.setToken("");
      this.setUserInfo(null);
      callback && callback();
    },

    // /**
    //  * @description: Confirm before logging out
    //  */
    // confirmLoginOut() {
    //   const { createConfirm } = useMessage();
    //   const { t } = useI18n();
    //   createConfirm({
    //     iconType: 'warning',
    //     title: () => h('span', t('sys.app.logoutTip')),
    //     content: () => h('span', t('sys.app.logoutMessage')),
    //     onOk: async () => {
    //       await this.logout(true);
    //     },
    //   });
    // },
    /**
     * 获取用户搜索习惯
     * @param dwname 窗口名称
     */
    getQueryHabit(dwname: string) {
      console.log("getQueryHabit this.queryHabit :>> ", this.queryHabit);
      const dwQuety = this.queryHabit?.find(item => item.dwname == dwname);
      console.log("getQueryHabit dwQuety :>> ", dwQuety);
      if (dwQuety) {
        console.log("dwQuety.query :>> ", dwQuety.query);
        let _data = getDiffToDate(cloneDeep(dwQuety.query));
        console.log("dwQuety.query :>> ", _data);
        return _data;
      }
      return {};
    },
    setSearchQueryHabit(dwname: string, query: any) {
      console.log("setSearchQueryHabit this.queryHabit :>> ", this.queryHabit);
      const dwItemIdx = this.queryHabit?.findIndex((item: any) => item.dwname == dwname) ?? -1;
      console.log("getQueryHabit dwQuety :>> ", dwItemIdx);
      if (dwItemIdx > -1) {
        this.queryHabit?.splice(dwItemIdx, 1);
      }
      let obj = {
        dwname,
        query: setDateToDiff(query)
      };
      this.queryHabit?.push(obj);
      console.log("setSearchQueryHabit _habit :>> ", this.queryHabit);
      this.setQueryHabit(this.queryHabit);
    },
    /**
     * @description 获取账套信息
     */
    async getToken() {
      // this.accounts = [];
      const data = await getTokenApi();
      // this.accounts = data.accounts ?? [];
    },
    async getUserInfo() {
      console.time("getUserInfo，用时间");
      const data: any = await getL1APPUserInfoApi({ funids: DEFAULT_FUNCIDS, options: sysOptionEnumArray });
      console.log(" sysOptionEnumArray :>>>>>>>>>>>>>>>>>>>>>", sysOptionEnumArray);
      if (data.ErrMsg) {
        throw new Error(data.ErrMsg);
      }
      console.timeEnd("getUserInfo，用时间");
      this.setUserInfo(data);
    },
    /**
     * @description 删除历史登录账号信息
     */
    delAccountFunc(data: any) {
      if (this.historyAccount?.length) {
        let hasIndex = this.historyAccount.findIndex(
          item => item.usercode.toLocaleLowerCase() == data.usercode.toLocaleLowerCase()
        );
        console.log("hasIndex :>> ", hasIndex);
        if (hasIndex > -1) {
          this.historyAccount.splice(hasIndex, 1);
        }
      }
    }
  },
  persist: piniaPersistConfig("longjoe-user")
});
