import {createStore} from "vuex"
import localforage from "localforage"

export default createStore({
  state: {
    scores: {
      record: Number(localStorage.record || 0),
      current: 0,
    },

    //--
    user: {
      id: "",
      username: "",
      userkey: "",
      userlevel: 1,
      usertype: 0,
      role: [
        {
          name: "",
          headimg: "",
          level: "0",
          sex: "",
          job: "",
          part: "",
          hp: "",
          ht: "",
          skill: [
            {id: 1, name: "劈柴刀法", level: 0, levelName: "第一重", value: 0},
            {id: 1, name: "鸿毛刀法", level: 0, levelName: "第一重", value: 0},
            {id: 1, name: "电击劈", level: 0, levelName: "第一重", value: 0},
            {id: 1, name: "雷霆斩", level: 0, levelName: "第一重", value: 0},
            {id: 1, name: "断岳斩", level: 0, levelName: "第一重", value: 0},
          ],
          createtime: "",
          updatetime: "",
        }
      ]
    },
  },

  getters: {
    getScore: (state) => state.scores.current,
    getRecord: (state) => state.scores.record,

    //--
    getUser: (state) => state.user,
  },

  mutations: {
    SET_RECORD(state, score) {
      state.scores.record = score
    },

    ADD_SCORE(state, score) {
      state.scores.current += score
    },

    SET_SCORE(state, score) {
      state.scores.current = score
    },

    SAVE(state) {
      localStorage.record = state.scores.record
    },

    SET_USER(state, user) {
      state.user = user
    },
    SAVE_USER(state, user) {
      //localStorage.user = user
      localforage.setItem('user', JSON.stringify(state.user)).then(result => {
        //console.log(result)
      })
    },
    async GET_USER(state) {
      let user = await localforage.getItem('user');
      if (user)
        state.user = JSON.parse(user.toString());
      else {
        state.user = {}
        await localforage.setItem('user', JSON.stringify(state.user))
      }
      return state.user;
    },
  },

  actions: {
    addScore({state, commit}, score) {
      commit("ADD_SCORE", score)
      commit("SET_RECORD", Math.max(state.scores.record, state.scores.current))
      commit("SAVE")
    },

    setScore({commit}, score) {
      commit("SET_SCORE", score)
    },

    //--
    async getUser({commit}) {
      return commit("GET_USER")
    },
    setUser({commit}, user) {
      commit("SET_USER", user)
    },
    addUser({commit}, user) {
      commit("SET_USER", user)
      commit("SAVE_USER", user)
    },
  },
})
