<template>
  <div v-loading="loading"
       class="login-bodyBox"
       element-loading-text="拼命加载中"
       element-loading-spinner="el-icon-loading"
       element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="login-center">
      <div class="login-right">
        <div class="login-header">
          <div class="header-box">
            <span class="iconfont icon-yiliangyiyun"></span>

            <p>管理后台</p>
          </div>
        </div>
        <!--登录-->
        <div v-if="loginBox"
             class="login-box">
          <div class="title-text">请确认登录管理后台的企业和密码</div>
          <img class="company-image"
               :src="companyLogo" />
          <span class="company-name">{{ companyName }}</span>
          <el-row>
            <el-col>
              <!-- <el-input v-model="formData.domainName"
                        placeholder="请输入公司简称" /> -->
              <el-select v-model="formData.domainName" filterable placeholder="请选择" class="comp-select">
                <el-option v-for="item in compOptionList" :key="item.compName" :label="item.compName" :value="item.compName">
                </el-option>
              </el-select>
            </el-col>
            <el-col class="icon-user">
              <span class="svg-container">
                <svg-icon icon-class="user" />
              </span>
              <el-input v-model="formData.username"
                        placeholder="请输入用户名/手机号" />
            </el-col>
            <el-col class="icon-user">
              <span class="svg-container">
                <svg-icon icon-class="password"></svg-icon>
              </span>
              <el-input v-model="formData.password"
                        type="password"
                        placeholder="请输入密码"
                        @keyup.enter.native="handleLogin" />
            </el-col>
            <el-col>
              <el-button type="primary"
                         @click="handleLogin"
                         style="margin-top: 10px">登录</el-button>
              <div class="operation-body">
                <div class="forget-password"
                     @click="getForgetBox">忘记密码</div>
                <div v-if="!companyName"
                     class="forget-password"
                     @click="goReception">返回前台</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <div class="login-footer">
      <!-- <p class="copyright">Copyright © 大连海大赢海科技有限公司版权所有 CP备案号 : 辽ICP备13007766号-6</p> -->
    </div>

    <!--忘记密码消息弹框盒子-->
    <el-dialog class="dialog"
               title="找回密码"
               :visible.sync="messageBox"
               width="30%"
               center>
      <!--弹框主体-->
      <el-form ref="forgetDate"
               :model="forgetDate"
               :rules="loginRule"
               label-width="90px"
               class="demo-ruleForm">
        <!-- <el-form-item label="当前企业：">{{ companyName }}</el-form-item> -->
        <el-form-item label="绑定手机号码："
                      prop="userCellPhone">
          <div style="display:flex;">
            <div class="verification-phone">
              <!-- <span> -->
              <el-input maxlength="11" :disabled="disablePhone"
                        class="compTel"
                        v-model="forgetDate.userCellPhone"
                        placeholder="请输入手机号" />
              <!-- {{ formData.userCellPhone | phoneFilter }}</span> -->
            </div>
            <el-button v-show="showVerification"
                       type="primary"
                       @click="sendVerification">发送验证码</el-button>
            <el-button v-show="!showVerification"
                       class="retry">重试({{ count }})s</el-button>
          </div>
        </el-form-item>
        <el-form-item label="验证码："
                      prop="veriCode">
          <el-input v-model="forgetDate.veriCode"
                    placeholder="请输入验证码" />
        </el-form-item>
        <el-form-item label="新管理密码："
                      prop="password">
          <el-input v-model="forgetDate.password"
                    placeholder="请输入新密码" />
          <div class="password-prompt">新管理密码为6-20位数字、字母任意组合</div>
        </el-form-item>
        <el-form-item label="确认管理密码："
                      prop="againPassword">
          <el-input v-model="forgetDate.againPassword"
                    placeholder="再次输入管理密码" />
        </el-form-item>
      </el-form>

      <!--弹框底部-->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="resetForm">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  retrievePassword,
  getCompanyInfo,
  getCompany,
  loginEnhanced
} from '../../api/login/login';
import { setToken } from '../../utils/auth';
import { sendMsg } from '../../api/businessSettings/businessSettings';
import { userType } from '../../api/user';
import Cookies from "js-cookie";
import "../../static/images/page/logo/iconfont.css";
export default {
  name: 'Login',
  filters: {
    phoneFilter (val) {
      const reg = /^(.{3}).*(.{4})$/;
      return val.replace(reg, '$1****$2');
    }
  },
  data () {
    return {
      showVerification: true,
      disabledButton: false,
      disablePhone: false,
      count: '',
      companyLogo: require('../../static/images/page/login/login.png'),
      timer: null,
      loading: false,
      loginBox: true,
      messageBox: false,
      compOptionList:[],
      companyName: localStorage.getItem('enterprise-front-companyName'),
      formData: {
        domainName: '',
        username: '',
        password: '', // 登录密码
        userCellPhone: '',
        userKind: '',
        veriCode: ''
      },
      loginRules: '',
      loginRule: {
        userCellPhone: [
          {
            required: true,
            message: '请输入正确的手机号',
            trigger: 'blur'
          }
        ],
        veriCode: [
          {
            required: true,
            message: '验证码为6位数字',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '密码为6到20位数字、大小写字母任意组合',
            trigger: 'blur'
          }
        ],
        againPassword: [
          {
            required: true,
            message: '请再次输入密码',
            trigger: 'blur'
          }
        ]
      },
      forgetDate: {
        password: '',
        againPassword: '',
        veriCode: '',
        tel: '',
        userCellPhone: ''
      },
      loginForm: ''
    };
  },
  created () {
    this.getAddress();
  },
  methods: {
    getAddress () {
      /* const aa = window.location.hostname;
      const parts = aa.split('.');
      let domainName = '';
      if (parts.length > 0) {
        domainName = parts[0];
      }
      if (!isNaN(domainName) || domainName === 'localhost'|| domainName === 'mgr') {
        domainName = ''
      }
      this.formData.domainName = domainName;
    */
      if (Cookies.get('compSimpleName') && Cookies.get('phone')) {
        this.formData.domainName = Cookies.get('compSimpleName')
        this.formData.username = Cookies.get('phone')
      }
      this.getCompInfo();
    },
    /* 忘记密码 */
    getForgetBox () {
      this.showVerification = true;
      this.messageBox = true;
    },
    goReception () {
      window.location.href = this.$store.getters.baseInfo.pcUrl
    },
    /* 点击取消 */
    resetForm () {
      this.messageBox = false;
      this.$refs.forgetDate.resetFields();
    },
    /* 点击保存 */
    submitForm () {
      this.$refs.forgetDate.validate((valid) => {
        if (valid) {
          this.checkPwd(this.forgetDate.password);
        } else {
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true
          });
          return false;
        }
      });
    },
    /* 在忘记密码时找回密码 */
    getNewPassword () {
      const data = {
        mobilePhone: this.formData.userCellPhone || this.forgetDate.userCellPhone,
        veriCode: this.forgetDate.veriCode,
        password: this.forgetDate.againPassword,
        userKind: 'MANAGER',
      };
      retrievePassword(data)
        .then(() => {
          this.$message({
            message: '修改成功',
            type: 'success',
            showClose: true
          });
          this.messageBox = false;
        })
        .catch((code) => {
          if (code === 'AUTH_004') {
            this.$message({
              message: '验证码无效',
              type: 'error',
              showClose: true
            });
            this.forgetDate.veriCode = '';
          } else if (code === 'AUTH_006') {
            this.$message({
              message: '新密码与原始密码相同',
              type: 'error',
              showClose: true
            });
            this.forgetDate.againPassword = '';
            this.forgetDate.password = '';
          }
        });
    },
    /* 检查输入密码的规则 */
    checkPwd (pwd) {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/;
      const re = new RegExp(reg);
      if (re.test(pwd)) {
        if (this.forgetDate.againPassword !== this.forgetDate.password) {
          this.$message({
            message: '输入的密码不一致，请重新输入',
            type: 'error',
            showClose: true
          });
          this.forgetDate.againPassword = '';
        } else {
          this.getNewPassword();
        }
      } else {
        this.$message({
          message: '密码不符合规则，请重新输入',
          type: 'error',
          showClose: true
        });
      }
    },
    /* 通过域名获取公司信息 */
    async getCompInfo () {
      const response = await getCompanyInfo({
        domainName: this.formData.domainName
      });
      getCompany().then((res) => {
          this.compOptionList=res
        })
      localStorage.setItem('enterprise-front-domainName', this.formData.domainName);
      if (response) {
        if (response.compHeadimg) {
          this.companyLogo = response.compHeadimg;
          localStorage.setItem('enterprise-front-companyLogo', this.companyLogo);
          this.$store.commit('user/SET_LOGO', this.companyLogo);
        } else {
          localStorage.setItem('enterprise-front-companyLogo', '');
        }
        if (response.compName && response.managerInfo.managerName) {
          localStorage.setItem('enterprise-front-companyName', response.compName);
          this.companyName = response.compName;
          // localStorage.setItem('enterprise-front-companyId', response.compId);
          // localStorage.setItem(
          //  'enterprise-front-userRealName',
          //  response.managerInfo.managerName
          // );
        }
        this.formData.userCellPhone = response.managerInfo.managerMobilePhone;
        this.formData.userKind = response.managerInfo.userKind;
      }
    },
    /* 点击发送验证码 */
    sendVerification () {
      if (!this.forgetDate.userCellPhone) {
        return
      }
      this.disablePhone = true
      clearInterval(this.timer);
      this.timer = null;
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.showVerification = false;
        this.postVerification();
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.showVerification = true;
            clearInterval(this.timer);
            this.timer = null;
            this.disablePhone = false
          }
        }, 1000);
      }
    },
    /* 发送验证码 */
    postVerification () {

      const data = {
        mobilePhone: this.formData.userCellPhone || this.forgetDate.userCellPhone,
        userKind: this.formData.userKind
      };
      sendMsg(data)
        .then(() => {
          this.disabledButton = false;
        })
        .catch((code) => {
          if (code === 'AUTH_003') {
            this.$message({
              message: '该手机号不存在',
              type: 'error',
              showClose: true
            });
            this.loginBox = true;
          }
        });
    },
    b64Decode (str) {
      return decodeURIComponent(atob(str));
    },
    b64Encode (str) {
      return btoa(encodeURIComponent(str));
    },
    /* 临时登录 */
    handleLogin () {
      if (!this.formData.password) {
        this.$message({
          message: '密码不能为空',
          type: 'warning',
          showClose: true
        });
      } else {
        let userPas = this.formData.domainName + ',' + this.formData.username.trim() + ',' + this.formData.password + ',' + this.formData.domainName;
        localStorage.setItem("ws-pf_token", this.b64Encode(userPas));

        const data = {
          companyName: this.formData.domainName,
          username: this.formData.username,
          password: this.formData.password,
          userKind: 'MANAGER'
        };
        loginEnhanced(data)
          .then(async (response) => {
            userType().then((res) => {
              if (res === 'SHIP_COAST_CLIENT') {
                this.$store.dispatch('user/serviceType', 'both')
              }
              if (res === 'COAST_CLIENT') {
                this.$store.dispatch('user/serviceType', 'board')
              }
              if (res === 'SHIP_CLIENT') {
                this.$store.dispatch('user/serviceType', 'ship')
              }
            })
            setToken('Admin-Token');
            localStorage.setItem('enterprise-front-tenantId', response.tenantId);
            localStorage.setItem('enterprise-front-companyId', response.compId);
            localStorage.setItem('enterprise-front-userRealName', response.loginName);
            localStorage.setItem('enterprise-front-tenantType', response.tenantType);
            localStorage.setItem('enterprise-front-customerServiceStaffPhone', response.customerServiceStaffPhone);
            await this.getCompInfo();
            this.$router.push({
              path: this.redirect || '/'
            });
            this.formData.userCellPhone = response.userMobilePhone;
          })
          .catch((error) => {
            if (error === 'AUTH_001') {
              this.$message({
                message: '用户名或密码错误，请重新输入',
                type: 'error',
                showClose: true
              });
              this.formData.password = '';
            } else if (error === 'AUTH_002') {
              this.$message({
                message: '账户已被禁用',
                type: 'error',
                showClose: true
              });
            } else if (error === 'AUTH_007') {
              this.$message({
                message: '租户被禁用',
                type: 'error',
                showClose: true
              });
            } else if (error === 'AUTH_008') {
              this.$message({
                message: '不存在的公司',
                type: 'error',
                showClose: true
              });
            }
          });
      }
    }
  }
};
</script>
<style scoped lang="scss">
.icon-yiliangyiyun{
color:#fff;
font-size:36px;
}
.icon-user {
  position: relative;
}

.svg-container {
  color: #a6a7a8;
  width: 30px;
  position: absolute;
  height: 32px;
  line-height: 32px;
  border-radius: 8px;
  top: 10px;
  left: 0;
  z-index: 9;
  .svg-icon {
    width: 2em;
    height: 1.1em;
  }
}
.login-bodyBox {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  background: url("../../static/images/page/login/backImg.jpg") no-repeat;
  background-size: 100% 100%;
  background-attachment: fixed;
  width: 100vw;
  height: 100vh;
  overflow-y: hidden;
  .compTel > .el-input__inner {
    width: 200px !important;
  }
  /deep/ .el-dialog {
    width: 500px !important;
    margin-top: 20vh !important;
    .dialog-footer .el-button {
      padding: 9px 30px;
      margin: 9px 0 0 2px;
    }
    .el-dialog__body .el-input {
      // width: 300px;
      padding-bottom: 10px;
    }
    .el-dialog__body .el-button {
      height: 31px;
      line-height: 30px;
      margin: 0;
      padding: 0 10px;
      font-size: 13px;
      display: inline-block;
    }
    .el-dialog__body .padNull {
      padding-bottom: 5px;
    }

    .company-box {
      font-size: 13px;
      display: inline-block;
      width: 130px;
      text-align: right;
      padding-right: 3px;
      color: #666666;
      margin-bottom: 0;
    }
    .company-name {
      width: 208px;
      display: inline-block;
      height: 30px;
      line-height: 30px;
      padding-bottom: 5px;
    }
    .font {
      font-size: 13px;
      display: inline-block;
      width: 130px;
      text-align: right;
      padding-right: 3px;
      color: #666666;
      margin-bottom: 0;
    }
    .font:before {
      content: "*";
      color: #e74c3c;
      margin-right: 5px;
    }
    .password-prompt {
      font-size: 12px;
      line-height: 16px;
      position: absolute;
      width: 300px;
      display: inline-block;
      color: #999;
      bottom: -20px;
      left: 1px;
    }
    .verification-phone {
      width: 200px;
      display: inline-block;
      background: #eeeeee;
      height: 30px;
      line-height: 30px;
      margin-bottom: 8px;
      margin-right: 13px;
      border-radius: 4px;
      span {
        color: #666;
        padding-left: 14px;
        font-size: 13px;
      }
      .el-button {
        padding: 11px 11px;
        margin: 9px 0 0 7px;
      }
    }
  }
  .login-header {
    .header-box {
      position: absolute;
      top: -20%;
      left: 50%;
      width: 224px;
      height: 33px;
      margin-left: -112px;
      // height: 60px;
      // max-width: 800px;
      // margin: 0 auto;
      // width: 100%;
      display: flex;
      align-items: center;
      p {
        color: #ffffff;
        padding-left: 10px;
        font-size: 16px;
      }
    }
  }

  .login-center {
    padding-top: 9%;
    max-width: 800px;
    margin: 0 auto;
    width: 100%;
    display: flex;
    -webkit-box-align: center;
    .login-left {
      box-shadow: -12px -6px 20px 0 #0e0e0e94;
      display: inline-block;
    }
    .login-right {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -200px;
      margin-top: -200px;
      width: 400px;
      height: 400px;
      background: #fff;
      display: inline-block;
      .login-box {
        /deep/ .el-input__inner {
          padding-left: 25px;
        }
        height: 340px;
        padding: 30px 50px;
        .title-text {
          color: #333;
          font-size: 14px;
          text-align: center;
        }
        .company-image {
          display: block;
          margin: 0 auto;
          margin-top: 18px;
          margin-bottom: 10px;
          width: 72px;
          height: 72px;
          border-radius: 6px;
        }
        .company-name {
          font-size: 16px;
          color: #333;
          font-weight: bold;
          text-align: center;
          display: block;
          padding-bottom: 30px;
        }
        .el-button--primary {
          cursor: pointer;
          // margin: 30px 0 20px;
          width: 100%;
          height: 40px;
          line-height: 40px;
          padding: 0;
        }
        .operation-body {
          display: flex;
          display: flex;
          margin-top: 20px;
          justify-content: space-around;
          .forget-password {
            color: #0560f5;
            text-align: center;
            cursor: pointer;
            font-size: 13px;
            font-weight: 500;
          }
        }
      }
      .verification-box {
        height: 220px;
        padding: 75px 50px 105px;
        .verification-phone {
          width: 206px;
          margin-right: 2px;
          display: inline-block;
          background: #eeeeee;
          height: 32px;
          line-height: 32px;
          border: 1px solid #dcdfe6;
          border-radius: 4px;
          img {
            padding: 0 10px;
            padding-bottom: 5px;
          }
          span {
            color: #666;
          }
        }
        .title-box {
          padding-bottom: 60px;
          font-size: 16px;
        }
        /deep/ .el-input__inner {
          height: 32px;
          line-height: 32px;
          font-size: 14px;
          padding: 0 8px;
        }
        /deep/ .el-input-group__prepend {
          padding: 0 10px;
        }
        /deep/ .el-row .el-col:nth-child(1) {
          .el-input__inner {
            background: #eeeeee;
            padding-left: 25px;
          }
          .el-button--primary {
            height: 32px;
            line-height: 30px;
            margin: 0;
            padding: 0 9px;
            font-size: 13px;
          }
        }
        /deep/ .el-row .el-col:nth-child(3) {
          .el-button--primary {
            height: 40px;
            margin: 0;
            width: 100%;
            font-size: 13px;
            background-color: #77a7f4;
          }
        }
      }
    }
  }
  .login-footer {
    text-align: center;
    color: #999;
    position: absolute;
    width: 100%;
    bottom: 30px;
    .copyright {
      padding: 5px 0;
    }
  }
  .retry {
    height: 32px;
    line-height: 30px;
    width: 85px;
    margin: 0;
    padding: 0 14px !important;
    font-size: 13px;
    display: inline-block;
    background-color: #eeeeee;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    color: #666;
  }
  /deep/ .el-row .el-input {
    margin-top: 10px;
  }
  .el-row {
    top: -30px;
  }
  /deep/ .el-input-group__prepend {
    background: none;
    border-right: none;
    padding: 0 10px;
    img {
      padding-bottom: 4px;
    }
  }
  /deep/ .el-input__inner {
    box-shadow: 0 0 0 1000px white inset;
  }
  /deep/ .el-form-item__label {
    font-size: 13px;
    padding-right: 7px;
  }
  /deep/ .el-input.is-active .el-input__inner,
  /deep/ .el-input__inner:focus {
    border-color: #dcdfe6;
  }
  /deep/ .el-input__inner:hover {
    border-color: #dcdfe6;
  }
  /deep/ .el-input,
  .el-input__inner,
  .el-input__icon {
    line-height: 29px;
  }

  /deep/ .el-form-item__label:before {
    content: "*";
    color: #e74c3c;
    margin-right: 4px;
  }
}
.el-dialog .el-input,
.el-input__inner,
.el-input__icon {
  height: 42px;
}
/deep/.phonenum {
  .el-form-item__content {
    height: 32px;
  }
  .el-input__inner {
    border: 1px solid #dcdfe6 !important;
    border-top-left-radius: 4px !important;
    border-bottom-left-radius: 4px !important;
  }
  .sendinput {
    width: 208px;
    margin-bottom: 10px;
    .el-input__inner {
      background-color: #eeeeee !important;
      border-color: #e4e7ed;
      color: #666666;
      cursor: not-allowed;
    }
  }
  .sendbutton {
    position: absolute;
    z-index: 9;
    top: 0;
    left: 214px;
  }
}
</style>
