import Vue from 'vue'
import Vuex from 'vuex'
import { getMyButton, getFarm } from '../utils/api'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    color: '#31C3A6',
    mode: true,
    // 按钮权限
    buttons: [],
    ip: 'http://115.238.57.190:8100',
    // 所选择的farmId
    farmId: '',
    farmList: [],
  },
  mutations: {
    setColor(state, data) {
      state.color = data
    },
    setMode(state, data){
      state.mode = data
    },
    SET_BUTTONS(state, data) {
      state.buttons = data
    },
    SET_FARMID(state, data) {
      state.farmId = data;
    },
    SET_FARMLIST(state, data) {
      state.farmList = data;
    }
  },
  actions: {
    setModeAsync(context, data) {
      context.commit('setMode' ,data)
    },
    setColorAsync(context, data) {
      context.commit('setColor', data)
    },
    setFarmIdAsync(context,data) {
      context.commit('SET_FARMID', data)
    },
    // 获取用户按钮权限
    GetButtons({ commit }) {
      return new Promise((resolve, reject) => {
        getMyButton({userId: localStorage.getItem('UserId')}).then(res => {
          if(res.code === 10000) {
            commit('SET_BUTTONS', res.data)
            resolve(res.data)
          } else {
            reject(new Error(res.message))
          }
        }).catch(error => {
            reject(error)
          })
      })
    },
    // 获取牧场列表
    GetFarm({ commit }){
      return new Promise((resolve, reject) => {
        getFarm().then(res => {
          if (res.code === 10000) {
            commit('SET_FARMLIST', res.data);
            resolve(res.data);
          } else {
            reject(new Error(res.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  modules: {
  },
  getters: {
    buttons: state => state.buttons
  }
})
