import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getUserDetailApi, updateUserApi, getUserListApi } from '@/service/user'
import { useAppStore } from '@/store/app'
import type { UserType } from '@/types/user'
import { until } from '@vueuse/core'

const initState = {
  nickName: '',
  gender: 0,
  language: '',
  city: '',
  province: '',
  country: '',
  avatarUrl: '',
  is_demote: true,
}

export const useUserStore = defineStore(
  'user',
  () => {
    const userInfo = ref<IUserInfo>({ ...initState }) // 登录用户信息（微信小程序）
    const userDetail = ref<UserType>({} as UserType) // 用户详细信息（系统）
    // 是否已完善资料 （身份证或统一社会信用代码是否为空）
    const isAuthComplete = computed(() => {
      if (!userDetail.value.userstype) return false
      if (userDetail.value.userstype === '个人') {
        return !!userDetail.value.usersidcardnumber
      } else {
        return !!userDetail.value.usersshtyxydm
      }
    })

    const setUserInfo = (val: IUserInfo) => {
      userInfo.value = val
    }

    const clearUserInfo = () => {
      userInfo.value = { ...initState }
    }
    // 一般没有reset需求，不需要的可以删除
    const reset = () => {
      userInfo.value = { ...initState }
    }

    const getUserInfo = async () => {
      const appStore = useAppStore()
      return getUserDetailApi(appStore.appInfo.userid)
    }

    const setUserDetail = (val: UserType) => {
      userDetail.value = val
    }

    const updateUser = async (data: Partial<UserType> & { usersid: string }) => {
      const { Data, Message, Status } = await updateUserApi(data)

      if (Status === 0) {
        // 更新用户信息
        userDetail.value = Object.assign(userDetail.value, data)
      }
      return { Data, Message, Status }
    }

    // 获取销售网点列表
    const getSellUserList = async () => {
      const { data: userList, loading } = useRequest(
        () => getUserListApi({ usersnature: '渠道' }, { pageindex: 1, rows: 999 }),
        {
          immediate: true,
        },
      )

      await until(loading).toBe(false)

      return userList.value.Data
    }

    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      reset,
      getUserInfo,
      userDetail,
      setUserDetail,
      isAuthComplete,
      updateUser,
      getSellUserList,
    }
  },
  {
    persist: true,
  },
)
