<template>
  <div style="height: 1000px;background-color: #fff;" class="registerBox">
    <div class="header1">
      <div class="header2">
        <div class="logo">
          <img src="@/assets/img/home/LOGO2020-12-22.png" alt style="width: 330px;"/>
        </div>
        <!-- <div class="title">{{$i18n.locale == 'zh' ? 'GEIDCP 全球能源互联网发展合作平台' : 'GEIDCP'}}</div> -->
      </div>
    </div>
    <div
        style="width: 1200px;height: 700px;background-color: #fff;margin: auto;margin-top: 30px;position: relative;"
    >
      <div style="line-height: 100px;padding-left: 30px;color: #999;">
        {{ $t('common.resetpassword') }}
        <span style="float: right;margin-right: 20px;color:#2c558a ;">
          <el-button type="text" @click="locale('zh')">中文</el-button>
          <span> / </span>
          <el-button type="text" style="margin-right: 20px;" @click="locale('en')">EN</el-button>
          <span
              class="cursor"
              @click="toBack"
          >{{ $t('common.Returntologin') }}
          </span>
        </span>

      </div>
      <div class="crumbs" style="width: 80%;margin: auto;">
        <el-steps :active="active" align-center>
          <el-step :title="$t('common.Fillintheaccountname')"></el-step>
          <el-step :title="$t('common.Authentication')"></el-step>
          <el-step :title="$t('common.Setnewpassword')"></el-step>
          <el-step :title="$t('common.complete')"></el-step>
        </el-steps>
      </div>
      <div style="width: 500px;margin: auto;margin-top: 50px;">
        <el-form ref="form" :model="form" label-width="120px" v-if="active==0">
          <el-form-item :label="$t('common.mobilePhone')" v-if="!isTelLogin">
            <GlobalRoaming ref='GlobalRoaming' :size="{width:'460px'}" v-model="form.name"
                           @getAreaCode="getPassAreaCode"></GlobalRoaming>
          </el-form-item>
          <el-form-item :label="$t('common.Email')+':'" v-if="isTelLogin">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item :label="$t('common.VerificationCode')">
            <el-input v-model="form.verificationCode"></el-input>
          </el-form-item>
          <el-form-item>
            <div class="securityCode-out" style="overflow:hidden">
              <div id="randomCode" style="float: left;padding-right: 4px;">
                <img style="border-radius: 5px;" :src="url"/>
              </div>
              <div id="securityCode" style="font-size: 16px;color: #999;">
                {{ $t('common.invisibility?') }}
                <span style="color: #0099ff;" class="cursor" @click="refreshCaptcha"> {{ $t('common.Changeit') }}</span>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
          <span
              v-if="!isTelLogin"
              type="text"
              style="font-size:20px; color: rgba(80,141,231,1);"
              class="cursor"
              @click="isTelLogin = !isTelLogin"
          >{{ $t('common.PasswordResetByEmail') }}</span>
          </el-form-item>
          <el-form-item>
          <span
              v-if="isTelLogin"
              type="text"
              style="font-size:20px; color: rgba(80,141,231,1);"
              class="cursor"
              @click="isTelLogin = !isTelLogin"
          >{{ $t('common.PasswordResetByPhone') }}</span>
          </el-form-item>
        </el-form>
        <el-form ref="form2" :model="form2" label-width="120px" v-if="active==1">

          <el-form-item :label="$t('common.phonenumber')+'/'+$t('common.Email')+':'">
            <el-input v-model="form2.mobile" :readonly="true"></el-input>
          </el-form-item>
          <el-form-item :label="$t('common.VerificationCode')" style="position: relative;">
            <el-input v-model="form2.verificationCode"></el-input>
            <span style="position: absolute;right: 8px;top: 0;">
              <span
                  v-show="show"
                  @click="sendCode(form2)"
                  style="margin-left: 40px;"
                  class="getCode cursor"
              >{{ $t('common.Sendverificationcode') }}</span>
              <span
                  v-show="!show"
                  class="count"
                  style="margin-left: 20px;color: #999;"
              >{{ count }} {{ $t('common.resend') }}</span>
            </span>
          </el-form-item>
        </el-form>
        <el-form ref="form3" :model="form3" label-width="120px" v-if="active==2">
          <el-form-item :label="$t('common.Newpassword')+':'">
            <el-input v-model="form3.passWord" show-password></el-input>
          </el-form-item>
          <el-form-item :label="$t('common.Repeatpassword')+':'" style="position: relative;">
            <el-input v-model="form3.confirmPassword" show-password></el-input>
          </el-form-item>
        </el-form>
        <el-form
            ref="form3"
            :model="form4"
            label-width="120px"
            v-if="active==3"
            style="margin-top: 100px;margin-left: -140px;"
        >
          <el-form-item>
            <i class="el-icon-mobile" style="font-size:65px;color:#0099ff;margin-left: 222px;"></i>
            <div style="text-align: center;color:#0099ff;line-height: 25px;font-size: 22px;">
              {{ $t('common.Passwordresetsuccessful') }}
            </div>
            <div style="text-align: center;color:#0099ff;line-height: 26px;">
              {{ $t('common.Pleaseloginagainwithnewpassword') }}
            </div>
          </el-form-item>
        </el-form>
        <div style="margin-top: 30px;" v-if="active!==3">
          <el-button type="primary" @click="onSubmit" style="width: 384px;float: right;">{{ $t('common.NextBu') }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Base from "@/views/base/Base";
import axios from "axios";
import {getMobileSmsCode, getCaptcha} from "@/api/user";
import {getUserInfoByTel1, sendPhoneCode, updatePwdLogout} from "@/api/login";
import {setPwd} from "@/api/user";
import {getToken} from "@/api/token.js";
import GlobalRoaming from "@/components/GlobalRoaming";

export default {
  name: "PasswordReset",
  extends: Base,
  components: {
    GlobalRoaming
  },
  data() {
    return {
      select: "0086",
      isTelLogin: true,
      active: 0,
      show: true,
      count: "",
      timer: null,
      userInfo: [],
      codeFromTel: "",
      isSendCode: false,
      service: "",
      lang: window.localStorage.getItem("locale"),
      form: {
        name: "",
        verificationCode: "",
        names: ''
      },
      form2: {
        mobile: "",
        verificationCode: "",
      },
      form3: {
        passWord: "",
        confirmPassword: "",
      },
      url: "",
    };
  },
  mounted() {
    // let userId = this.$store.getters["user/isLogin"];
    let userId = this.$Cookies.get('token')
    if (userId) {
      this.logOut();
    }
    this.refreshCaptcha();
  },
  watch: {
    //  "isTelLogin":function(value){
    //      if(value){

    //      }else{

    //      }
    //  },
    active() {
      if (this.active == 3) {
        setTimeout(() => {
          this.toBack();
        }, 2000);
      }
    },
  },
  methods: {
    locale(lang) {
      this.$i18n.locale = lang
      let locale = window.localStorage.getItem('locale')
      if (locale) {
        window.localStorage.setItem('locale', lang)
      } else {
        window.localStorage['locale'] = lang;
      }
      this.language = window.localStorage.getItem('locale');
      this.lang = window.localStorage.getItem('locale');
      // this.$bus.emit('setLang', window.localStorage.getItem("locale"))
      console.log(window.localStorage.getItem('locale'))
    },
    getPassAreaCode(code) {
      this.select = code;
      console.log("select=" + this.select);
    },
    refreshCaptcha() {
      getCaptcha(this.codeUid).then((response) => {
        this.codeUid = response["headers"]["captcha-uid"];
        let data = response.data;
        if (data.size == 0) {
          return;
        }
        let reader = new FileReader();
        reader.onload = (e) => {
          this.url = e.target.result || "";
        };
        reader.readAsDataURL(data);
      });
    },
    // 得搜索国家首字母
    getCountrySearchs(item, index) {
      this.getSearchs = item;
    },
    toBack() {
      this.$router.go(-1);
    },
    login: function () {
      if (this.loginType == 1) {
        this.accountPasswordLogin();
      } else {
        this.mobileLogin();
      }
    },
    onSubmit() {
      if (this.active == 0) {
        //校验用户是否存在。
        this.getUserInfo();
      } else if (this.active == 1) {
        //请输入验证码
        if (!this.form2.verificationCode) {
          this.$message.warning(this.$t('common.Pleaseenterverification'));
          return;
        }
        //后台自动登录，获取token值
        this.codeLogin();
      } else if (this.active == 2) {
        //设置新密码
        this.resetPass();
      } else if (this.active == 3) {
        var interval = setInterval(() => {
          location.reload();
          clearInterval(interval);
        }, 2000);
      }
    },
    codeLogin: function () {
      if (!this.isTelLogin) {
        this.service = "TX";
      } else {
        this.service = "YJ";
      }
      let locale = window.localStorage.getItem('locale');
      let myList = new Array(this.form2.mobile, locale);
      let names = myList.join(',');
      try {
        this.submitHandler((token) => {
          this.$store
              .dispatch("user/MOBILE_LOGIN", {
                mobile: names,
                checkCode: this.form2.verificationCode,
                service: this.service,
                token: token,
              })
              .then(() => {
                this.active++;
              })
              .catch((error) => {
                this.$message.error(error.msg);
              });
        }, false);
      } catch (err) {
        console.log(err);
      }
    },
    verificationTel: function (name) {
      //验证手机、邮箱合法性
      const regPhone = /^(0|86|17951)?(13[0-9]|15[1-9]|16[6]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (regEmail.test(name) || regPhone.test(name)) {
        return true;
      } else {
        this.$message.warning(this.$t('common.Pleaseenteravalidmobilephonenumberoremail') + "!");
        return false;
      }
    },
    getUserInfo: function () {
      if (!this.form.name) {
        this.$message.warning(this.$t('common.Phoneandemailcannotbeempty'));
        return;
      }
      if (!this.form.verificationCode) {
        this.$message.warning(this.$t('common.Verificationcodecannotbeempty'));
        return;
      }
      //校验手机号/邮箱/验证码格式
      if (!this.verificationTel(this.form.name)) {
        return false;
      }
      if (!this.isTelLogin) {
        this.form.names = this.select + this.form.name
      }
      //获取当前登录手机号的用户信息
      getUserInfoByTel1(!this.isTelLogin ? this.form.names : this.form.name, this.form.verificationCode, this.codeUid, this.$i18n.locale)
          .then((result) => {
            if (
                result.status == 200 && result.data != null && result.data != ""
            ) {
              // this.userInfo = result.data;
              this.form2.mobile = !this.isTelLogin ? this.form.names : this.form.name;
              this.active++;
            }
          })
          .catch((error) => {
            // this.msg(this.$t("common.userdoesnotexist") + "！", "error");
            this.msg(error.msg, "error");
            this.refreshCaptcha();
          });
    },
    async resetPass() {
      let userId = this.$store.getters["user/isLogin"];
      if (userId == "") {
        this.$message.warning(this.$t('common.ThesystemisbusyPleasetryagainlater'));
        return;
      }
      if (this.form3.passWord == "" || this.form3.passWord == null) {
        this.$message.warning(this.$t('common.Newpasswordcannotbeempty'));
        return;
      }
      if (
          this.form3.confirmPassword == "" ||
          this.form3.confirmPassword == null
      ) {
        this.$message.warning(this.$t('common.Confirmpasswordcannotbeempty'));
        return;
      }
      //判断两次密码是否一致
      if (this.form3.passWord != this.form3.confirmPassword) {
        this.$message.warning(this.$t('common.Thetwopasswordsarenotthesame'));
        return;
      }
      //校验密码格式
      var msg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/.test(this.form3.confirmPassword)
          ? ""
          : $t('common.Yourpasswordstrengthistoolow');
      debugger
      if (msg != "") {
        return this.$message({
          message: msg,
          type: "warning",
        });
      }
      let token = getToken();
      let param = {};
      param.id = userId;
      param.password = this.form3.confirmPassword;
      await setPwd(JSON.stringify(param), token)
          .then((result) => {
            if (result.status == 200) {
              this.$message({
                message: this.$t('common.Passwordchangedsuccessfully') + "！",
                type: "success",
              });
              this.dialogVisible = false;
              this.active++;
            }
          })
          .catch((error) => {
            this.msg(error.msg, "error");
          });
      await this.logOut();
    },
    logOut: function () {
      // 退出的逻辑代码
      this.$store
          .dispatch("user/LOGOUT")
          .then(() => {
          })
          .catch((error) => {
            /* this.$message({
                    type: 'error',
                    message: error.msg
                });*/
          });
    },
    toView(router, json) {
      this.$router.push({name: router, params: json});
    },
    async sendCode() {
      // const {data: res} = await this.$http.get(`/userRegisterAndLogin/sendCode`)
      this.form2.mobile = !this.isTelLogin ? this.form.names : this.form.name;
      let mobile = "";
      if (!this.isTelLogin) {
        mobile = this.form.name.substring(4)
      } else {
        mobile = this.form.name;
      }
      //验证手机号合法性
      // const regPhone = /^(0|86|17951)?(13[0-9]|15[123456789]|16[6]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      const regEmail = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/;
      if (!this.isTelLogin) {
        this.service = "TX";
      } else {
        this.service = "YJ";
      }
      //发送验证码 判断当前是手机号还是邮箱号  短信：service：“TX"   邮件：service：“YJ
      await sendPhoneCode(this.form2.mobile, this.service, this.$i18n.locale)
          .then((result) => {
            this.isSendCode = true;
            this.msg(result.msg, "success");
          })
          .catch((error) => {
            this.msg(error.msg, "error");
          });
      //倒计时
      const TIME_COUNT = 60;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
    },
    msg: function (msg, type) {
      if (msg == "error") {
        msg = this.$t('common.ThesystemisbusyPleasetryagainlater');
      }
      return this.$message({
        message: msg,
        type: type,
      });
    },
    //次方法用于测试
    testMethod() {
      axios
          .get("./userRegisterAndLogin/sendCode/", {
            params: {
              telNum: 666,
            },
          })
          .then((res) => {
            console.log(res);
          })
          .catch((error) => {
            console.log(error);
            alert(this.$t('common.Networkerror'));
          });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.getSearchs1 {
  color: #0c27ff;
}

.getSearchs2 {
  color: #d12910;
}

.header1 {
  width: 100%;
  height: 120px;
  margin: auto;
  background: #2c558a;
  /* border-bottom: 2px solid #c2c2c2; */
}

.header2 {
  width: 1200px;
  height: 120px;
  margin: auto;
  position: relative;
  border-bottom: 1px solid #fff;
  /* background: skyblue; */
}

.language {
  line-height: 50px;
  color: #ccc;
  font-weight: 400;
  font-size: 12px;
}

.logo {
  position: absolute;
  top: 30px;
  left: 80px;
  width: 260px;
  height: 55px;
  /* background-image: url(@/assets/logo.png); */
}

.title {
  position: absolute;
  top: 40px;
  left: 450px;
  font-size: 30px;
  font-weight: 700;
  color: #fff;
}

.crumbs >>> .el-step__icon {
  width: 37px;
  height: 37px;
  font-size: 18px;
}

.crumbs >>> .el-step.is-horizontal .el-step__line {
  top: 20px;
}

.crumbs >>> .el-step__head.is-process {
  color: #409eff;
  border-color: inherit;
}

.crumbs >>> .el-step__head.is-process .el-step__icon.is-text {
  background: #409eff;
  color: #fff;
  border-color: #409eff;
  width: 46px;
  height: 46px;
}

.crumbs >>> .el-step__title.is-process,
.crumbs >>> .el-step__description.is-process {
  color: #409eff;
}

.crumbs >>> .el-collapse-item {
  /* width: 80%; */
  margin: auto;
}

.el-collapse {
  border: none;
}

.crumbs >>> .el-collapse-item__header {
  padding: 0 20px 0 100px;
}

.crumbs >>> .el-collapse-item__wrap {
  padding: 0 0 0 100px;
}

.el-checkbox {
  display: block;
  margin-bottom: 20px;
}

.getCode :active {
  color: rgb(255, 0, 0);
}

.registerBox /deep/ .el-select {
  width: 150px;
}
</style>
