<template>
  <div class="loginbg" id="outheight">
    <!--输入框-->
    <div class="htmleaf-container">
      <div class="wrapper" :class="{'form-success': login}">
        <div class="container">
          <h3 style="color:white; margin-top: 15px">欢迎使用</h3>
          <p class="form" :style="{'margin-top': margintop + 'px'}">
            <input type="text" v-model="ename" class="usericon"/>
            <input :type="showpass==true?'text':'password'" v-model="password" class="psicon"/>
            <img :src="imageurl"
                 style="width: 20px;margin-bottom: 5px;position: absolute;left: 62%;bottom: 43%;"
                 alt=""
                 @click="changepass()"/>
            <button type="button" id="login-button" @click.prevent="confirm()"><strong>登录</strong></button>
          </p>
          <div class="row">
            <img src="../../assets/选中.png" style="width: 20px;margin-bottom: 5px" alt="" v-if="showsave"
                 @click="showoff()">
            <img src="../../assets/未选.png" style="width: 20px;margin-bottom: 5px" alt="" v-if="!showsave"
                 @click="showon()">
            <span class="text-left font">记住密码</span>
            <img src="../../assets/选中.png" style="width: 20px;margin-bottom: 5px" alt="" v-if="showauto == '1'"
                 @click="showoff1()">
            <img src="../../assets/未选.png" style="width: 20px;margin-bottom: 5px" alt="" v-if="showauto == '2'"
                 @click="showon1()">
            <span class="text-left font">自动登录</span>
            <p></p>
            <span class="devicetext">设备码：{{ deviceIemi }}</span>
          </div>
        </div>
      </div>
    </div>
    <!--<load-appdata @ready="onReady"></load-appdata>-->
    <div style="width: 100%;height: 100%;position: fixed;top: 0px;" v-show="loaderShow">
      <div id="loading" class="loading">登陆中...</div>
    </div>
    <modal :show.sync="modifyPassword" backdrop="false">
      <header slot="modal-header" class="modal-header">
      </header>
      <article slot="modal-body" class="modal-body">
        <modify-pass-word :sourse="login" :weak-password="weakPassword" v-if="modifyPassword"
                          v-on:success="success"></modify-pass-word>
      </article>
      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>
  </div>
</template>

<script>

/**
 * 说明：
 * /rs/vue 请求获取到的配置文件有关配置项目
 * telephone.LoginApp.weakPassword：为true 是判断是否弱密码校验
 *
 * globle 校验参数 Device_IEMI 是否需要校验设备iemi编码
 *
 */


import Vue from 'vue'
import * as Util from '../../Util'
import JSEncrypt from 'jsencrypt'
//获取json配置文件
let asyncReady = async function (self, url) {
  // 获取配置信息
  try {
    console.log("获取营收配置文件和参数【开始】")
    await self.$appdata.load()
    console.log("获取营收配置文件和参数【结束】，开始获取vue配置文件【开始】")
    let that = self
    let res = await Vue.resetget(`${url}/phone/rs/vue`, {data: {}}, {resolveMsg: null, rejectMsg: null})
    that.$set('config', res.data)
    Vue.config2 = res.data
    // 判断是否需要弱密码校验
    if (self.config && self.config.telephone && self.config.telephone.LoginApp && "undefined" != typeof self.config.telephone.LoginApp.weakPassword) {
      self.weakPassword = self.config.telephone.LoginApp.weakPassword
    }
    console.log("手机端获取.json文件")
    console.log(JSON.stringify(self.config))
    return true
  } catch (error) {
    // 此处业务数据装载异常不做任何处理，理论上不会有任何异常
    self.$showMessage('登录失败!用户名或密码错误!')
    return false
  }
}

//装载业务数据
let asyncLoadData = async function (self, url) {
  try {
    // 读取报建本地配置文件
    var result = HostApp.readLocalFile('workflow_apply.json')
    if (result.code == 500) {
      console.log('不存在流程配置文件，即不使用报建app')
      return
    }
    var data = JSON.parse(result.data)
    console.log('读取报建配置文件成功,存入缓存中的data=>' + JSON.stringify(data))
    Vue.workflow_vue = Vue.prototype.$workflow_vue = data
  } catch (error) {
    // 此处业务数据装载异常不做任何处理，理论上不会有任何异常,只有当app版本端版本较低无readlocalfile时会异常
    console.log(error)
  }
}

export default {
  title: '登录系统',
  data() {
    return {
      loaderShow: false,
      config: {},
      weakPassword: false,
      modifyPassword: false,
      ename: '',
      login: 'login',
      password: '',
      showsave: true,
      showauto: '2',  // 1 自动登陆  2取消自动登陆
      showpass: false,
      imageurl: require('../../assets/miwen.png'),
      deviceIemi: '无法获取该设备码，请联系管理员',
      loginSafe: false,
      margintop: document.documentElement.clientHeight * 0.1
    }
  },

  ready() {
    if (Vue.android) {
      const userCache = this.$androidUtil.getPreference('login_user_cache')
      this.showauto = this.$androidUtil.getPreference('auto_login')
      this.showauto = this.showauto ? this.showauto : '2'
      console.log(`自动登陆标识ready：${this.showauto}`)
      if (userCache) {
        const userCacheJSON = JSON.parse(userCache.replace(/\'/g, '\"'))
        this.password = userCacheJSON.password
        this.ename = userCacheJSON.username
      }
      this.deviceIemi = this.$androidUtil.getDeviceIEMI()
      console.log(`手机设备码：${this.deviceIemi}`)
      if (this.showauto == '1' && this.password) {
        this.confirm()
      }
    }
  },
  methods: {
    success(val) {
      // 修改密码成功
      this.modifyPassword = false
      this.password = val
    },
    // 对资源菜单进行排序
    sortFunctions (val) {
      this.sortArr(val)
      val.forEach((item)=>{
        if(item.children && Array.isArray(item.children)){
          this.sortArr(item.children)
        }
      })
      return val
    },
    sortArr(val){
      val.sort((itemA, itemB)=>{
        if(itemA.position !== itemB.position){
          return itemA.position - itemB.position
        }else{
          return itemA.id - itemB.id
        }
      })
    },
    // 记住密码选中/未选中
    showoff() {
      this.showsave = false
    },
    showon() {
      this.showsave = true
    },
    showoff1() {
      this.showauto = '2'
    },
    showon1() {
      this.showauto = '1'
    },
    changepass() {
      this.showpass = this.showpass ? false : true
      if (this.showpass) {
        this.imageurl = require("../../assets/mingwen.png")
      } else {
        this.imageurl = require("../../assets/miwen.png")
      }
    },
    async confirm() {
      this.loaderShow = true
      let ip ='';
      const rest = await fetch(`${this.$androidUtil.getProxyUrl()}/rs/systemUrl/getIp`);
      const ipData = await rest.json();
      ip=ipData.ip;
      const userData2 = {name: this.ename, password: this.password,ip: ip,device_type:'PHONE'}
      await this.$resetpost(`${this.$androidUtil.getProxyUrl()}/rs/logic/getLogin`, userData2, {
        resolveMsg: null,
        rejectMsg: null
      })
      console.log('Vue.android：' + Vue.android)
      const userData = {username: this.ename, password: this.password}
      console.log('获取登陆信息：' + userData)
      Vue.dataUrl = this.$androidUtil.getProxyUrl() + "/"
      // rsa加密
      let encrypt = new JSEncrypt();
      encrypt.setPublicKey('MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqPvovSfXcwBbW8cKMCgwqNpsYuzF8RPAPFb7LGsnVo44JhM/xxzDyzoYtdfNmtbIuKVi9PzIsyp6rg+09gbuI6UGwBZ5DWBDBMqv5MPdOF5dCQkB2Bbr5yPfURPENypUz+pBFBg41d+BC+rwRiXELwKy7Y9caD/MtJyHydj8OUwIDAQAB');
      const userDataEncrypt = encrypt.encrypt(JSON.stringify(userData))
      console.log("加密后的用户登录信息", userDataEncrypt)
      try {
        let ret = {}
        try {
          ret = await this.$resetpost(`${this.$androidUtil.getProxyUrl()}/rs/user/userLogin/手机服务`, userDataEncrypt, {
            resolveMsg: null,
            rejectMsg: null
          })
          this.$androidUtil.setPreference('siteId', ret.data.f_extend1 || '')
          this.$androidUtil.setPreference('flatId', ret.data.f_extend2 || '')
          this.$androidUtil.setPreference('name', ret.data.name || '')
          this.$androidUtil.setPreference('ename', ret.data.ename || '')
          if ((JSON.stringify(ret.data).startsWith("{") || JSON.stringify(ret.data).data.startsWith("[")) && ret.data.code && ret.data.msg && ret.data.code !== 200) {
            throw {status: ret.data.code, message: ret.data.msg}
          }
        } catch (e) {
          if (Vue.android) {
            this.loaderShow = false
            this.$showMessage('登录失败!用户名或密码错误!')
          }
          return
        }

        // 设置登录人
        if ((JSON.stringify(ret.data).startsWith("{") || JSON.stringify(ret.data).data.startsWith("[")) && ret.data.code && ret.data.msg && ret.data.code === 200) {
          Vue.user = Util.f = ret.data.data
        } else {
          Vue.user = Util.f = ret.data
        }

        // 对资源菜单进行排序
        let viewDetails = await Vue.resetpost(`${this.$androidUtil.getProxyUrl()}/rs/search`, {
          source: 'this.getRights().where(row.getType()==$function$ && row.getPath($name$).indexOf($功能权限$) != -1)',
          userid: Vue.user.id
        }, {resolveMsg: null, rejectMsg: null})
        const rithtList = viewDetails.data
        Vue.user.r = []
        rithtList.forEach(x => Vue.user.r.push(x.name))
        // 功能排序
        if ((JSON.stringify(ret.data).startsWith("{") || JSON.stringify(ret.data).data.startsWith("[")) && ret.data.code && ret.data.msg && ret.data.code === 200) {
          Vue.functions = this.sortFunctions(ret.data.data.functions)
        } else {
          Vue.functions = this.sortFunctions(ret.data.functions)
        }
        console.log('登陆人信息', JSON.stringify(Vue.user))
        let userStr
        if (Vue.android) {
          console.log(`Device_IEMI:${this.$androidUtil.getPreference('Device_IEMI')}`)
          // 判断是否需要验证 设备码
          if (this.$androidUtil.getPreference('Device_IEMI')) {
            console.log(`手机设备码：${this.deviceIemi}`)
            let result = await this.$resetpost(`${this.$androidUtil.getProxyUrl()}/rs/sql/tel_singleTable_OrderBy`, {
              data: {
                items: '*',
                tablename: 't_equipment',
                orderitem: 'id desc',
                condition: `f_terminal_number = '${this.deviceIemi}' and f_state = '正常'`
              }
            }, {resolveMsg: null, rejectMsg: null})
            console.log(`检测设备码存在是否：${result.data.length}`)
            if (result.data.length == 0) {
              HostApp.alert('设备码未绑定，请联系管理员！')
              return
            }
          }
          if (this.showsave) {
            userStr = `{'username':'${this.ename}','password':'${this.password}'}`
          } else {
            userStr = `{'username':'${this.ename}','password':''}`
          }
          console.log(this.showauto)
          this.$androidUtil.setPreference('login_user_cache', userStr)
          this.$androidUtil.setPreference('f_repairman_id', Util.f.id)
          this.$androidUtil.setPreference('f_repairman_name', Util.f.name)
          this.$androidUtil.setPreference('f_orgid', Util.f.orgid)
          this.$androidUtil.setPreference('f_role_name', Util.f.f_role_name || '')
          console.log("自动登陆标识" + Util.f.f_role_name)
          console.log(this.showauto)
          this.$androidUtil.setPreference('auto_login', this.showauto)
        }
        // 设置当前登录人信息
        if ((JSON.stringify(ret.data).startsWith("{") || JSON.stringify(ret.data).startsWith("[")) && ret.data.code && ret.data.msg && ret.data.code === 200) {
          Vue.$login = Vue.prototype.$login  = {jwt: ret.data.data.id,
            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)
            }, 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)
            }}
        } else {
          Vue.$login = Vue.prototype.$login = {jwt: ret.data.id,
            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)
            }, 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)
            }}
        }
        // 获取参数
        console.log('获取参数system以及安检参数')
        const flag = await asyncReady(this, this.$androidUtil.getProxyUrl())
        if (!flag) {
          this.loaderShow = false
          console.log('获取参数异常')
          return
        }
        console.log('获取参数结束')
        this.loaderShow = false
        // 弱口令验证
        if (this.weakPassword && !(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?!.*(123|321|abc|cba))[a-zA-Z\d!@#$%^&*()_+-=<>?]{8,16}$/.test(this.password))) {
          await this.$showMessage('登录系统: 此账户的密码过于简单，请修改密码后重新登陆！！！', ['confirm'])
          this.modifyPassword = true
          return
        }
        this.$goto('nav-bottom')
      } catch (e) {
        if (Vue.android) {
          this.loaderShow = false
        }
        this.$showMessage("登录失败!用户名或密码错误!")
      }
    },
  },
  watch: {
    'config'(val) {
      Vue.config = val
    }
  }
}
</script>
<style scoped="">
.devicetext {
  font: 13px PingFang-SC-Medium;
  position: fixed;
  width: 100%;
  bottom: 13px;
  transform: translate(-50%, -50%);
}

/*输入框样式*/
/*@import url(http://fonts.useso.com/css?family=Source+Sans+Pro:200,300);*/
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-weight: 300;
}

.loginbg {
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
}

.loginbg ::-webkit-input-placeholder {
  /* WebKit browsers */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
}

.loginbg :-moz-placeholder {
  /* Mozilla Firefox 4 to 18 */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  opacity: 1;
  font-weight: 300;
}

.loginbg ::-moz-placeholder {
  /* Mozilla Firefox 19+ */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  opacity: 1;
  font-weight: 300;
}

.loginbg :-ms-input-placeholder {
  /* Internet Explorer 10+ */
  font-family: 'Source Sans Pro', sans-serif;
  color: white;
  font-weight: 300;
}

.wrapper {
  /*background: #2D83BA;
  background: -webkit-linear-gradient(top left, #2D83BA 0%, #2D83BA 100%);
  background: linear-gradient(to bottom right, #2D83BA 0%, #2D83BA 100%);
  opacity: 0.8;*/
  /*position: absolute;*/
  /*top: 50%;
  right: 10%;
  width: 40%;
  height: 350px;
  margin-top: -150px;*/
  overflow: hidden;
}

.wrapper.form-success .container h3 {
  -webkit-transform: translateY(85px);
  -ms-transform: translateY(85px);
  transform: translateY(85px);
}

.container {
  /*max-width: 350px;*/
  margin: 0 auto;
  /*padding: 30px 100px 50px 100px;
  height: 350px;*/
  text-align: center;
  /*以下增加*/
  /*background: #2D83BA;
  background: -webkit-linear-gradient(top left, #2D83BA 0%, #2D83BA 100%);
  background: linear-gradient(to bottom right, #2D83BA 0%, #2D83BA 100%);*/
  opacity: 0.8;
}

.container h3 {
  font-size: 40px;
  -webkit-transition-duration: 1s;
  transition-duration: 1s;
  -webkit-transition-timing-function: ease-in-out;
  transition-timing-function: ease-in-out;
  font-weight: 200;
}

.form {
  padding: 20px 0;
  /*margin-top: 15%;*/
  position: relative;
  z-index: 2;
}

.form input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: 0;
  border: 1px solid #50ABE6;
  background-color: #50ABE6;
  width: 250px;
  border-radius: 3px;
  padding: 10px 15px;
  margin: 0 auto 10px auto;
  display: block;
  text-align: center;
  font-size: 18px;
  color: white;
  -webkit-transition-duration: 0.25s;
  transition-duration: 0.25s;
  font-weight: 300;
}

.form input:hover {
  background-color: rgba(255, 255, 255, 0.4);
}

.form input:focus {
  background-color: white;
  width: 300px;
  color: #53e3a6;
}

.usericon {
  background-image: url(../../assets/usericon.png);
  background-repeat: no-repeat;
  background-size: 30px;
  background-position-x: 8px;
  background-position-y: 8px;
}

.psicon {
  background-image: url(../../assets/psicon.png);
  background-repeat: no-repeat;
  background-size: 30px;
  background-position-x: 8px;
  background-position-y: 8px;
}

.form button {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: 0;
  background-color: white;
  border: 0;
  padding: 10px 15px;
  color: #253830;
  border-radius: 3px;
  width: 250px;
  cursor: pointer;
  font-size: 18px;
  -webkit-transition-duration: 0.25s;
  transition-duration: 0.25s;
}

.form button:hover {
  background-color: #f5f7f9;
}

/*注册字体样式*/
.form span {
  color: #fff;
  display: table-footer-group;
  position: absolute;
  right: 10px;
  margin-top: 10px;
  cursor: pointer;
}

.logotitle {
  color: #fff;
  position: absolute;
  top: 50px;
  left: 50px;
  font-size: 50px;
}

/*注册模态框界面样式*/
.modifystyle {
  background: #FCFEEE;
}

.modifystyle div {
  height: auto;
  margin-bottom: 15px;
  /*text-align: center;*/
  /*margin-left: 20%;*/
}

/*bootstrap字体图标要手动调整，所以使用字体图标的span必须紧跟在input后面，负责会错位*/
.modifystyle div input + span {
  top: 0 !important;
  right: 32%;
}

.modifystyle span {
  color: red;
}

/* 通告区内容 */
.notice-board {
  height: auto;
  position: absolute;
  top: 50%;
  margin-top: -150px;
  margin-left: 100px;
  color: #fff;
}

/*修改密码底部按钮部分样式*/
.footerbtn {
  text-align: center;
  padding: 15px;
}

.footerbtn button {
  width: 100px;
  margin-left: 20px;
}

.bg-bubbles {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.bg-bubbles li {
  position: absolute;
  list-style: none;
  display: block;
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.15);
  bottom: -160px;
  -webkit-animation: square 25s infinite;
  animation: square 25s infinite;
  -webkit-transition-timing-function: linear;
  transition-timing-function: linear;
}

.bg-bubbles li:nth-child(1) {
  left: 10%;
}

.bg-bubbles li:nth-child(2) {
  left: 20%;
  width: 80px;
  height: 80px;
  -webkit-animation-delay: 2s;
  animation-delay: 2s;
  -webkit-animation-duration: 17s;
  animation-duration: 17s;
}

.bg-bubbles li:nth-child(3) {
  left: 25%;
  -webkit-animation-delay: 4s;
  animation-delay: 4s;
}

.bg-bubbles li:nth-child(4) {
  left: 40%;
  width: 60px;
  height: 60px;
  -webkit-animation-duration: 22s;
  animation-duration: 22s;
  background-color: rgba(255, 255, 255, 0.25);
}

.bg-bubbles li:nth-child(5) {
  left: 70%;
}

.bg-bubbles li:nth-child(6) {
  left: 80%;
  width: 120px;
  height: 120px;
  -webkit-animation-delay: 3s;
  animation-delay: 3s;
  background-color: rgba(255, 255, 255, 0.2);
}

.bg-bubbles li:nth-child(7) {
  left: 32%;
  width: 160px;
  height: 160px;
  -webkit-animation-delay: 7s;
  animation-delay: 7s;
}

.bg-bubbles li:nth-child(8) {
  left: 55%;
  width: 20px;
  height: 20px;
  -webkit-animation-delay: 15s;
  animation-delay: 15s;
  -webkit-animation-duration: 40s;
  animation-duration: 40s;
}

.bg-bubbles li:nth-child(9) {
  left: 25%;
  width: 10px;
  height: 10px;
  -webkit-animation-delay: 2s;
  animation-delay: 2s;
  -webkit-animation-duration: 40s;
  animation-duration: 40s;
  background-color: rgba(255, 255, 255, 0.3);
}

.bg-bubbles li:nth-child(10) {
  left: 90%;
  width: 160px;
  height: 160px;
  -webkit-animation-delay: 11s;
  animation-delay: 11s;
}

@-webkit-keyframes square {
  0% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }
  100% {
    -webkit-transform: translateY(-700px) rotate(600deg);
    transform: translateY(-700px) rotate(600deg);
  }
}

@keyframes square {
  0% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }
  100% {
    -webkit-transform: translateY(-700px) rotate(600deg);
    transform: translateY(-700px) rotate(600deg);
  }
}

.loading {
  width: 36%;
  height: 7%;
  position: absolute;
  top: 30%;
  left: 32%;
  line-height: 56px;
  color: #fff;
  padding-left: 60px;
  font-size: 15px;
  background: #000 url(../../assets/loging.gif) no-repeat 10px 50%;
  opacity: 0.7;
  z-index: 9999;
  -moz-border-radius: 20px;
  -webkit-border-radius: 20px;
  border-radius: 20px;
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=70);
}
</style>
