/*Login*/
<template>
  <div>
    <transition name="marsk-fade">
      <div v-if="loginShow" class="marsk" />
    </transition>
    <transition name="slide-fade">
      <div class="login" v-if="loginShow">
        <i class="el-icon-close" @click="close" v-if="closeShow"></i>
        <div class="steps" v-if="formFlog===1">
          <p>手机验证</p>
        </div>
        <el-form
          ref="loginForm"
          class="login-form"
          :model="loginForm"
          :rules="loginRules"
          auto-complete="on"
          label-position="left"
          v-if="formFlog===0"
        >
          <div class="loginTitle">
            <h3 class="title" :class="index==0?'active':''"  @click="loginTob(0)" >账户登录</h3>
            <h3 class="title" :class="index!=0?'active':''"  @click="loginTob(1)">短信登录</h3>
          </div>
          <el-form-item prop="username" v-if="loginTitle === 0">
            <el-input
              ref="username"
              v-model="loginForm.username"
              type="text"
              size="small"
              name="username"
              placeholder="邮箱/用户名"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="password" v-if="loginTitle === 0">
            <el-input
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              size="small"
              name="password"
              placeholder="请输入密码"
              auto-complete="on"
              @keyup.enter.native="Login"
            >
              <svg-icon
                slot="suffix"
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                @click="showPwd"
              />
            </el-input>
          </el-form-item>
          <el-form-item prop="mobile" v-if="loginTitle === 1">
            <el-input
              ref="mobile"
              v-model="loginForm.mobile"
              type="text"
              size="small"
              style="width: 223px"
              name="mobile"
              placeholder="请输入手机号码"
              auto-complete="on"
            />
            <el-button
              class="code"
              type="danger"
              size="small"
              :disabled="countDown > 0"
              plain
              @click.native.prevent="getCode"
              >{{ countDown > 0 ? `${countDown}s` : "获取验证码" }}</el-button
            >
          </el-form-item>
          <el-form-item prop="code" v-if="loginTitle === 1">
            <el-input
              ref="code"
              v-model="loginForm.code"
              type="text"
              size="small"
              name="code"
              placeholder="请输入验证码"
              auto-complete="on"
            />
          </el-form-item>

          <el-button
            type="danger"
            size="small"
            class="login-btn"
            :loading="loading"
            @click.native.prevent="Login"
            >登录</el-button
          >
          <div class="link">
            <span class="link-item" @click="toPage('forget')">忘记密码</span>
            <span class="link-item" @click="toPage('register')">免费注册</span>
          </div>
        </el-form>
        <el-form
          ref="mobileForm"
          class="login-form mobileForm"
          :model="mobileForm"
          :rules="mobileRules"
          auto-complete="on"
          label-position="left"
          v-if="formFlog===1"
        >
          <el-form-item prop="zmobile">
            <el-input
              ref="zmobile"
              v-model="mobileForm.zmobile"
              type="text"
              size="small"
              class="mobileItem"
              name="zmobile"
              placeholder="请输入手机号码"
              auto-complete="on"
              ><span slot="prefix" class="solt">手机号码</span></el-input
            >
          </el-form-item>
          <el-form-item prop="zcode">
            <el-input
              ref="zcode"
              v-model="mobileForm.zcode"
              type="text"
              size="small"
              class="mobileItem"
              style="width: 223px"
              name="zcode"
              placeholder="请输入验证码"
              auto-complete="on"
              ><span slot="prefix" class="solt">验证码</span></el-input
            >
            <el-button
              class="code"
              type="danger"
              size="small"
              :disabled="countDown > 0"
              plain
              @click.native.prevent="getZCode"
              >{{ countDown > 0 ? `${countDown}s` : "获取验证码" }}</el-button
            >
          </el-form-item>
          <div class="agree">
            <el-checkbox v-model="mobileForm.checked"
              >点击“下一步”按钮将视为您已阅读并同意</el-checkbox
            >
            <span class="link-item" @click="toPage('protocol')"
              >《注册协议》</span
            >
          </div>
          <el-button
            type="danger"
            size="small"
            class="next-btn"
            @click.native.prevent="Next"
            >下一步</el-button
          >
        </el-form>
      </div>
      <!-- <div class="login">
        <p>手机验证<i class="el-icon-close" @click="close" style="position:none"></i></p>
        <div></div>
      </div> -->
    </transition>
  </div>
</template>

<script>
import { request, enPassword } from "@/utils/request";
import { setToken } from "@/utils/token";
import { validPwd, validMobile, validCode } from "@/utils/validate";

export default {
  name: "Login",
  props: {
    loginShow: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    const validatePwd = (rule, value, callback) => {
      if (value) {
        if (!validPwd(value)) {
          callback(new Error("6~18位，只能包含字母、数字和下划线"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入密码"));
      }
    };
    const validateMobile = (rule, value, callback) => {
      if (value) {
        if (!validMobile(value)) {
          callback(new Error("请输入正确的手机号码"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入手机号码"));
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value) {
        if (!validCode(value)) {
          callback(new Error("验证码为6位数字"));
        } else {
          callback();
        }
      } else {
        callback(new Error("请输入验证码"));
      }
    };
    return {
      closeShow:true,
      countDown: "00",
      loginTitle: 0,
      formFlog:0,
       index:0,
      mobileFlog:'',
      loginForm: {
        username: "",
        password: "",
        mobile: "",
        code: "",
      },
      mobileForm: {
        zmobile: '',
        zcode: '',
        checked:''
      },
      loginRules: {
        username: [
          { required: true, message: "请输入邮箱/用户名", trigger: "blur" },
        ],
        password: [{ required: true, trigger: "blur", validator: validatePwd }],
        mobile: [
          { required: true, trigger: "blur", validator: validateMobile },
        ],
        code: [{ required: true, trigger: "blur", validator: validateCode }],
      },
      mobileRules:{
        zmobile: [
          { required: true, trigger: "blur", validator: validateMobile },
        ],
        zcode: [{ required: true, trigger: "blur", validator: validateCode }],
      },
      
      loading: false,
      passwordType: "password",
    };
  },
  methods: {
    close() {
      this.$emit("putLogin", false);
    },
    showPwd() {
      this.passwordType =
        this.passwordType === "password" ? "text" : "password";
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    theLast() {
      this.countDown = 60;
      const timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
          this.countDown < 10 && (this.countDown = "0" + this.countDown);
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
    getCode() {
      if (this.countDown > 0) return this.$message.error("请不要频繁点击!");
      if (!this.loginForm.mobile) return this.$message.error("请输入手机号码!");
      if (!validMobile(this.loginForm.mobile))
        return this.$message.error("请输入正确的手机号码!");
      const params = {
        transCode: "A00001",
        mailOrPhone: this.loginForm.mobile,
        type: "3",
        channel: '1',
      };
      request(params)
        .then((res) => {
          this.$message.success(
            `验证码已发送至手机号： ${this.loginForm.mobile} ,请注意查收！`
          );
          this.theLast();
        })
        .catch((err) => {});
    },
    getZCode() {
      if (this.countDown > 0) return this.$message.error("请不要频繁点击!");
      if (!this.mobileForm.zmobile) return this.$message.error("请输入手机号码!");
      if (!validMobile(this.mobileForm.zmobile))
        return this.$message.error("请输入正确的手机号码!");
      const params = {
        transCode: "A00001",
        mailOrPhone: this.mobileForm.zmobile,
        type: this.mobileFlog,
        channel: '1',
      };
      request(params)
        .then((res) => {
          this.$message.success(
            `验证码已发送至手机号： ${this.mobileForm.zmobile} ,请注意查收！`
          );
          this.theLast();
        })
        .catch((err) => {});
    },
    loginTob(type){
      this.index=type;
      this.loginTitle=type
      this.$refs.loginForm.clearValidate()
      this.loginForm={
        username: "",
        password: "",
        mobile: "",
        code: "",
      }
    },
    Next(){
      this.$refs.mobileForm.validate((valid) => {
          if (valid) {
            if (this.mobileForm.checked) {
              let param={
                transCode: "A00008",
                authCode:this.mobileForm.zcode,
                phoneNo:this.mobileForm.zmobile,
              };
              request(param)
                .then(res=>{
                  this.$message.success("登录成功!");
                  this.loginForm.password = "";
                  this.loading = false;
                  this.formFlog=0
                  this.close();
                })
                .catch(err=>{})
            } else {
              this.$alert('请仔细阅读《注册协议》，并同意！', '提示', {
                confirmButtonText: '确定',
                callback: (action) => {},
              })
            }
          } else {
            return false
          }
        })
    },
    getUserData(){
      let param={
        transCode: "B00001",
      };
      request(param)
        .then(res=>{
          if(res.mobileNo&&res.userType==='2'&&this.loginTitle === 0){
            this.mobileForm.zmobile=res.mobileNo
            this.mobileFlog='5'
            this.formFlog=1
            this.closeShow=false
            return
          }
          if(!res.mobileNo&&res.userType==='0'){
            this.mobileFlog='6'
            this.formFlog=1
            this.closeShow=false
            return
          }
              this.$message.success("登录成功!");
              this.loginForm.password = "";
              this.loading = false;
              this.close();
        })
        .catch(err=>{})
    },
    Login() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let params =
            this.loginTitle === 0
              ? {
                  transCode: "A00002",
                  userName: this.loginForm.username,
                  authCode: "",
                  password: enPassword(this.loginForm.password),
                  type: "",
                }
              : {
                  transCode: "A00002",
                  userName: "",
                  authCode: this.loginForm.code,
                  password: "",
                  type: "0",
                  phoneNo: this.loginForm.mobile,
                };
          request(params)
            .then((res) => {
              sessionStorage.setItem("userRole", res.userRole);
              this.$store.dispatch("user/changeState", {
                key: "token",
                value: res.clientToken,
              });
              this.$store.dispatch("user/changeState", {
                key: "name",
                value: res.nickName,
              });
              this.$store.dispatch("user/changeState", {
                key: "userId",
                value: res.userId,
              });
              this.$store.dispatch("user/changeState", {
                key: "userType",
                value: res.userType,
              });
              this.$store.dispatch("user/changeState", {
                key: "realStatus",
                value: res.authenticationState,
              });
              this.$store.dispatch("user/changeState", {
                key: "cfdUrl",
                value: res.cfdUrl,
              });
              this.$store.dispatch("user/changeState", {
                key: "userRole",
                value: res.userRole,
              });
              this.$store.dispatch("user/changeState", {
                key: "loginStatus",
                value: true,
              });
              // this.$store.dispatch("user/changeState", {
              //   key: "mobileNo",
              //   value: res.mobileNo,
              // });
              setToken(res.clientToken);
              this.getUserData()
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          return false;
        }
      });
    },
    toPage(type) {
      this.$emit("putLogin", { type: type });
      if (type == 'protocol') {
        this.$router.push('/protocol')
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
@import "@/styles/mixin.scss";

.marsk-fade-enter-active,
.marsk-fade-leave-active {
  transition: all 0.5s;
}
.marsk-fade-enter,
.marsk-fade-leave-to {
  opacity: 0;
}
div /deep/.mobileItem .el-input__inner{
    text-indent: 3em;
  }
.marsk {
  @include position(fixed, 0, 0, 0, 0, 1000);
  background: rgba(4, 112, 204, 0.05);
}
.title {
   padding-bottom: 20px;
}
.active{
  color:#F56C6C;
  border-bottom: 1px solid #F56C6C;
}

.slide-fade-enter-active {
  transition: all 0.3s ease;
}
.slide-fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.8, 1);
}
.slide-fade-enter,
.slide-fade-leave-to {
  transform: translateY(7.48rem);
}
.loginTitle {
  display: flex;
  justify-content: space-around;
  h3:hover {
    // text-decoration: underline;
    color: #F56C6C ;
    cursor: pointer;
  }
}

.login {
  @include position(fixed, 40%, auto, 50%, auto, 1001);
  @include w_h(400px);
  transform: translate(-50%, -50%);
  font-size: 12px;
  line-height: 22px;
  color: $color_3;
  background: $color_f;
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 0 7px 7px rgba(0, 0, 0, 0.4);
  .el-icon-close {
    @include position(absolute, 15px, auto, auto, 14px, 1001);
    font-size: 16px;
    color: $color_9;
    transition: all 0.3s;
    &:hover {
      cursor: pointer;
      color: $color_on;
    }
  }
  &-form {
    @include w_h();
    padding: 60px 40px;
    .title {
      margin-bottom: 30px;
      font-size: 20px;
      text-align: center;
    }
    .solt {
      padding: 0 6px;
      font-size: 12px;
      color: $color_6;
    }
    .login-btn {
      margin: 10px auto 30px;
      @include w_h();
    }
    .link {
      @include flex(center);
      color: $color_9;
      .link-item {
        margin: 0 10px;
        &:hover {
          cursor: pointer;
          color: $color_on;
        }
      }
    }
  }
  .agree {
      text-align: left;
      font-size: 12px;
      .link-item {
        color: #409eff;
        &:hover {
          cursor: pointer;
          text-decoration: underline;
        }
      }
    }
    .next-btn {
      margin: 30px auto 0px;
      @include w_h();
    }
  
  .steps {
    @include w_h(100%, 40px);
    line-height: 40px;
    text-align: center;
    color: #fff;
    background: #004498;
    .on {
      color: $color_f;
    }
    position: absolute;
  }
}
</style>

<style lang="scss">
@import "@/styles/variables.scss";
@supports (-webkit-mask: none) and (not (cater-color: $color_9)) {
  .login-form .el-input input {
    font-size: 12px;
    color: $color_9;
  }
}
.login-form {
  .el-input {
    &__inner:focus {
      border-color: $color_9;
    }
  }
}
</style>

