import { defineStore } from 'pinia';
import { useTransferPage } from '@/hooks/useTransferPage';
import { ref, computed } from 'vue';
import { getUserInfo, logoutPhysical } from '@/api/modules/login';
import config from '@/config';

import { Study, UserStoreState } from '@/types';
import { UserInfo, VipCardInfo } from '@/types/user';
import tools from '@/utils/uni-tool';
import defaultAvatar from '@/static/personal/avatar_default.png'

// @ts-ignore
// import { useUserStore as useOldUserStore } from '@/hooks/useUserStore';
import { CardType, EnumExamType, EnumReviewMode, EnumUserType } from '@/common/enum';
import { OPEN_VIP_POPUP } from '@/types/injectionSymbols';
import { getDirectedSchool, saveDirectedSchool } from '@/api/modules/study';
// const oldUserStore = useOldUserStore()
const themeColor = '#31A0FC';
type CheckLoginOptions = {
  askToLogin?: boolean;
}

export const useUserStore = defineStore('ie-user', {
  state: (): UserStoreState => ({
    accessToken: null,
    user: null,
    card: null,
    isDefaultModifyPwd: false,
    isPasswordExpired: false,
    isExamGuideShow: false,
    tempInfo: {
      location: '',
      examType: undefined,
    },
    org: {
      ...config.defaultOrg,
    },
    rememberPwd: false,
    cardPassword: '',
    cardNo: '',
    directedSchoolList: [],
    practiceSettings: {
      reviewMode: EnumReviewMode.AFTER_SUBMIT,
      autoNext: false
    }
  }),
  getters: {
    isLogin(state: UserStoreState): boolean {
      return !!state.accessToken && state.user !== null && Object.keys(state.user).length > 0;
    },
    userInfo(state: UserStoreState): UserInfo {
      return state.user || {} as UserInfo;
    },
    avatar(state: UserStoreState): string {
      return this.userInfo.avatar || defaultAvatar
    },
    nickName(state: UserStoreState): string {
      return this.userInfo.nickName || '游客'
    },
    anonymousPhoneNumber(state: UserStoreState): string {
      if (this.userInfo.phonenumber && this.userInfo.phonenumber.length === 11) {
        return this.userInfo.phonenumber.slice(0, 3) + '****' + this.userInfo.phonenumber.slice(7)
      }
      return '';
    },
    isVip(): boolean {
      if (!this.card) {
        return false;
      }
      const { outDate } = this.card;
      return !!this.userInfo.cardId && new Date(outDate) > new Date();
    },
    isExperienceVip(): boolean {
      if (!this.card) {
        return false;
      }
      const { outDate } = this.card;
      return this.card?.type === CardType.EXPERIENCE && new Date(outDate) > new Date();
    },
    vipInfo(state: UserStoreState): VipCardInfo {
      if (state.card) {
        return state.card;
      }
      return {} as VipCardInfo;
    },
    orgInfo(state: UserStoreState) {
      return state.org;
    },
    isStudent(): boolean {
      return this.userInfo.userType === EnumUserType.STUDENT;
    },
    isTeacher(): boolean {
      return this.userInfo.userType === EnumUserType.TEACHER;
    },
    isAgent(): boolean {
      return this.userInfo.userType === EnumUserType.AGENT;
    },
    isAuditor(): boolean {
      return false;
      return this.userInfo.accountType === 2;
    },
    hasDirectedSchool(): boolean {
      return this.directedSchoolList.length > 0;
    },
    hasTestAndRecord(): boolean {
      // 职高对口升学 目前不支持测评
      return this.getExamType != EnumExamType.VHS;
    },
    /**
     * 需要完成信息完善的用户类型
     * @returns 
     */
    needCompleteInfo(): boolean {
      return this.isTeacher || this.isAgent;
    },
    // 兼容游客时显示
    getLocation(): string {
      if (this.isLogin) {
        return this.user?.location || '';
      }
      return this.tempInfo?.location || '';
    },
    getExamType(): string {
      if (this.isLogin) {
        return this.user?.examType || '';
      }
      return this.tempInfo?.examType || '';
    },
    isHN(): boolean {
      return this.getLocation == '湖南'
    },
    isVHS(): boolean {
      return this.getExamType === EnumExamType.VHS;
    }
  },
  actions: {
    setToken(token: string) {
      this.accessToken = token;
    },
    async login(token: string) {
      try {
        this.accessToken = token;
        // await oldUserStore.SyncToken(token);
        const userInfo = await this.getUserInfo();;
        return Promise.resolve({
          success: true,
          userInfo: userInfo
        });
      } catch (error) {
        return Promise.resolve({
          success: false,
          userInfo: null
        });
      }
    },
    checkLogin({ askToLogin = true }: CheckLoginOptions = {}): Promise<boolean> {
      if (this.isLogin) {
        return Promise.resolve(true);
      }
      const { transferTo } = useTransferPage();
      return new Promise((resolve, reject) => {
        if (askToLogin) {
          tools.showModal({
            title: '提示',
            content: '当前未登录，是否前往登录？',
            confirmColor: themeColor
          }).then(confirm => {
            if (confirm) {
              transferTo('/pagesSystem/pages/login/login').then((res) => {
                resolve(res as boolean);
              }).catch(() => {
                resolve(false);
              });
            }
          });
        } else {
          transferTo('/pagesSystem/pages/login/login').then((res) => {
            resolve(res as boolean);
          }).catch(() => {
            resolve(false);
          });
        }
      });
    },
    checkVip() {
      return new Promise((resolve, reject) => {
        if (!this.isVip) {
          resolve(false);
        }
        resolve(true);
      });
    },
    checkInfoComplete() {
      return new Promise((resolve, reject) => {
        if (this.needCompleteInfo && (!this.userInfo.location || !this.userInfo.examType || !this.userInfo.endYear)) {
          const { transferTo } = useTransferPage();
          transferTo('/pagesSystem/pages/bind-teacher-profile/bind-teacher-profile').then(res => {
            resolve(res as boolean);
          }).catch(() => {
            resolve(false);
          });
        } else {
          resolve(true);
        }
      });
    },
    async getUserInfo() {
      const res = await getUserInfo();
      const { data, isDefaultModifyPwd, isPasswordExpired, card, org } = res;
      if (data) {
        this.user = data;
        if (card) {
          this.card = card;
        }
        this.isDefaultModifyPwd = isDefaultModifyPwd;
        this.isPasswordExpired = isPasswordExpired;
      }
      if (org) {
        this.org = org;
      }
      return data;
    },
    /**
     * 保存定向学校列表
     * @param list 定向学校列表
     */
    async saveDirectedSchoolList(list: Study.DirectedSchool[]) {
      await saveDirectedSchool(list);
      await this.getDirectedSchoolList();
    },
    /**
     * 获取定向学校列表
     */
    async getDirectedSchoolList() {
      const { data } = await getDirectedSchool();
      this.directedSchoolList = data || [];
    },
    setPracticeSettings(settings: Study.PracticeSettings) {
      this.practiceSettings = settings;
    },
    askLogout() {
      return new Promise((resolve, reject) => {
        uni.$ie.showModal({
          title: '提示',
          content: '确定退出登录吗？',
          confirmColor: themeColor
        }).then(confirm => {
          if (confirm) {
            this.logout();
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    rememberLoginInfo(remember: boolean, cardNo: string, cardPassword: string) {
      this.rememberPwd = remember;
      if (remember) {
        this.cardNo = cardNo;
        this.cardPassword = cardPassword;
      } else {
        this.cardNo = '';
        this.cardPassword = '';
      }
    },
    logout() {
      this.accessToken = null;
      this.user = null;
      this.isDefaultModifyPwd = false;
      this.isPasswordExpired = false;
      this.org = {
        ...config.defaultOrg,
      };
      const { transferTo } = useTransferPage();
      setTimeout(() => {
        transferTo('/pagesMain/pages/index/index', {
          type: 'reLaunch'
        })
      }, 300);
    },
    deleteAccount() {
      uni.$ie.showLoading('注销中...');
      logoutPhysical().then(() => {
        this.logout();
      }).finally(() => {
        uni.$ie.hideLoading();
      });
    },
    /**
     * 拨打客服电话
     * @returns 
     */
    callContactPhone() {
      if (!this.orgInfo.contactPhone) {
        uni.$ie.showToast('暂无客服电话');
        return;
      }
      uni.showActionSheet({
        title: '客服电话',
        itemList: [`拨打电话：${this.orgInfo.contactPhone}`],
        success: (res) => {
          uni.makePhoneCall({
            phoneNumber: this.orgInfo.contactPhone
          });
        }
      });
    }
  },
  persist: {
    storage: {
      getItem: uni.getStorageSync,
      setItem: uni.setStorageSync,
    }
  }
});