import {
  http
} from '@/utils/request'

const TOKEN = 'app_token'
// const USER = 'app_user'
// const NEWSNUM='app_news_num'
const HISTORY = "app_history"
const ALLACCOUNTS = "app_accounts"
const getDefaultState = () => {
  return {
    token: uni.getStorageSync(TOKEN),
    // token: '1104|nAMfPQH3HTnb4Y6p06mgIbPjPNC9Hqb24sbglwfQ',
    user: null, //用户信息
    news_num: 0, //消息数
    order_count: null, //订单数量
    history: uni.getStorageSync(HISTORY) || [], //历史搜索
    allaccounts: uni.getStorageSync(ALLACCOUNTS) || [], //所有账号
  }
}


const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  async LOGIN(state, value) {
    await this.commit('user/SET_TOKEN', value)
    await this.dispatch('user/getUserInfo', false)
  },
  LOGOUT() {
    return this.dispatch('user/resetToken')
  },
  // 登录
  async SET_TOKEN(state, value) {
    state.token = value
    await uni.setStorageSync(TOKEN, value);
  },
  //获取用户信息
  SET_USERINFO(state, value) {
    state.user = value
    // uni.setStorageSync(USER, value);
  },
  //获取消息未读数
  SET_NEWS(state, value) {
    state.news_num = value
    // uni.setStorageSync(NEWSNUM, value);
  },
  //添加历史记录
  SET_HISTORY(state, value) {
    if (state.history.length == 0) {
      state.history.unshift(value)
    } else {
      let Index = state.history.findIndex(item => {
        return item == value
      })
      if (Index == -1) {
        state.history.unshift(value)
      }
    }
    uni.setStorageSync(HISTORY, state.history);
  },
  //删除历史记录
  DEL_HISTORY(state) {
    uni.removeStorageSync(HISTORY);
    state.history = []
  },
  //保存所有账号
  SET_ACCOUNTS(state, value) {
    state.allaccounts = value
    uni.setStorageSync(ALLACCOUNTS, value);
  },
  //修改资料后改变用户信息
  SET_REFRESH(state, value) {
    let Index = state.allaccounts.findIndex(item => {
      return item.phone == value.phone
    })
    if (Index != -1) {
      state.allaccounts[Index].phone = value.phone
      state.allaccounts[Index].avatar = value.avatar
      state.allaccounts[Index].nickname = value.nickname
      uni.setStorageSync(ALLACCOUNTS, state.allaccounts);
    }
  },
  // //删除账号
  // DEL_ACCOUNTS(state, value) {
  //   let Index = state.allaccounts.findIndex(item => { return item.phone == value })
  //   state.allaccounts.splice(Index, 1)
  //   uni.setStorageSync(ALLACCOUNTS, state.allaccounts);
  // },
  //获取订单数量
  SET_ORDERNUM(state, value) {
    state.order_count = value
  }
}

const actions = {
  //登录
  async login({
    commit,
    state,
    dispatch
  }, {
    form,
    switchAllaccounts
  }) {
    return new Promise((resolve, reject) => {

      http.post('/v1/login', form, {
        custom: {
          loading: true
        }
      }).then(({
        token
      }) => {
        if (switchAllaccounts && state.allaccounts.length == 0) {
          const tempUserInfo = {
            ...Object.assign({}, state.user),
            token: state.token,
          }
          dispatch('getAccounts', {
            info: tempUserInfo,
            switchAllaccounts
          })
        }
        resolve(token)
        commit('SET_TOKEN', token)
        dispatch('getUserInfo', switchAllaccounts)
        dispatch('getNewsNum')
      }).catch(err => {
        reject(err)
      });

    })
  },
  //退出登录
  async logout({
    commit
  }) {
    /* #ifdef MP-WEIXIN */
    //await http.post('/v1/socialite/unbind-user/wechat-mini')
    /* #endif */
    return new Promise((resolve, reject) => {
      http.post('/v1/logout', {}, {
        custom: {
          loading: true
        }
      }).then(() => {
        // console.log(token)
        uni.removeStorageSync(TOKEN);
        commit('SET_TOKEN')
        commit('SET_USERINFO', {})
        commit('SET_NEWS', 0)
        resolve()
      }).catch(err => {
        reject(err)
      });
    })
  },

  //获取用户信息
  getUserInfo({
    commit,
    state,
    dispatch
  }, switchAllaccounts) {

    return new Promise((resolve, reject) => {
      if (!state.token) return
      http.get('/v1/me', {}, {
        custom: {
          silence: true
        }
      }).then(({
        phone,
        user_info,
        is_vip,
        wallet,
        balance,
        vip_expired
      }) => {
        let user = user_info
        user.phone = phone
        user.is_vip = is_vip
        user.wallet = wallet
        user.balance = balance
        user.vip_expired = vip_expired
        commit('SET_USERINFO', user)
        dispatch('bindCid')
        dispatch('getAccounts', {
          info: {
            ...user,
            token: state.token
          },
          switchAllaccounts
        })
        resolve(user)
      }).catch(err => {
        reject(err)
      })
    })
  },

  getAccounts({
    commit,
    state
  }, {
    info,
    switchAllaccounts = false
  }) {

    const obj = {
      avatar: info.avatar,
      birthday: info.birthday,
      code: info.code,
      gender: info.gender,
      nickname: info.nickname,
      phone: info.phone,
      token: info.token,
    }
    let all = state.allaccounts
    const index = all.findIndex(e => e.phone == obj.phone)
    if (index >= 0) all[index] = Object.assign({}, state.allaccounts[index], obj)
    else {
      if (switchAllaccounts) all = [...all, obj]
    }
    commit('SET_ACCOUNTS', all)
  },
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      uni.removeStorageSync(TOKEN);
      commit('RESET_STATE')
      resolve()
    })
  },
  bindCid() {
    // #ifdef APP-PLUS
    const cid = plus.push.getClientInfo()?.clientid
    http.post('/v1/push-bind-uni', {
      cid
    }, {
      custom: {
        toast: false
      }
    })
    // #endif
  },

  //异步获取消息未读数
  getNewsNum({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      if (!state.token) return
      http.get('/v1/messages/wait-read-num', {}, {
        custom: {
          silence: true
        }
      }).then(({
        num
      }) => {
        commit('SET_NEWS', num)
        resolve(num)
      }).catch(err => {
        reject(err)
      })
    })
  },
  //获取订单数量
  getOrderNum({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      if (!state.token) return
      http.get('/v1/order/statistics').then(res => {
        commit('SET_ORDERNUM', res)
      }).catch(err => {
        reject(err)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
