import services from "@/services";
import Taro from "@tarojs/taro";
import { create } from "zustand";

interface GlobalStoreType {
  userInfo?: API.UserInfoRespDto["appUser"];
  updateUserInfo(): void;
  /** 项目配置 */
  projectConfig: any;
  /** 项目流程配置 */
  projectFlowConfig: any;
  queryProjectConfig(id: string): void;
  /** 是否认证 */
  isAuth: boolean;
  /** 主体信息 */
  mainBodyInfo?: any[];
  collectionInfo?: Record<string, any>;//收运公司信息
  queryMainBodyInfo(mobile?: string): void;
  /** 查询认证信息 */
  queryAuthenticationInfo(): void;
  upCollectionInfo(data: any): void;
}
const useGlobalStore = create<GlobalStoreType>((set) => ({
  userInfo: undefined,
  projectConfig: undefined,
  projectFlowConfig: undefined,
  isAuth: false,
  mainBodyInfo: undefined,
  collectionInfo: undefined,

  /** 更新用户信息 */
  updateUserInfo: () => {
    const token = Taro.getStorageSync("token");
    if (token) {
      services.login.getUserInfo().then((res) => {
        if (res.code === 200) {
          if (res.data.appUser.nickname !== null) {
            set(() => ({ userInfo: res.data.appUser }));
          } else {
            Taro.removeStorageSync("token");
          }
        }
      });
    }
  },

  /** 查询认证信息 */
  queryAuthenticationInfo() {
    services.login.queryAuthenticationInfo().then((res) => {
      if (res.code === 200) {
        set({ isAuth: true });
      }
    });
  },

  /** 查询主体信息 */
  queryMainBodyInfo(mobile?: string) {
    if (mobile && mobile.length > 0) {
      services.login.getMainBodyInfo(mobile ?? "").then((res) => {
        if (res.code === 200) {
          set({ mainBodyInfo: res.data });
        }
      });
    }
  },

  /** 查询项目配置 */
  queryProjectConfig(id: string) {
    services.approve.getTemplateConfig(id).then((res: any) => {
      if (res.code === 200) {
        services.approve
          .getApplicationNodeConfig(res.data.flowProcessId)
          .then((res1: any) => {
            if (res1.code === 200) {
              set({ projectConfig: res.data, projectFlowConfig: res1.data });
            }
          });
      }
    });
  },

  upCollectionInfo(data: any) {
    set({ collectionInfo: data });
  }

}));

export default useGlobalStore;
