import Vue from 'vue'
import Vuex from 'vuex'
import { normalCallPost } from './assets/utils';

Vue.use(Vuex)

let userData = {};
const now = new Date();

try {
  userData = JSON.parse(window.sessionStorage.userData || '{}');
} catch (error) {
  console.log('未从session中获取到userData')
}

function convertTreeToList(root, array) {
  if (!root || !root.length) return array;
  root.forEach(item => {
    let data = JSON.parse(JSON.stringify(item));
    const url = data.url ? data.url : (item.childList[0] ? (item.childList[0].url || '') : '');
    delete data.childList;
    array.push({
      name: data.name,
      path: data.url,
      id: data.id,
      parentId: data.parentId,
      icon: data.imgPath,
    });
    if (item.childList) {
      convertTreeToList(item.childList, array);
    }
  })
  return array;
}

function isPc() {
  var userAgentInfo = navigator.userAgent;
  var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
  var flag = true;
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
  }
  return flag;
}

// store.watch(function (state) {
//   return state.sessions
// }, function (val) {
//   console.log('CHANGE: ', val);
//   localStorage.setItem('vue-chat-session', JSON.stringify(val));
// }, {
//   deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
// })

export default new Vuex.Store({
  state: {
      //这里放全局参数
    isLogin: false,
    isMobile: !isPc(),
    userData,
    group: '',
    sessions: [{
      id: 1,
      user: {
        name: '示例介绍',
        img: '../src/assets/images/2.png'
      },
      messages: [{
        content: 'Hello，这是一个基于Vue + Vuex + Webpack构建的简单chat示例，聊天记录保存在localStorge, 有什么问题可以通过Github Issue问我。',
        date: now
      }, {
        content: '项目地址(原作者): https://github.com/coffcer/vue-chat',
        date: now
      }, {
        content: '本项目地址(重构): https://github.com/is-liyiwei',
        date: now
      }]
    }, {
      id: 2,
      user: {
        name: 'webpack',
        img: '../src/assets/images/3.jpg'
      },
      messages: [{
        content: 'Hi，我是webpack哦',
        date: now
      }]
    }],
    currentSessionId: 1,
    filterKey: ''
  },
  mutations: {
     //这里是set方法
    setUserData(state, data) {
      data.flat = convertTreeToList(data.barList, []);
      state.userData = Object.assign({}, state.userData, data);
      state.isLogin = true;
      window.sessionStorage.userData = JSON.stringify(data);
    },
    logout(state) {
      state.userData = {};
      state.isLogin = false;
      window.sessionStorage.userData = '';
    },
    setGroup(state, data) {
      state.group = data;
    },
    changeCurrentSessionId(state, id) {
      state.currentSessionId = id;
    },
    addMessage(state, msg) {
      state.sessions[state.currentSessionId - 1].messages.push({
        content: msg,
        date: new Date(),
        self: true
      })
    },
    INIT_DATA(state) {
      let data = localStorage.getItem('vue-chat-session');
      //console.log(data)
      if (data) {
        state.sessions = JSON.parse(data);
      }
    }
  },
  actions: {
    login({ commit }) {
      normalCallPost('/login/index').then(({ data }) => {
        commit('setUserData', data)
      }).catch(error => {

      })
    },
    logout({ commit }) {
      normalCallPost('/login/logout').then(data => { }).catch(error => { }).then(() => {
        commit('logout')
      })
    },
    initData(context) {
      context.commit('INIT_DATA')
    }
  }
})
