import {login, logout, getInfo, smsLogin, chungengUserLogin, chungengFarmerLogin} from '@/api/login';
import { registerOn } from "@/api/register";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getSystemAttachmentUrl } from '@/api/system/config'
import Cookies from "js-cookie";

const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    bookName: '',
    deptName:'',
    nickName: '',
    baseRoutingUrl: '',
    businessLevel: '',
    userId:null,
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_USERID: (state, userId) => {
      state.userId = userId
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    },
    SET_LOGINDEPTID: (state, loginDeptId) => {
      state.loginDeptId = loginDeptId
    },
    SET_LOGINBOOKID: (state, loginBookId) => {
      state.loginBookId = loginBookId
    },
    SET_DEPTNAME: (state, deptName) => {
      state.deptName = deptName
    },
    SET_BOOKNAME: (state, bookName) => {
      state.bookName = bookName
    },
    SET_NICKNAME: (state, nickName) => {
      state.nickName = nickName
    },
    SET_baseRoutingUrl: (state, baseRoutingUrl) => {
      state.baseRoutingUrl = baseRoutingUrl
    },
    SET_businessLevel: (state, businessLevel) => {
      state.businessLevel = businessLevel
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        login(username, password, code, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          getInfo(res.token).then(response => {
            const user = response.user
            console.info(user.nickName);
            //   const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
            const avatar = "";
            if (response.roles && response.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', response.roles)
              commit('SET_PERMISSIONS', response.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_BOOKNAME', user.bookName)
            commit('SET_NAME', user.userName)
            commit('SET_USERID', user.userId)
            commit('SET_LOGINDEPTID', user.loginDeptId)
            commit('SET_LOGINBOOKID', user.loginBookId)
            commit('SET_DEPTNAME', user.deptName)
            commit('SET_AVATAR', avatar)
            commit('SET_NICKNAME', user.nickName);
            commit('SET_businessLevel', user.businessLevel);
            //commit('SET_businessLevel', 'TEST');
            getSystemAttachmentUrl().then((resp) => {
              commit('SET_baseRoutingUrl', resp.msg);
            });
          })
          Cookies.set("_Login_url", window.location.href);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    //短信验证码登录
    SmsLogin({ commit }, userInfo) {
      const mobile = userInfo.mobile.trim()
      const smsCode = userInfo.smsCode
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        smsLogin(mobile, smsCode, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          Cookies.set("_Login_url", window.location.href);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    //注册
    Register({ commit }, userInfo) {
      const mobile = userInfo.mobile.trim()
      const smsCode = userInfo.smsCode
      const uuid = userInfo.uuid
      const memberName = userInfo.memberName
      const idcard = userInfo.idcard
      return new Promise((resolve, reject) => {
        registerOn(memberName, idcard, mobile, smsCode, uuid).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          Cookies.set("_Login_url", window.location.href);
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          const user = res.user
          //   const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
          const avatar = "";
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_BOOKNAME', user.bookName)
          commit('SET_NAME', user.userName)
          commit('SET_USERID', user.userId)
          commit('SET_LOGINDEPTID', user.loginDeptId)
          commit('SET_LOGINBOOKID', user.loginBookId)
          commit('SET_DEPTNAME', user.deptName)
          commit('SET_AVATAR', avatar)
          commit('SET_NICKNAME', user.nickName);
          commit('SET_businessLevel', user.businessLevel);
          //commit('SET_businessLevel', 'TEST');
          console.info(user.businessLevel);
          getSystemAttachmentUrl().then((resp) => {
            commit('SET_baseRoutingUrl', resp.msg);
          });
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_businessLevel', '')
          commit('SET_NICKNAME', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 更新用户信息

    // 春耕App用户登录
    ChungengLogin({ commit }, userInfo) {
      const code = userInfo.code;
      return new Promise((resolve, reject) => {
        chungengUserLogin(code).then(res => {
          setToken(res.token)
          commit('SET_TOKEN', res.token)
          getInfo(res.token).then(response => {
            const user = response.user;
            //   const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
            const avatar = "";
            if (response.roles && response.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', response.roles)
              commit('SET_PERMISSIONS', response.permissions)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_BOOKNAME', user.bookName)
            commit('SET_NAME', user.userName)
            commit('SET_USERID', user.userId)
            commit('SET_LOGINDEPTID', user.loginDeptId)
            commit('SET_LOGINBOOKID', user.loginBookId)
            commit('SET_DEPTNAME', user.deptName)
            commit('SET_AVATAR', avatar)
            commit('SET_NICKNAME', user.nickName);
            commit('SET_businessLevel', user.businessLevel);
            //commit('SET_businessLevel', 'TEST');
            getSystemAttachmentUrl().then((resp) => {
              commit('SET_baseRoutingUrl', resp.msg);
            });
          })
          Cookies.set("_Login_url", window.location.href);
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 春耕App用户登录
    ChungengFarmerLogin({ commit }, userInfo) {
      const code = userInfo.code;
      return new Promise((resolve, reject) => {
        chungengFarmerLogin(code).then(res => {
          Cookies.set("user", res.data, { expires: 30 });
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    },
  }
}

export default user
