import { City, ExtraUserInfo } from '@/types/app-type'
import { defineStore } from 'pinia'
import { ref } from 'vue'

const initState = {
  nickname: '',
  avatar: '',
  mobile: '',
  sex: 0,
  city: {
    allscore: 0,
    code: '0',
    isopen: 0,
    lizations: [],
    policy: 0,
    provincename: '',
    years: 0,
  },
  estimatedAchievement: {
    year: 0, // 学期
    expectedScore: '', // 成绩
    requireSubject: [],
    optionalSubject: [],
    provinceCode: '',

    className: null,
    createTime: '',
    createUserId: 0,
    createUserName: null,

    id: 0,
    init: false,
    isDelete: false,
    isUpdateScore: 0,
    isVIP: false,

    provinceName: '',
    rank: 0,
    schoolName: null,
    sp: 0,
    subjectGroup: '',
    updateTime: null,
    updateUserId: null,
    updateUserName: null,
    uuid: null,
    vipCode: null,
    wxId: 0,
  },
  userFilterParams: {
    phase: 0,
  },
  token: '',
  openid: '',
  zyBatches: {
    batchName: '',
    count: 0,
    itemCount: 0,
  },
  batchDataUrl: '',
  batchName: '',
  wishList: [],
  wishListId: '',
  isShowAi: true,
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<ExtraUserInfo>({ ...initState })

    // 设置用户信息
    const setUserInfo = (val: ExtraUserInfo) => {
      userInfo.value = val
    }

    // 设置用户所在城市
    const setUserCity = (val: City) => {
      userInfo.value.city = val
    }

    // 设置预估成绩
    const setEstimatedAchievement = (val: any) => {
      userInfo.value.estimatedAchievement = Object.assign(userInfo.value.estimatedAchievement, val)
    }

    // 设置用户token
    const setUserToken = (val: string) => {
      userInfo.value.token = val
    }

    const setUserOpenId = (val: string) => {
      userInfo.value.openid = val
    }

    const setUserNickName = (val: string) => {
      userInfo.value.nickname = val
    }

    const setUserAvatar = (val: string) => {
      userInfo.value.avatar = val
    }

    const setUserBaseInfo = ({ mobile, sex }: { mobile?: string; sex: number }) => {
      userInfo.value.sex = sex
      if (mobile) {
        userInfo.value.mobile = mobile
      }
    }

    // 清除预估成绩
    const clearUserEstimatedAchievement = () => {
      userInfo.value.estimatedAchievement = Object.assign(userInfo.value.estimatedAchievement, {
        year: 0, // 学期
        expectedScore: '', // 成绩
        requireSubject: [],
        optionalSubject: [],
        provinceCode: '',
        subjectGroup: '',
      })
    }

    const setZyBatches = (val: any) => {
      userInfo.value.zyBatches = val
    }

    const setBatchDataUrl = (val: string) => {
      userInfo.value.batchDataUrl = val
    }
    const setBatchName = (val: string) => {
      userInfo.value.batchName = val
    }

    const setWishListMajor = ({ val, uId }: { val: any; uId: string }) => {
      try {
        const targetItem = userInfo.value.wishList.find((item) => item.uId === uId)
        if (!targetItem) {
          console.error('未找到对应的志愿清单项')
          return
        }

        userInfo.value = {
          ...userInfo.value,
          wishList: userInfo.value.wishList.map((item) => {
            if (item.uId === uId) {
              return {
                ...item,
                vItems: [...item.vItems, { ...val, sort: item.vItems.length + 1 }],
              }
            }
            return item
          }),
        }
      } catch (error) {
        console.error('更新志愿清单失败:', error)
      }
    }

    const deleteWishListCollege = ({ uId }: { uId: string }) => {
      userInfo.value.wishList = userInfo.value.wishList.filter((item) => item.uId !== uId)
    }
    const deleteWishListMajor = ({ uId, planId }: { uId: string; planId: string }) => {
      userInfo.value.wishList = userInfo.value.wishList
        .map((item) => {
          if (item.uId === uId) {
            item.vItems = item.vItems.filter((vItem: any) => vItem.planId !== planId)
            return item
          }
          return item
        })
        .filter((item) => item.vItems.length > 0)
    }
    const setWishListMajorWithUn = (val: any) => {
      userInfo.value.wishList.push({ ...val, sort: userInfo.value.wishList.length + 1 })
    }
    // 排序专业
    const sortWishMajorList = ({ list, uIndex }: { list: any[]; uIndex: number }) => {
      userInfo.value.wishList[uIndex].vItems = [...list]
      if (userInfo.value.wishList[uIndex].vItems.length === 0) {
        userInfo.value.wishList.splice(uIndex, 1)
      }
    }

    // 排序大学
    const sortWishCollegeList = ({ list }: { list: any[] }) => {
      userInfo.value.wishList = list
    }

    // 清除志愿表
    const clearWishList = () => {
      userInfo.value.wishList = []
    }

    const setWishListId = ({ id }: { id: number }) => {
      userInfo.value.wishListId = id
    }

    const clearWishListId = () => {
      userInfo.value.wishListId = ''
    }

    const setIsVIP = (val: boolean) => {
      userInfo.value.estimatedAchievement.isVIP = val
    }

    const setVipCode = (val: string) => {
      userInfo.value.estimatedAchievement.vipCode = val
    }

    // 清除用户信息
    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const setIsShowAi = (val: boolean) => {
      userInfo.value.isShowAi = val
    }
    const isLoginFlag = computed(() => !!userInfo.value.token)

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLoginFlag,
      reset,
      setUserCity,
      setEstimatedAchievement,
      clearUserEstimatedAchievement,
      setUserToken,
      setUserOpenId,
      setUserNickName,
      setUserAvatar,
      setZyBatches,
      setBatchDataUrl,
      setBatchName,
      clearWishList,
      setWishListMajor,
      setWishListMajorWithUn,
      deleteWishListMajor,
      deleteWishListCollege,
      sortWishMajorList,
      sortWishCollegeList,
      setIsVIP,
      setVipCode,
      setIsShowAi,
      setUserBaseInfo,
      setWishListId,
      clearWishListId,
    }
  },
  {
    persist: true,
  },
)
