<template>
  <el-container :style="backStyle">
    <div class="mask"></div>
    <el-header height="30px">
      <div class="logo-container" v-if="showTenant"></div>
    </el-header>
    <!-- 登录页添加授权按钮 -->
    <!-- <span class="container-header">
      <a @click="authMan"><i class="el-icon-document"></i>申请访问权限 </a>
    </span> -->
    <el-main>
      <div class="login-card__container fullheight">
        <el-card shadow="never" class="login-card">
          <div :style="totemStyle" class="totem-div">
            <h2>{{ companyName }}</h2>
          </div>
          <div class="login-div">
            <el-form
              style="margin: 40px 50px"
              :model="principal"
              :rules="rules"
              ref="principal"
            >
              <div class="welcome-title">欢迎登录</div>
              <!--欢迎登录-->
              <el-form-item prop="account">
                <el-input
                  size="medium"
                  clearable
                  prefix-icon="icon-account"
                  v-model="principal.account"
                ></el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input
                  show-password
                  clearable
                  prefix-icon="icon-password"
                  @keyup.enter.native="submitForm('principal')"
                  @focus="inputGetFocus"
                  size="medium"
                  v-model="principal.password"
                ></el-input>
              </el-form-item>

              <el-form-item prop="remberPwd">
                <el-checkbox
                  title="有效期为7天"
                  v-model="principal.remberPwd"
                  :true-label="1"
                  :false-label="0"
                  >记住密码</el-checkbox
                >
              </el-form-item>

              <!--              <el-alert v-if="responseError" :title="responseError" type="error" :closable="false"></el-alert>-->
              <el-form-item class="btns" style="text-align: right">
                <el-button
                  size="medium"
                  type="primary"
                  @focus="inputGetFocus"
                  @click="submitForm('principal')"
                  class="login-btn"
                  :loading="loading"
                  >登录</el-button
                >
                <el-button
                  size="medium"
                  @click="resetForm('principal')"
                  :disabled="loading"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </div>
    </el-main>
    <!-- 弹出申请授权 -->
    <el-dialog
      title="申请授权"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form label-width="200px">
        <el-form-item label="下载信息文件">
          <el-button @click="download" :loading="downLoading">
            <i class="el-icon-download">下载信息文件</i>
          </el-button>
        </el-form-item>
        <!-- 上传授权文件 -->
        <el-form-item label="上传授权文件">
          <el-upload
            ref="fileUp"
            :multiple="false"
            :show-file-list="false"
            :action="downLoad"
            :accept="accept"
            :file-list="files"
            :limit="1"
            :on-success="success"
            :on-error="error"
            :before-upload="beforeAvatarUpload"
          >
            <el-button>
              <i class="el-icon-upload2">上传授权文件</i>
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span class="infoTip"
        >请将系统信息文件发送至管理员，申请授权后将授权文件上传本机以获取访问权限</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >

        <el-button
          size="medium"
          @click="resetForm('principal')"
          :disabled="loading"
          >重置</el-button
        ></span
      >
    </el-dialog>
    <!-- 弹出申请授权 -->
    <el-dialog
      title="申请授权"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <el-form label-width="200px">
        <el-form-item label="下载信息文件">
          <el-button @click="download" :loading="downLoading">
            <i class="el-icon-download">下载信息文件</i>
          </el-button>
        </el-form-item>
        <!-- 上传授权文件 -->
        <el-form-item label="上传授权文件">
          <el-upload
            ref="fileUp"
            :multiple="false"
            :show-file-list="false"
            :action="downLoad"
            :accept="accept"
            :file-list="files"
            :limit="1"
            :on-success="success"
            :on-error="error"
            :before-upload="beforeAvatarUpload"
          >
            <el-button>
              <i class="el-icon-upload2">上传授权文件</i>
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <span class="infoTip"
        >请将系统信息文件发送至管理员，申请授权后将授权文件上传本机以获取访问权限</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <!-- <el-footer class="copyright">Copyright © 版权所有 2019</el-footer> -->
  </el-container>
</template>

<script>
import uc from '@/api/uc.js'
import Cookie from 'js-cookie'
import portal from '@/api/portal.js'
import {mapState} from 'vuex'
export default {
  name: 'login',
  props: ['tenant'],
  data() {
    var checkAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入账号'))
      }
      if (/^[a-zA-Z0-9_-]{2,20}$/.test(value)) {
        return callback()
      } else {
        return callback(new Error('账号格式不符合规范'))
      }
    }
    return {
      logo: '',
      name: 'EDP',
      showTenant: false,
      showLogo: false,
      companyName: '管理平台',
      tenantName: '',

      principal: {
        tenantId: '',
        account: '',
        password: '',
        remberPwd: 0
      },
      rules: {
        account: [{validator: checkAccount, trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}]
      },
      responseError: '',
      loading: false,
      backStyle: {
        width: '100%',
        height: '100%',
        background: `url(${require('@/assets/img/bg.jpg')}) no-repeat center / 100% 100%`
        // background: `url(${require('@/assets/img/loginbg.png')}) no-repeat center / 100% 100%`,
        // background: `url(${require("@/assets/img/back.jpg")}) center / 100% auto no-repeat`
      },
      totemStyle: {
        width: '420px',
        height: '420px',
        float: 'left',
        // backgroundColor: "rgb(169 187 205 / 13%)",
        backgroundColor: '#282b33',
        background: `url(${require('@/assets/img/loginImg.jpg')}) no-repeat center / 100% 100%`
        // background: `#1975FF url(${require("@/assets/img/totem.png")}) center / 100% auto no-repeat`
        // background: `transparent url(${require("@/assets/img/totem1.png")}) no-repeat center 30% / 100% 70% `
      },
      //负责的是登录页授权文件相关数据变量
      isIeExplorer: false,
      dialogVisible: false,
      downLoading: false,
      accept: '.lic',
      files: [],
      uploadingFiles: {}
    }
  },
  mounted() {
    window.webSocket && window.webSocket.close()
    this.setDefaultValue()
    //获取租户信息
    let tenant = this.tenant ? this.tenant : 'platform'
    if (tenant) {
      let url = '${uc}/uc/tenantManage/v1/getTenantByCode?code=' + tenant
      let _this = this

      this.$http.get(url).then(resp => {
        if (resp.data) {
          let tenantManage = resp.data
          _this.showTenant = true
          _this.companyName = tenantManage.name
          if (tenant != 'platform') {
            _this.principal.tenantId = resp.data.id
          }
          if (tenantManage.ico) {
            let ico = JSON.parse(tenantManage.ico)
            if (ico && ico.length > 0) {
              _this.showLogo = true
              _this.logo =
                window.context.portal +
                '/file/v1/getLogoFile?logoType=manage&tenantId=' +
                tenantManage.id
            }
          }
        }
      })
    } else {
      //不是租户
      this.sysSetting()
    }
  },
  computed: mapState({
    downLoad: function() {
      return `${
        window.context.portal
      }/uc/AuthorizationModel/v1/uploadAuthorizationFile`
    },
    headers: state => {
      return {Authorization: `Bearer ${state.login.currentUser.token}`}
    }
  }),
  methods: {
    //如果记住密码则默认表单赋值
    setDefaultValue() {
      let account = Cookie.get('account'),
        remberPwd = Number(Cookie.get('remberPwd')),
        password = Cookie.get('accountPwd')
      if (remberPwd) {
        // 如果有记住密码 取密文解密放进输入框
        let Base64 = require('js-base64').Base64
        password = Base64.decode(password)
      }
      this.principal = {
        ...this.principal,
        ...{account, password, remberPwd}
      }
    },
    //获取系统默认配置 系统Logo、名称
    sysSetting() {
      const _this = this
      let url =
        window.context.portal + '/sys/sysProperties/v1/getDecryptBySysSetting'
      this.$http.get(url).then(response => {
        if (response && response.data && response.data.value) {
          _this.showTenant = true
          let sysSettingData = JSON.parse(response.data.value)
          if (sysSettingData.manageName == '') {
            _this.companyName = _this.name
          } else {
            _this.companyName = sysSettingData.manageName
          }
          if (sysSettingData.ico.length > 0) {
            let ico = sysSettingData.ico
            _this.showLogo = true
            _this.logo =
              window.context.portal +
              '/file/v1/downloadFile?fileId=' +
              ico[0].id
          }
        }
      })
    },
    querySearch(queryString, cb) {
      if (!queryString) {
        return cb([])
      }
      let queryFilter = {}
      queryFilter.pageBean = {
        page: 1,
        pageSize: 20,
        total: 0,
        showTotal: true
      }
      let query = {
        property: 'name_',
        value: queryString,
        group: 'main',
        operation: 'LIKE',
        relation: 'AND'
      }
      if (!queryFilter.querys) {
        queryFilter.querys = []
      }
      queryFilter.querys.push(query)

      this.$http
        .post(`${window.context.uc}/uc/tenantManage/v1/listJson`, queryFilter)
        .then(res => {
          // 调用 callback 返回建议列表的数据
          cb(res.data.rows)
        })
    },
    handleSelect(item) {
      this.tenantName = item.name
      this.principal.tenantId = item.id
    },
    setRouterPath() {
      this.$store.dispatch('login/actionLoginAccount', this.principal.account)
      localStorage.setItem(
        this.principal.account + 'loginRoutePath',
        this.$route.path
      )
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.inputGetFocus()
          this.loading = true
          this.setRouterPath()
          this.$store
            .dispatch('login/loginByPrincipal', this.principal)
            .then(loginStatus => {
              if (loginStatus && loginStatus == true) {
                this.$store.dispatch('menu/actionMenus').then(res => {
                  if (res.length) {
                    if (res[0].children && res[0].children.length) {
                      this.$router.push({
                        path: `/sysplat/${res[0].children[0].alias}`
                      })
                      // 无固定首页
                      // this.$router.push({
                      //     path: `/frontPlat/${res[0].alias}/${res[0].children[0].alias}`,
                      // })
                      //获取端口号,判断是否是养护系统
                      //   let port = window.location.port
                      //   if (port === '8198' || port === '8888') {
                      //     this.$router.push({
                      //       path: `/sysplat/${res[0].children[0].alias}`
                      //     })
                      //   } else {
                      //     // 固定首页
                      //     // this.$router.push({
                      //     //  path: `/sysplat/sysIndex`
                      //     // })
                      //   }
                    }
                    // else {
                    //     this.$router.push({
                    //         path: `/frontPlat/${res[0].alias}`,
                    //     })
                    // }
                  }
                  this.loading = false
                })
                this.$store.dispatch('menu/actionFrontMenus')
                //     .then(res=>{
                //         if(window.context.railway){
                //             this.$router.push({
                //                 path: `/frontPlat/${res[0].alias}`,
                //             })
                //         }else{
                //             this.$router.push({
                //                 path: `/frontPlat/frontIndex`,
                //             });
                //         }
                //         this.loading = false
                //     });
                // 连接websocket
                this.$bus.$emit('login')
                this.getAllDict()
              } else if (loginStatus == false) {
                this.$router.push({
                  name: 'resetPwdView',
                  params: {account: this.principal.account}
                })
              }
            })
            .catch(msg => {
              this.loading = false
              if (msg.startsWith('timeout of')) {
                msg = '登录超时'
              }
              this.responseError = msg
            })
        } else {
          return false
        }
      })
    },
    getAllDict() {
      portal.getSysDict().then(data => {
        if (data) {
          sessionStorage.setItem('dict_data', JSON.stringify(data))
        }
      })
    },
    inputGetFocus() {
      this.responseError = ''
    },
    resetForm(formName) {
      this.responseError = ''
      this.$refs[formName].resetFields()
    },
    //弹出授权模态框
    authMan() {
      this.dialogVisible = true
    },
    //关闭模态框
    handleClose(done) {
      done()
    },
    //授权文件下载信息文件
    download() {
      this.downLoading = true
      //   console.log('ffff')
      portal.downloadFileLic().then(res => {
        this.downLoading = false
        // const content = res
        // const blob = new Blob([content])
        // const fileName = 'license.lic'
        // const elink = document.createElement('a')
        // elink.download = fileName
        // elink.style.display = 'none'
        // elink.href = URL.createObjectURL(blob)
        // document.body.appendChild(elink)
        // elink.click()
        // URL.revokeObjectURL(elink.href) // 释放URL 对象
        // document.body.removeChild(elink)
        // this.downLoading = false
      })
    },
    //上传授权文件成功返回提示
    success(response, file, fileList) {
      this.$message.success(response)
      console.log(response, file, fileList)
    },
    //上传失败返回提示
    error(response, file, fileList) {
      this.$message.error('文件上传失败')
      delete this.uploadingFiles[Base64.encode(file.name)]
    },
    beforeAvatarUpload(file) {
      // 文件类型限制
      const name = file.name ? file.name : ''
      const ext = name
        ? name.substr(name.lastIndexOf('.') + 1, name.length)
        : true
      const isExt = this.accept.indexOf(ext) < 0
      this.isChecking = !isExt
      if (isExt) {
        if (this.accept == 'false') {
          this.$message.error('请配置可上传文件的格式!')
        } else {
          this.$message.error('上传的附件只能是 ' + this.accept + '格式!')
        }
        return !isExt
      }
      this.uploadingFiles[Base64.encode(name)] = 'eror'
    }
  },
  created() {
    let USER_AGENT = navigator.userAgent.toLowerCase()
    let isChrome = /.*(chrome)\/([\w.]+).*/
    if (!isChrome.test(USER_AGENT)) {
      this.isIeExplorer = true
    }
  },
  components: {}
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/element-variables.scss';
.mask {
  /*background-color: #1a1a1a;*/
  /*opacity: .5;*/
  /*position: fixed;*/
  /*height: 100vh;*/
  /*width: 100vw;*/
  /*z-index: 1;*/
}
.login-card__container {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -o-box;
  display: flex;
  display: -webkit-flex; /* Safari */
  display: flex;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
}

.logo-container {
  margin-top: 10px;
  /*display: inline-block;*/
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 200px;
  margin-left: 30px;
}
.container-header {
  position: absolute;
  right: 0;
  padding: 20px;
  a {
    color: #5b9dff;
    font-size: 13px;
    text-decoration: none;
    cursor: pointer;
  }
}

.logo-container > i.icon-hotent-H-c {
  font-size: 36px;
  // background-image: linear-gradient($--color-secondary, $--color-primary);
  //background-clip: text;
  //-webkit-background-clip: text;

  color: #fff;
  margin-right: -5px;
}
.logo-container > .logos {
  display: inline-block;
  width: 60px;
  height: 50px;
  background: url('~@/assets/img/logo.png') no-repeat center / 100%;
}

.v-line {
  color: #fbfbfb;
  margin: 0 5px;
}

.logo-container > i.icon-hotent-H-ie {
  font-size: 36px;
  //background-clip: text;
  //-webkit-background-clip: text;
  //color: $--color-primary;
  //margin-right: -5px;
}

.logo-container:hover > i.icon-hotent-H-c {
  background-image: linear-gradient($--color-primary, $--color-secondary);
}

.logo-container > span.pre-word {
  font-size: 26px;
  font-weight: bold;
  color: $--color-primary;
}

.logo-container > span.tail-word {
  font-size: 24px;
  font-weight: bold;
  color: #bdbfc2;
}

.logo-container > .logo-divider {
  margin: 0 25px 11px 25px;
  height: 18px;
}

.logo-container > .system-name {
  color: #fff;
  font-weight: bold;
  font-size: 16px;
}

.site-div {
  float: right;

  margin-top: 25px;
  margin-right: 40px;
}

.site-div > a {
  color: #5b9dff;
  font-size: 12px;
  text-decoration: none;
}

.site-div > a > i {
  font-weight: bold;
  margin-right: 5px;
}

.login-card {
  /*width: 600px;*/
  height: 420px;
  border: 0;
  background: transparent;
  box-shadow: 0 0 120px rgba(0, 109, 167, 0.6);
}

.totem-div {
  /*-moz-box-shadow: 2px 2px 5px #999;*/
  /*-webkit-box-shadow: 2px 2px 5px #999;*/
  /*box-shadow: 2px 2px 5px #999;*/
  display: flex;
  justify-content: center;
  align-items: center;
  align-items: start;
  > div {
    width: 100%;
    padding: 0 40px;
  }
  h2 {
    font-size: 24px;
    text-align: center;
    color: #fff;
    font-weight: 600;
    letter-spacing: 2px;
    padding-top: 36px;
    /*padding-left: 60px;*/
  }

  >>> .el-divider {
    margin: 15px auto;
    background-color: #373b46;
    .el-divider__text {
      color: #6c7079;
      background-color: #282b33;
    }
  }
}

.login-div {
  width: 400px;
  height: 420px;
  float: right;
  background-color: #fff;
  padding-top: 26px;
}

.welcome-title {
  min-height: 20px;
  margin-top: 40px;
  font-size: 18px;
  margin-bottom: 50px;
  /*color: #fff;*/
  letter-spacing: 2px;
  // font-weight: 600;
  text-align: center;
  font-family: Roboto, Microsoft YaHei, Sans-serif;
}

.copyright {
  color: #fff;
  font-size: 13px;
  text-align: center;
}

>>> .el-card__body {
  padding: 0;
}

.login-card /deep/ .el-alert__content {
  padding: 5px;
}

.btns >>> .el-form-item__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.main-header {
  /*position: absolute;*/
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  /*left: 50%;
    transform: translate(-50%, 0);
    top: 28%;*/
  color: #fff;
}

.main-header .logos {
  display: inline-block;
  width: 80px;
  height: 55px;
  /*background: url("~@/assets/img/logo.png") no-repeat center / 100% ;*/
  background: url('~@/assets/img/logo.png') no-repeat center / 100%;
}

.main-header .system-name {
  font-family: Roboto, Microsoft YaHei, Sans-serif;
  font-size: 20px;
  font-weight: bold;
  /*color:#fff;*/
  letter-spacing: 5px;
}

.main-header .driver {
  margin: auto 10px;
}

.main-header .subTit {
  font-weight: bold;
  font-size: 16px;
  letter-spacing: 2px;
}
.infoTip {
  display: block;
  width: 400px;
  color: rgba(255, 0, 0, 0.7);
  font-size: 16px;
  text-align: center;
  margin-left: 30px;
}
.login-btn {
  width: 220px;
  border: 1px solid #2182f7;
  background-color: #2182f7;
}
>>> .el-checkbox__input.is-checked .el-checkbox__inner {
  background-color: #2182f7;
  border-color: #2182f7;
}
</style>
