import {get_info, get_point_types, get_employee_map,getMenu} from '@/api/login'
import {setToken, setUserId, getToken} from '@/utils/auth'
import moment from 'moment'
import router from '@/router'

const user = {
  state: {
    token: '',
    user_info: {},
    account_info: {},
    user_id: 0,
    tabbar_selected: 'tab1',
    cart_checkout_ids: [],
    cart_count: 0,
    point_types: [],
    msg_count: 0,
    network_status:0,
    addressinfo: {
      name: '',
      tel: '',
      id: 0,
      address: ''
    },
    employee_map: {},
    getMenu:{},
    buyPopup:false,
  },

  mutations: {
    BUYPOPUP:(state, data)=>{
      // console.log(data);
      state.buyPopup = data
    },
    GET_MENU:(state, data) => {
      state.getMenu = data
    },
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    RESET: (state, token) => {

    },
    SET_USERID: (state, user_id) => {
      state.user_id = user_id
    },
    SET_HOME_TAB: (state, tab) => {
      state.tabbar_selected = tab
    },
    SET_USERINFO: (state, data) => {
      if (window.plus) {
        plus.storage.setItem('user_info', JSON.stringify({data:data}))
      } else {
        localStorage.setItem('user_info', JSON.stringify({data:data}))
      }
      state.user_info = data
    },
    SET_ACCOUNTINFO: (state, data) => {
      state.account_info = data
    },
    SET_CART_COUNT: (state, data) => {
      state.cart_count = data
    },
    SET_CHECKOUT_IDS: (state, data) => {
      state.cart_checkout_ids = data
    },
    SET_ADDRESSINFO: (state, data) => {
      state.addressinfo = data
    },
    SET_EMPLOYEE_MAP: (state, data) => {
      state.employee_map = data
    },
    SET_NETWORK_STATUS: (state, data) => {
      state.network_status = data
    },
    SET_POINT_TYPES: (state, data) => {
      state.point_types = data
    },
  },

  actions: {
    setBuyPopup({commit},data){
      commit('BUYPOPUP',data);
    },
    // 获取菜单
    getMenu({commit}){
        return new Promise((resolve, reject) => {
            getMenu().then(response => {
             var menu_common=response.data.data.menu_common;
             var menu=response.data.data.menu;
             var men=JSON.parse(window.plus? plus.storage.getItem('menuCommon'):localStorage.getItem("menuCommon")); //缓存的menuCommon
             var local_menu=JSON.parse(window.plus? plus.storage.getItem('menu'):localStorage.getItem("menu")); //缓存的ment
             var isXd=true;
             if(men && local_menu){
               // for(let i=0;i<menu_common.length;i++){
               //    if(menu_common[i]!=men[i]){
               //      isXd=false
               //    }
               // }
               // 判断考勤模块的下载压缩包地址
               // for(let i=0;i<menu.length;i++){
               //    if(menu[i].code_id=="attendance_manage"){
               //        for(let j=0;j<menu[i].child.length;j++){
               //            if(menu[i].child[j].download_url!=local_menu[i].child[j].download_url){
                            isXd=false
               //            }
               //        }

               //     }
               // }
               if(isXd){
                  resolve(true)
               }else{
                 if (window.plus) {
                   plus.storage.setItem('menu', JSON.stringify(response.data.data.menu))
                   plus.storage.setItem('menuCommon', JSON.stringify(response.data.data.menu_common))
                 } else {
                   localStorage.setItem('menu', JSON.stringify(response.data.data.menu))
                   localStorage.setItem('menuCommon', JSON.stringify(response.data.data.menu_common))
                 }
                 resolve(true);
               }
             }else{
               if (window.plus) {
                 plus.storage.setItem('menu', JSON.stringify(response.data.data.menu))
                 plus.storage.setItem('menuCommon', JSON.stringify(response.data.data.menu_common))
               } else {
                 localStorage.setItem('menu', JSON.stringify(response.data.data.menu))
                 localStorage.setItem('menuCommon', JSON.stringify(response.data.data.menu_common))
               }
               resolve(true);
             }
            }).catch(error => {
              reject(error)
            })
        })
    },
    clear_cache({dispatch,commit}){
       commit('SET_USERINFO','');
      if(window.plus){
        plus.storage.removeItem('SET_EMPLOYEE_MAP')
        plus.storage.removeItem('message_cate_list')
        plus.storage.removeItem('SET_POINT_TYPES')
        plus.storage.removeItem('user_info')
        plus.storage.removeItem('account_info')
        plus.storage.removeItem('buyPopupPage')
        plus.storage.removeItem('buyPopup')
        plus.storage.removeItem('last_click_pos')
        plus.storage.removeItem('token-expire')
        plus.storage.removeItem('loglevel:webpack-dev-server')
        plus.storage.removeItem('menu')
        plus.storage.removeItem('menuCommon')
      }else{
        localStorage.removeItem('SET_EMPLOYEE_MAP')
        localStorage.removeItem('message_cate_list')
        localStorage.removeItem('SET_POINT_TYPES')
        localStorage.removeItem('user_info')
        localStorage.removeItem('account_info')
        localStorage.removeItem('buyPopupPage')
        localStorage.removeItem('buyPopup')
        localStorage.removeItem('last_click_pos')
        localStorage.removeItem('token-expire')
        localStorage.removeItem('loglevel:webpack-dev-server')
        localStorage.removeItem('menu')
        localStorage.removeItem('menuCommon')
      }
      if(window.plus){
        plus.io.requestFileSystem( plus.io.PRIVATE_DOC, function(fs){
          var directoryReader = fs.root.createReader();
          directoryReader.readEntries( function( entries ){
            var i;
            for( i=0; i < entries.length; i++ ) {
              entries[i].removeRecursively( function ( entry ) {
              }, function ( e ) {
                alert( e.message );
              } );
            }
          }, function ( e ) {
            alert( "Read entries failed: " + e.message );
          } );
        } );
      }
    },
    update_user_info({dispatch,commit},data){
          dispatch('get_user_info', getToken());
    },
    update_point_types({dispatch}){
      if(window.plus){
        plus.storage.removeItem('SET_POINT_TYPES')
      }else{
        localStorage.removeItem('SET_POINT_TYPES')
      }
      dispatch('get_point_types')
    },
    update_employee_map({dispatch}){
      if(window.plus){
        plus.storage.removeItem('SET_EMPLOYEE_MAP')
      }else{
        localStorage.removeItem('SET_EMPLOYEE_MAP')
      }
      dispatch('get_employee_map')
    },

    get_employee_map({commit},is){
      return new Promise((resolve, reject) => {
        let employee_map = null
        let oneId = null
        let nowDate = moment().format("YYYY-MM-DD HH:mm:ss")
        if(window.plus){
          employee_map = JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP'))
        }else{
          employee_map = JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
        }
        if (employee_map) {
          for (const key in employee_map) {
            if (employee_map.hasOwnProperty(key) && employee_map[key].localStorageExpire) {
              oneId = employee_map[key].id
            }
          }
        }
        if(!is){
          // 更新
          if(employee_map && oneId && moment(nowDate).isBefore(employee_map[oneId].localStorageExpire)){
            commit('SET_EMPLOYEE_MAP', employee_map)
            resolve(employee_map)
          }else{
            get_employee_map().then(response => {
              if(response.data.code == 1){
                let data = {}
                for(let i in response.data.data.list){
                  data[response.data.data.list[i].id] = response.data.data.list[i]
                  if (i == 0) {
                    oneId = response.data.data.list[i].id
                    data[response.data.data.list[i].id].localStorageExpire = moment().add(Math.floor(Math.random() * (120 - 60 + 1)) + 60, "second").format("YYYY-MM-DD HH:mm:ss")
                  }
                }
                commit('SET_EMPLOYEE_MAP', data)
                if (window.plus) {
                  plus.storage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
                } else {
                  localStorage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
                }
              }
              resolve(response.data)
            }).catch(error => {
              reject(error)
            })
          }
        }else{
          get_employee_map().then(response => {
            if(response.data.code == 1){
              let data = {}
              for(let i in response.data.data.list){
                data[response.data.data.list[i].id] = response.data.data.list[i];
              }
              data.localStorageExpire = moment().add(Math.floor(Math.random() * (120 - 60 + 1)) + 60, "second").format("YYYY-MM-DD HH:mm:ss")
              commit('SET_EMPLOYEE_MAP', data)
              if (window.plus) {
                plus.storage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
              } else {
                localStorage.setItem('SET_EMPLOYEE_MAP', JSON.stringify(data))
              }
            }
            resolve(response.data)
          }).catch(error => {
            reject(error)
          })
        }
      })
    },

    get_point_types({commit},is){
      return new Promise((resolve, reject) => {
        let point_types = null
        if(is){
          get_point_types().then(response => {
            if(response.data.code == 1){
              commit('SET_POINT_TYPES', response.data.data.list);
              if (window.plus) {
                plus.storage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              } else {
                localStorage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              }
            }
            resolve(response.data.data.list)
          }).catch(error => {
            reject(error)
          })
          return
        };
        if(window.plus){
          point_types = JSON.parse(plus.storage.getItem('SET_POINT_TYPES'))
        }else{
          point_types = JSON.parse(localStorage.getItem('SET_POINT_TYPES'))
        }
        if(point_types){
          commit('SET_POINT_TYPES', point_types)
          resolve(point_types)
        }else{
          get_point_types().then(response => {
            if(response.data.code == 1){
              commit('SET_POINT_TYPES', response.data.data.list)
              if (window.plus) {
                plus.storage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              } else {
                localStorage.setItem('SET_POINT_TYPES', JSON.stringify(response.data.data.list))
              }
            }
            resolve(response.data.data.list)
          }).catch(error => {
            reject(error)
          })
        }

      })
    },
    get_user_info({commit},token) {
      return new Promise((resolve, reject) => {
        let user_info = null
        let nowDate = moment().format("YYYY-MM-DD HH:mm:ss");
        if(token=='isShow'){
            get_info(getToken()).then(response => {
              if(response.data.data.user.is_official == 0){
                router.push({
                  path: '/noAccess',
                  query: {
                    msg: '当前用户未授权进入系统，请联系管理员为您【启用积分管理】，<br/>如需咨询客服，请到您企业专属的功道云服务群咨询'
                  }
                })
                return
              }
              response.data.data.user.localStorageExpire = moment().add(Math.floor(Math.random() * (120 - 60 + 1)) + 60, "second").format("YYYY-MM-DD HH:mm:ss")
              commit('SET_USERINFO', response.data.data.user)
              if (window.plus) {
                plus.storage.setItem('user_info', JSON.stringify(response.data.data.user))
              } else {
                localStorage.setItem('user_info', JSON.stringify(response.data.data.user))
              }
              resolve(response.data)
            }).catch(error => {
              reject(error)
            })
            return;
        }
        if (window.plus) {
          user_info = JSON.parse(plus.storage.getItem('user_info'))
        } else {
          user_info = JSON.parse(localStorage.getItem('user_info'))
        }
        if (user_info && user_info.data.id && moment(nowDate).isBefore(user_info.data.localStorageExpire)) {
          commit('SET_USERINFO', user_info.data)
          resolve({code: 1, msg: '', data: {user: user_info}})
        }else{
          if(typeof(token) == 'undefined'){ return false}
          get_info(token).then(response => {
            response.data.data.user.localStorageExpire = moment().add(Math.floor(Math.random() * (120 - 60 + 1)) + 60, "second").format("YYYY-MM-DD HH:mm:ss");
            commit('SET_USERINFO', response.data.data.user)
            if (window.plus) {
              plus.storage.setItem('user_info', JSON.stringify({data:response.data.data.user}))
            } else {
              localStorage.setItem('user_info', JSON.stringify({data:response.data.data.user}))
            }
            resolve(response.data)
          }).catch(error => {
            reject(error)
          })
        }

      })
    },
  }
}

export default user
