import Vue from 'vue'
import JSEncrypt from 'jsencrypt'
import {HttpResetClass} from 'vue-client'

let loginGen = async function (name, password) {
  let data = {name: name, password: password}
  // rsa加密
  let encrypt = new JSEncrypt();
  encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqPvovSfXcwBbW8cKMCgwqNpsYuzF8RPAPFb7LGsnVo44JhM/xxzDyzoYtdfNmtbIuKVi9PzIsyp6rg+09gbuI6UGwBZ5DWBDBMqv5MPdOF5dCQkB2Bbr5yPfURPENypUz+pBFBg41d+BC+rwRiXELwKy7Y9caD/MtJyHydj8OUwIDAQAB');
  console.log(data)

  let getLogin = await Vue.resetpost('/rs/logic/getLogin', data, {resolveMsg: null, rejectMsg: null}, 'RSA')
  if (getLogin.data.states === '登录成功') {
    // 调用远程登录服务，获取所有有权访问的功能
    data = {username: name, password: password}
    data = encrypt.encrypt(JSON.stringify(data))
    let resource = await Vue.resetpost(`/rs/user/userLogin/客服系统`, data, {
      resolveMsg: null,
      rejectMsg: null
    })
    console.log('登陆获取Util', JSON.stringify(resource.data))
    Vue.$login.f = resource.data
    //获取jwt
    Vue.$login.jwt = getLogin.data.jwt
    // 把登录用户添加到cookie里
    Vue.cookie.set('loginId', Vue.$login.f.id)

    try {
      //获取有权限的功能树
      let hasRight = await Vue.resetpost(`/rs/search`, {
          source: "tool.getFullTree(this.getRights().where(row.getType() == $function$))",
          userid: Vue.$login.f.id
        },
        {
          resolveMsg: null,
          rejectMsg: null
        })
      console.log('有权限功能返回数据', JSON.stringify(hasRight.data))
      //准备替换功能树
      var fun=[]
      hasRight.data[0].children[0].children.forEach((item) => {
        if(item.name=='客服系统'){
          item.children.forEach((item1) => {
            fun.push(item1)
          })
        }
      })
      // console.log('替换前', JSON.stringify(Vue.$login.f.functions))
      // console.log('替换后', JSON.stringify(fun))
      Vue.$login.f.functions=fun
    }catch (error) {
    }
    if (Vue.$login.f.id !== '11') {
      try {
        let getAllArea = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($区$).getChildren()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})

        let areaTemp = []
        for (let i = 0; i < getAllArea.data.length; i++) {
          let getSliceArea = await Vue.resetpost('/rs/search',
            {source: 'this.getChildren()', userid: getAllArea.data[i].id},
            {resolveMsg: null, rejectMsg: null})
          let sliceTemp = []
          for (let j = 0; j < getSliceArea.data.length; j++) {
            sliceTemp.push({label: getSliceArea.data[j].name, value: getSliceArea.data[j].name})
          }
          areaTemp.push({label: getAllArea.data[i].name, value: sliceTemp})
        }
        Vue.$login.f.f_allArea = areaTemp
      }catch (error) {
        Vue.$login.f.f_allArea =[]
        console.log('获取区县',error)
      }
      // 获取抄表员
      try {
        let getGasman = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($抄表员$).getUsers()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        let gasman = []
        for (let i = 0; i < getGasman.data.length; i++) {
          gasman.push(getGasman.data[i])
        }
        Vue.$login.f.f_gasman = gasman
      }catch (error) {
        Vue.$login.f.f_gasman = []
        console.log('抄表员模块',error)
      }
      // 获取安装人
      try {
        let getInstallman = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($安装员$).getUsers()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        console.log('获取安装员', getInstallman)
        let installman = []
        for (let i = 0; i < getInstallman.data.length; i++) {
          installman.push(getInstallman.data[i])
        }
        Vue.$login.f.f_installman = installman
      }catch (error) {
        Vue.$login.f.f_installman =[]
        console.log('安装人模块',error)
      }
      // 获取换表员
      try {
        let getChangeMeterman = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($换表员$).getUsers()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        let changemeterman = []
        for (let i = 0; i < getChangeMeterman.data.length; i++) {
          changemeterman.push(getChangeMeterman.data[i])
        }
        Vue.$login.f.f_changemeterman = changemeterman
      }catch (error) {
        Vue.$login.f.f_changemeterman = []
        console.log('换表员模块',error)
      }
      // 票据使用人
      try {
        let getPaperUseman = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($票据使用人$).getUsers()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        let perperuseman = []
        for (let i = 0; i < getPaperUseman.data.length; i++) {
          perperuseman.push(getPaperUseman.data[i])
        }
        Vue.$login.f.f_paperUseman = perperuseman
      }catch (error) {
        Vue.$login.f.f_paperUseman = []
        console.log('票据使用人模块',error)

      }
      // 票据分配人
      try {
        let getPaperAllotman = await Vue.resetpost('/rs/search', {
          source: 'this.getParentByType($organization$).getChildByName($票据分配人$).getUsers()',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        let paperallotman = []
        for (let i = 0; i < getPaperAllotman.data.length; i++) {
          paperallotman.push(getPaperAllotman.data[i])
        }
        Vue.$login.f.f_paperAllotman = paperallotman
      }catch (error) {
        Vue.$login.f.f_paperAllotman = []
        console.log('票据分配人模块',error)
      }
      // TODO 处理界面细节
      try {
        let viewDetails = await Vue.resetpost('rs/search', {
          source: 'this.getRights().where(row.getType()==$function$ && row.getPath($name$).indexOf($功能权限$) != -1)',
          userid: Vue.$login.f.id
        }, {resolveMsg: null, rejectMsg: null})
        let r = viewDetails.data
        Vue.$login.r = []
        r.forEach(x => Vue.$login.r.push(x.name))
      }catch (error) {
        Vue.$login.r = []
        console.log('加载模块失败',error)
      }
      // 调用登录后处理
      for(let proc of Vue.$login.afterLogin) {
        await proc(Vue.$login.f)
      }
      // 定时发送心跳
      setInterval(()=> {
        let http = new HttpResetClass()
        http.load('POST', `rs/user/access/${Vue.$login.f.id}`, {}, {resolveMsg: null, rejectMsg: null}).then((req) => {
          if(req.data.status==710){
            Vue.showMessage(req.data.msg+",您将被强制退出系统", ['confirm']).then((res) => {
              if (res === 'confirm') {
                location.reload()
              }
            })
          }
        })
      }, 2 * 60 * 1000)
    }

  } else {
    let error = {status: 401, data: getLogin.data.states}
    // 抛出错误
    throw error
  }
}

let GetLoginInfoService = {
  // 登录后要处理的异步对象
  afterLogin: [],
  //验证码开关
  Verification: true,
  install (Vue, options) {
    // 给vue增添对话框显示方法
    Vue.$login = Vue.prototype.$login = GetLoginInfoService
  },

  f: {

  },

  /**
   * 登录
   * @param name
   * @param password
   */
  login (name, password) {
    return loginGen(name, password)
  },

  convertToIn (val) {
    let temp = ''
    if (val instanceof Array) {
      if (val.length >= 1) {
        temp = '('
        val.forEach((res) => {
          temp += `'${res}',`
        })
        temp = temp.substr(0, temp.length - 1) + ')'
      }
    }
    return temp
  },

  toStandardYearMonth () {
    let dt = new Date()
    let month = dt.getMonth() + 1
    return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month)
  },

  toStandardYearMonth1 () {
    let dt = new Date()
    let month = dt.getMonth() + 1
    return dt.getFullYear() + (month < 10 ? '0' + month : month)
  },

  toStandardDateString () {
    let dt = new Date()
    let month = dt.getMonth() + 1
    let date = dt.getDate()
    return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  },

  toStartAndEndDateString () {
    let dt = new Date()
    let month = dt.getMonth() + 1
    // let date = dt.getDate()
    return [dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-01',
      dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (new Date(dt.getFullYear(), month, 0).getDate())]
    // return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
  },

  toStandardTimeString () {
    let dt = new Date()
    let month = dt.getMonth() + 1
    let date = dt.getDate()
    let hour = dt.getHours()
    let min = dt.getMinutes()
    let sec = dt.getSeconds()
    return dt.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date) +
      ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
  },

  guid () {
    let buf = new Uint16Array(8)
    window.crypto.getRandomValues(buf)
    let S4 = function (num) {
      let ret = num.toString(16)
      while (ret.length < 4) {
        ret = '0' + ret
      }
      return ret
    }
    return (S4(buf[0]) + S4(buf[1]) + S4(buf[2]) + S4(buf[3]) + S4(buf[4]) + S4(buf[5]) + S4(buf[6]) + S4(buf[7]))
  },

  choices (role, param, hasBlank = false, blankHint = '请选择') {
    if (role == 'view') {
      Vue.getParams(param, [null])
    } else {
      let result = []
      if (hasBlank)
        result.push({label: blankHint, value: null})
      if (!Vue.param || !Vue.param[param])
        result.push({label: '请在系统设置里更新参数', value: '请在系统设置里更新参数'})
      else {
        let p = Vue.param[param]
        p.forEach(function (item) {
          result.push({label: item.name, value: item.name})
        })
      }
      return result
    }
  },

  required (param) {
    if (typeof param === 'number' && param == 0)
      return false
    if (!param)
      return true
    param = param + ''
    param = param.trim()
    if (!param)
      return true
    return false
  },

  isInt (n) {
    return !window.isNaN(n) && n % 1 === 0
  },

  isFloat (n) {
    return !window.isNaN(n)
  },

// this will convert all true/false to boolean
  booleanFilter (paper) {
    for (let key in paper) {
      if (!paper.hasOwnProperty(key))
        continue
      if (typeof paper[key] == 'object' && paper[key] != null) {
        booleanFilter(paper[key])
      } else {
        if (paper[key] === 'true' || paper[key] == 'false')
          paper[key] = (paper[key] === 'true')
      }
    }
  },
// recursively traverse through each path
  ratifyPics (paper) {
    for (let key in paper) {
      if (key.endsWith('_path')) {
        if (!paper[key]) {
          paper[key] = 'rs/db/file/nopic.png'
        } else {
          paper[key] = 'rs/db/file/' + paper[key]
        }
      } else if (paper[key] !== null && typeof (paper[key]) == 'object') {
        ratifyPics(paper[key])
      }
    }
  },

// load script and other stuff
  loadscript (type, fileName) {
    return new Promise((resolve, reject) => {
      let element
      if (type == 'css') {
        element = document.createElement('link')
        element.setAttribute('rel', 'stylesheet')
        element.setAttribute('type', 'text/css')
        element.setAttribute('href', fileName)
      } else if (type == 'js') {
        element = document.createElement('script')
        element.setAttribute('type', 'text/javascript')
        element.setAttribute('src', fileName)
      }
      if (element) {
        element.setAttribute('async', '')
        element.setAttribute('defer', '')
        element.addEventListener('load', function () {
          resolve(element)
        }, false)
        element.addEventListener('error', function () {
          reject(element)
        }, false)
        document.body.appendChild(element)
      }
    })
  },
// 不能选择器中截取掉多余的字符
  orgName (name) {
    return name.substring(10)
  },

  getNowDate (name) {
    // 求取当前时间的工具
    let myweekday = ''
    let year = ''
    let mydate = new Date()
    myweekday = mydate.getDay()
    let mymonth = mydate.getMonth() + 1
    let myday = mydate.getDate()
    let myyear = mydate.getYear()
    year = (myyear > 200) ? myyear : 1900 + myyear
    let week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期日', '星期六']
    // document.write("<font color=#ffffff>今天是 "+year+"年"+mymonth+"月"+myday+"日 "+weekday+"</font>");
    return year + '年' + mymonth + '月' + myday + '日  ' + week[myweekday]
  },

  addDate (date, days) {
    // 求取当前时间的工具
    let endDate = new Date(date)
    endDate = endDate.valueOf()
    endDate = endDate + days * 24 * 60 * 60 * 1000
    endDate = new Date(endDate)
    let month = endDate.getMonth() + 1
    let day = endDate.getDate()
    let hour = endDate.getHours()
    let min = endDate.getMinutes()
    let sec = endDate.getSeconds()
    return endDate.getFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) +
      ' ' + (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min) + ':' + (sec < 10 ? '0' + sec : sec)
    // return a
  },

// 通过地址栏的参数获取参数内容
  getUrlParames (param) {
    var query = window.location.search
    var iLen = param.length
    var iStart = query.indexOf(param)
    if (iStart === -1) {
      return ''
    }
    iStart += iLen + 1
    var iEnd = query.indexOf('&', iStart)
    if (iEnd === -1) {
      return query.substring(iStart)
    }
    return query.substring(iStart, iEnd)
  },

// 从地址栏获取加密的参数
  getUrlCompileParames (param) {
    let code = unescape(window.location.search.slice(1, window.location.search.length))
    let query = String.fromCharCode(code.charCodeAt(0) - code.length)
    for (var i = 1; i < code.length; i++) {
      query += String.fromCharCode(code.charCodeAt(i) - query.charCodeAt(i - 1))
    }
    let iLen = param.length
    let iStart = query.indexOf(param)
    if (iStart === -1) {
      return ''
    }
    iStart += iLen + 1
    let iEnd = query.indexOf('&', iStart)
    if (iEnd === -1) {
      return query.substring(iStart)
    }
    return query.substring(iStart, iEnd)
  },

// 对字符串进行加密
  compileStr (code) {
    let c = String.fromCharCode(code.charCodeAt(0) + code.length)
    for (let i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) + code.charCodeAt(i - 1))
    }
    return escape(c)
  },
// 字符串进行解密
  uncompileStr (code) {
    code = unescape(code)
    let c = String.fromCharCode(code.charCodeAt(0) - code.length)
    for (var i = 1; i < code.length; i++) {
      c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1))
    }
    return c
  },

  dateDescripte (date) {
    let nowTime = new Date().getTime()
    let oldTime = new Date(date).getTime()
    let timeDiff = nowTime - oldTime
    // 规则说明
    // 小于等于2分钟为刚刚
    // 大于2分钟小于等于1小时为取整的分钟前（例如：35分钟前）
    // 大于1小时小于等于24小时为取整的小时前（例如：15小时前）
    // 大于24小时小于等于30天为取整的天前（例如：12天前）
    // 大于30天小于等于12月为取整的月前，月份统一为30天一月，不做额外处理（例如：3个月前）
    // 大于365取整的年前，（例如：2年前）
    let minute = 1000 * 60
    let hour = minute * 60
    let day = hour * 24
    let month = day * 30
    let year = month * 12
    let des = ''
    if (timeDiff <= minute * 2) {
      des = '刚刚'
    } else if (minute * 2 < timeDiff && timeDiff < hour) {
      des = `${Math.floor(timeDiff / minute)}分钟前`
    } else if (hour < timeDiff && timeDiff <= day) {
      des = `${Math.floor(timeDiff / hour)}小时前`
    } else if (day < timeDiff && timeDiff <= month) {
      des = `${Math.floor(timeDiff / day)}天前`
    } else if (month < timeDiff && timeDiff <= year) {
      des = `${Math.floor(timeDiff / month)}个月前`
    } else if (year < timeDiff) {
      des = `${Math.floor(timeDiff / year)}年前`
    }
    return des
  },

  nextMonth20 (date) {
    let ds = date.split('-')
    let nextMonth = ds[1] - 0 + 1
    return ds[0] + '-' + (nextMonth < 10 ? '0' + nextMonth : nextMonth) + '-20 00:00:00'
  }
}

export default GetLoginInfoService
