import {
  defineStore
} from "pinia";
import {
  autoLoginByCode,
  fetchUserInfo,
  fetchBabyInfo,
  fetchMemberInfo,
  fetchAutoPhone,
  fetchBabyInfoById,
  updateBabyInfo,
} from "../api/user.js";
import {
  useGlobalStore
} from "./global.js";
import {
  useHomeStore
} from "./home.js";
import md from "../md.js";

const globalStore = useGlobalStore();

export const useUserStore = defineStore("userInfo", {
  state: () => {
    return {
      userInfo: null,
      babyInfo: null,
      memberInfo: null,
      babyNickCache: [],
      cepingjieguoInfo: null,
    };
  },
  actions: {
    /**
     * 更新用户信息
     * @param {Object} userInfo
     */
    setUserInfo(userInfo) {
      this.userInfo = userInfo;
    },
    setMemberInfo(memberInfo) {
      this.memberInfo = memberInfo;
    },

    /**
     * 更新宝宝信息
     * @param {Object} babyInfo
     */
    setBabyInfo(babyInfo) {
      this.babyInfo = babyInfo;
    },

    async changeBabySelected(babyId) {
      // 更新选中状态

      const {
        data
      } = await fetchBabyInfoById(babyId);
      console.log("babyInfo", data);
      if (data?.memberId !== "not_login") {
        this.babyInfo = data;
      }
    },

    saveBabyInfo(babyInfo) {
      this.babyInfo.allBabyBaseInfo.push(babyInfo);
    },

    /**
     * 用户手机号验证的回调方法，用于获取encryptedData、iv、code，然后调用fetchAutoPhone接口完成手机号授权
     * @param {Object} data : {encryptedData, iv, code}
     * @returns
     */
    async phoneCallback(data, onOpenRegisterFn = () => { }) {
      uni.login({
        provider: "weixin",
        success: async (res) => {
          // console.log('wxAutoLogin', res);
          if (res.errMsg === "login:ok") {
            // 用户手机授权
            const {
              data: babyExistence
            } = await fetchAutoPhone({
              phoneEncryptedData: data.encryptedData,
              phoneIv: data.iv,
              code: data.code,
              codeLogin: res.code,
            });
            !babyExistence && onOpenRegisterFn && onOpenRegisterFn();

            const homeStore = useHomeStore();
            await homeStore.setBabyExistence(babyExistence);

            // 授权注册成功后做一次登录
            this.wxAutoLogin();
          } else {
            uni.showToast({
              title: res.errMsg,
              icon: "error",
            });
          }
        },
      });
    },

    /**
     * 获取用户信息
     */
    async loadUserInfo() {
      const {
        data
      } = await fetchUserInfo();
      console.log("userInfo", data);
      if (data?.memberId !== "not_login") {
        // 缓存用户memberId
        uni.setStorageSync('memberId', data?.memberId)
      }
        this.userInfo = data;
    },

    setBabyNickCache(id, name) {
      const findIndex = this.babyNickCache.findIndex((item) => item.id === id);
      console.log("this.babyNickCache", findIndex);
      if (findIndex > -1) {
        this.babyNickCache[findIndex].name = name;
      } else {
        this.babyNickCache.push({
          id,
          name
        });
      }
    },

    /**
     * 获取宝宝信息
     */
    // async loadBabyInfo() {
    //   const { data } = await fetchBabyInfo();
    //   console.log("babyInfo", data);
    //   if (data?.memberId !== "not_login") {
    //     this.babyInfo = data;
    //     console.log("this.11111", this.babyNickCache, data?.content?.id);

    //     const findItem = this.babyNickCache.find(
    //       (item) => item.id == data?.content?.id
    //     );
    //     if (data?.content?.id && findItem) {
    //       this.babyInfo.babyName = findItem.name;

    //       this.babyInfo.allBabyBaseInfo.forEach((item) => {
    //         if (item.id == data?.content?.id) {
    //           item.babyName = findItem.name;
    //         }
    //       });
    //     }
    //   }
    // },
    async loadBabyInfo(retryCount = 0) {
      const MAX_RETRIES = 3;
      const RETRY_DELAY = 1000; // 1 second

      try {
        const { data } = await fetchBabyInfo();
        console.log("babyInfo-宝宝信息", data);

        if (data?.memberId !== "not_login") {
          this.babyInfo = data;
          if (data.allBabyBaseInfo) {


            if (this.babyInfo.babyAge == "0月龄") {
              this.babyInfo.babyAge = "1月龄";
            }

            console.log("this.11111", this.babyNickCache, data?.content?.id);

            const findItem = this.babyNickCache.find(
              (item) => item.id == data?.content?.id
            );
            if (data?.content?.id && findItem) {
              this.babyInfo.babyName = findItem.name;

              this.babyInfo.allBabyBaseInfo.forEach((item) => {
                if (item.id == data?.content?.id) {
                  item.babyName = findItem.name;
                }
              });
            }
            return; // Success case, exit the function
          } else {
            console.log("this.babyInfo", '重新请求接口');
            if (retryCount < MAX_RETRIES - 1) {
              await new Promise(resolve => setTimeout(resolve, RETRY_DELAY));
              return this.loadBabyInfo(retryCount + 1);
            } else {
              console.log("Max retries reached, giving up");
              // Show user notification when max retries reached
              // uni.showToast({
              // 	title: "系统繁忙，请稍后再试",
              // 	icon: "none",
              // });
            }
          }
        }
      } catch (error) {
        console.log("🚀 ~ loadBabyInfo ~ error:", error);
        if (retryCount >= MAX_RETRIES - 1) {
          // Show user notification when max retries reached with error
          uni.showToast({
            title: "系统繁忙，请稍后再试",
            icon: "none",
          });
        }
      }
    },

    /**
     * 获取用户积分信息
     */
    async loadMemberInfo() {
      const {
        data
      } = await fetchMemberInfo();
      console.log("fetchMemberInfo=", data);
      this.setMemberInfo(data);
      //  this.memberInfo = data;
      //  if (data?.memberId !== "not_login") {
      //    this.babyInfo = data;
      //  }
    },
    /**
     * 获取宝宝信息
     */
    async loadHomeInfo() {
      const homeStore = useHomeStore();
      await homeStore.loadHomeInfo();
    },

    /**
     * wx.login 获取code后，调用此方法完成登录
     * @param {String} code
     */
    async autoLoginByCode(code) {
      const {
        data
      } = await autoLoginByCode(code);
      console.log("autoLoginByCode", data);
      // 如果登录成功，获取用户信息和宝宝信息，更新到state中，方便全局使用
      if (data && data.cuk) {
        globalStore.setCuk(data.cuk, data.openId, data.unionId);

        await this.loadUserInfo();
        await this.loadBabyInfo();
        await this.loadHomeInfo();
      }
    },

    /**
    * 用户自动登录
    */
    async wxAutoLogin(cb = null) {
      uni.login({
        provider: "weixin",
        success: async (res) => {
          console.log("wxAutoLogin", res);
          if (res.errMsg === "login:ok") {
            await this.autoLoginByCode(res.code);
            cb && cb();
          } else {
            uni.showToast({
              title: res.errMsg,
              icon: "error",
            });
          }

          md.sensors.init();
        },
      });
    },

    /**
     * 
     * @param {sy使用}  
     * @returns 
     */
    async syWxAutoLogin(cb = null) {
      uni.login({
        provider: "weixin",
        success: async (res) => {
          if (res.errMsg === "login:ok") {
            const { data } = await autoLoginByCode(res.code);
            // 如果登录成功，获取用户信息和宝宝信息，更新到state中，方便全局使用
            if (data && data.cuk) {
              globalStore.setCuk(data.cuk, data.openId, data.unionId);
              cb && cb();
            }
          } else {
            uni.showToast({
              title: res.errMsg,
              icon: "error",
            });
          }

          md.sensors.init();
        },
      });
    },

    async createBabyInfo(babyInfo) {
      console.log("createBabyInfo:", babyInfo);
      const res = await updateBabyInfo(babyInfo);
      if (res.success) {
        await this.loadBabyInfo();
        await this.loadUserInfo();
        await this.loadHomeInfo();
        return true;
      } else {
        return false;
      }
    },
  },
});