import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios';

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    //所有的任务列表
    list:[],
    inputValue:'aaa',
    nextID:5,
    viewstatus:'all'
  },
  getters: {
    //统计未完成条数的情况
    unDoneLength(state){
      return state.list.filter(v=>v.done === false).length
    },
    infolist(state){
      if(state.viewstatus === 'all'){
        return state.list
      }
      if(state.viewstatus === 'undone'){
        return state.list.filter(v=>!v.done)
      }
      if(state.viewstatus === 'done'){
        return state.list.filter(v=>v.done)
      }
      return state.list
    }
  },
  mutations: {
    initlist(state,list){
      //接收到action中getlist函数传过来额参数后，对state中的list直接进行赋值操作
      state.list = list
    },
    setInputValue(state,value){
      //为store中的InputValue赋值
      state.inputValue = value
    },
    addItem(state){
      //添加列表项
      const obj = {
        id:state.nextID,
        info:state.inputValue.trim(),
        done:false
      }
      state.list.push(obj)
      state.nextID++
      state.inputValue = ''
    },
    removeItem(state,id){
      //删除列表项
      //根据id查找对应项的索引
     const removeId =  state.list.findIndex(v=>v.id === id)
     if(removeId !== -1){
       state.list.splice(removeId,1)
     }
    },
    changeStatus(state,param){
      //修改列表项的选中状态
      const updateId =  state.list.findIndex(v=>v.id === param.id)
      if(updateId !== -1){
        state.list[updateId].done = param.done
      }
    },
    //清除已完成的任务
    cleanDone(state){
      state.list =  state.list.filter(v=>v.done === false)
    },
    //修改视图中的关键字
    changeviewstatus(state,status){
      state.viewstatus = status
    }
  },
  actions: {
    getlist(context){
      //发送请求请求list.json中的数据
      axios.get('/list.json')
      .then(res=>{
        console.log(res.data)
        //调用imutation中的initlist函数，并将res.date传给它
        context.commit('initlist',res.data)
      })
    }
  },
  modules: {
  }
})
