/*
 * @Author: your name
 * @Date: 2022-01-04 15:14:05
 * @LastEditTime: 2022-01-06 14:03:03
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \goldenPig\src\store\index.js
 */
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://120.27.234.126:8010',
    // 所选择的farmId
    farmId: '',
    farmList: [],
    userName: '',
  },
  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;
    },
    SET_USERNAME(state, data) {
      state.userName = data;
    }
  },
  actions: {
    setModeAsync(context, data) {
      context.commit('setMode' ,data)
    },
    setColorAsync(context, data) {
      context.commit('setColor', data)
    },
    setFarmIdAsync(context,data) {
      context.commit('SET_FARMID', data)
    },
    setUserNameAsync(context, data) {
      context.commit('SET_USERNAME', 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 && res.code === 10000) {
            commit('SET_FARMLIST', res.data);
            resolve(res.data);
          } else {
            res && reject(new Error(res.message))
          }
        }).catch(error => {
          reject(error)
        })
      })
    }
  },
  modules: {
  },
  getters: {
    buttons: state => state.buttons
  }
})
