<template>
  <div class="reset-password ">
    <div class="reset-password-container" :style="{ width: isTablet ? '100%' : '1400px' }">
      <img v-if="logo" :src="logo" class="reset-decoration-logo">
      <div class="reset-form-wrapper">
        <div v-if="result === ''">
          <div class="title">忘记密码</div>
          <MsgValidate ref="msgValidateRef">
            <template #password>
              <el-form ref="formRef" :model="resetForm" :rules="resetRules">
                <el-form-item prop="password" style="height:104px">
                  <el-input v-model="resetForm.password" type="password" placeholder="请输入新密码"/>
                  <div class="tips">密码长度必须为8～20位字符，由大写字母、小写字母、数字、特殊符号中的3种及以上类型组成</div>
                </el-form-item>
                <el-form-item prop="rePassword">
                  <el-input v-model="resetForm.rePassword" type="password" placeholder="请输入确认密码"/>
                </el-form-item>
              </el-form>
            </template>
          </MsgValidate>
          <!-- <el-form ref="formRef" :model="resetForm" :rules="resetRules" label-position="top">
          <el-row :gutter="40">
              <el-col>
                <div class="head">
                  <div class="title">找回密码</div>
                  <el-button type="text" @click="toLogin">直接登录</el-button>
                </div>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="phone" label="手机号码">
                  <el-input v-model="resetForm.phone" placeholder="请输入手机号码" maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="图形验证码" prop="captcha">
                  <div class="flex">
                    <el-input v-model="resetForm.captcha" maxlength="6" placeholder="请输入图形验证码"/>
                    <img :src="captchaImg" class="captch-img" alt="验证码" @click="fetchVerifyGraphic">
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="验证码" prop="smsCode">
                  <div class="flex">
                    <el-input v-model="resetForm.smsCode" maxlength="6" placeholder="请输入验证码"/>
                    <el-button :disabled="time > 0" type="primary" @click="getSmsCaptcha" class="sms-btn">{{ captchaBtnText }}</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          <el-row :gutter="40">
              <el-col>
                <div class="head" style="margin-top: 30px">
                  <div class="title">重置密码</div>
                </div>
              </el-col>
              <el-col :span="12">
                <el-form-item label="新密码" prop="password">
                  <el-input v-model="resetForm.password" type="password" placeholder="请输入新密码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="确认密码" prop="rePassword">
                  <el-input v-model="resetForm.rePassword" type="password" placeholder="请输入确认密码"/>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form> -->
          <el-button :loading="loading" type="primary" class="btn-reset" @click.native.prevent="reset">完成</el-button>
          <div><el-button type="text" @click="toLogin">去登录</el-button></div>

        </div>
        <ResetResult :result="result" v-if="result !== ''" />
      </div>
      <div class="version">Copyright 2017-2019 联通智网科技股份有限公司 版权所有 京ICP备16005440号-1</div>
    </div>
  </div>
</template>

<script>
// import { validPhone } from '@/utils/validate'
import { forgetPassword, getLoginSecretKey } from '@/api/user'
import ResetResult from './components/ResetResult.vue'
import { getJMJqueryParams } from '@/utils/sm4'
import MsgValidate from './components/MsgValidate.vue'
export default {
  name: 'ResetPassword',
  components: { ResetResult, MsgValidate },
  data() {
    // const validateUsername = (rule, value, callback) => {
    //   if (!validPhone(value)) {
    //     callback(new Error('请输入手机号码'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validatePassword = (rule, value, callback) => {
    //   if (value.length < 6) {
    //     callback(new Error('请输入短信验证码'))
    //   } else {
    //     callback()
    //   }
    // }
    // const validateCaptcha = (rule, value, callback) => {
    //   if (value.length !== 4) {
    //     callback(new Error('请输入验证码'))
    //   } else {
    //     callback()
    //   }
    // }
    const validateRePassword = (rule, value, callback) => {
      if (value !== this.resetForm.password) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      logo: this.$store.getters.logo,
      companyName: this.$store.getters.companyName,
      resetForm: {
        // phone: '',
        // captcha: '',
        // smsCode: '',
        password: '',
        rePassword: '',
        requestId: '',
        platformSource: 'Web'
      },
      resetRules: {
        // phone: [
        //   { required: true, message: '请输入手机号', trigger: 'blur' },
        //   { trigger: 'blur', validator: validateUsername }
        // ],
        // captcha: [
        //   { required: true, message: '请输入图形验证码', trigger: 'blur' },
        //   { trigger: 'blur', validator: validateCaptcha }
        // ],
        // smsCode: [
        //   { required: true, message: '请输入验证码', trigger: 'blur' },
        //   { trigger: 'blur', validator: validatePassword }
        // ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        rePassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { trigger: 'blur', validator: validateRePassword }
        ]
      },
      // 图片验证码
      // captchaImg: '',
      // // 请求图片验证码返回的请求id
      // requestId: '',
      // captchaBtnText: '发送验证码',
      // timer: null,
      // time: 0,
      loading: false,
      result: '',
      isTablet: window.OS.isTablet
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted() {
    // 默认查询图片验证码
    // this.fetchVerifyGraphic()
  },
  methods: {
    /**
     * 查询图片验证码
     */
    // async fetchVerifyGraphic() {
    //   // 获取图片验证码
    //   const { captchaImg, requestId } = await getGraphic({ platformSource: 'Web' })
    //   // 记录当前图片验证码
    //   this.captchaImg = captchaImg
    //   // 请求id
    //   this.requestId = requestId
    // },

    /**
     * 获取短信验证码
     */
    // getSmsCaptcha() {
    //   // 校验结果
    //   const validResult = []
    //   this.$refs.formRef.validateField(
    //     ['phone', 'captcha'],
    //     (errorMsg) => {
    //       if (!errorMsg) {
    //         validResult.push(errorMsg)
    //         // 没有校验完全
    //         if (validResult.length !== 2) {
    //           return
    //         }
    //         clearTimeout(this.timer)
    //         sendSmsCaptcha({
    //           phone: this.resetForm.phone,
    //           captchaImage: this.resetForm.captcha,
    //           requestId: this.requestId,
    //           platformSource: 'Web',
    //           tenantNo: this.$route.query.tenantNo
    //         }).then(data => {
    //           this.time = 60
    //           this.captchaBtnText = `${this.time - 1}S后重发`
    //           this.countdown()
    //         }).catch(() => {
    //           // 如果接口报错了，则刷新二维码
    //           this.fetchVerifyGraphic()
    //           this.captchaBtnText = '重新获取'
    //         })
    //       }
    //     })
    // },

    /**
     * 开始倒计时
     */
    // countdown() {
    //   this.timer = setTimeout(() => {
    //     if (this.time > 1) {
    //       this.time--
    //       this.captchaBtnText = `${this.time}S后重发`
    //       this.countdown()
    //     } else {
    //       this.time = 0
    //       clearTimeout(this.timer)
    //       this.captchaBtnText = '重新获取'
    //     }
    //   }, 1000)
    // },
    // 找回密码 下一步
    reset() {
      // 获取
      const msgParams = this.$refs.msgValidateRef.getData()
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          if (!msgParams) return
          const params = { ...this.resetForm, ...msgParams, ...{ smsCode: msgParams.sms }}// cloneDeep(this.resetForm)
          console.log(params, 'params')
          delete params.rePassword
          delete params.captcha
          delete params.sms
          this.loading = true
          await this.getSecretKey(params)
          forgetPassword(params)
            .then(() => {
              this.loading = false
              this.result = 'success'
            })
            .catch((error) => {
              // 连接似乎有问题，请检查网络
              if (error.code === 0) return (this.result = 'NetworkError')
              // 失败，清空验证码们，并重新获取图形验证码
              this.$refs.msgValidateRef.clearInit()
              this.$message.error({ message: error.message, type: 'error', duration: 5 * 1000 })
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    // 获取随机请求id-登录密码加密
    async getSecretKey(params) {
      try {
        const { requestId, secretKey } = await getLoginSecretKey()
        params.requestId = requestId
        params.password = getJMJqueryParams(params.password, secretKey)
      } catch (error) {
        // 连接似乎有问题，请检查网络
        error.code === 0 && (this.result = 'NetworkError')
      }
    },
    toLogin() {
      this.$router.push({ name: 'Login' })
    }
  }
}
</script>

<style lang="scss">
.reset-password {
  background-image: url(../../assets/img/login-bg.jpeg);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  min-height: 100%;
  width: 100%;
  overflow: hidden;

  .reset-password-container {
    background-repeat: no-repeat;
    background-size: 520px auto;
    background-position: right 770px center;
    padding: 70px;
    width: 1400px;
    height: 100vh;
    position: relative;
    margin: 0 auto;
    .reset-decoration-logo {
      background-image: url(../../assets/img/login-logo.svg);
      background-size: 100% 100%;
      width: auto;
      height: 42px;
    }
    .reset-form-wrapper {
      width: 426px;
      min-height: 585px;
      background: #FFFFFF;
      box-shadow: 0px 6px 27px 0px rgba(37, 48, 68, 0.08);
      border-radius: 8px;
      padding: 32px 70px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translateX(-50%) translateY(-50%);
      text-align: center;
      .head {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        height: 46px;
        padding-bottom: 24px;
        border-bottom: 1px dashed #EBEEF2;
        .title {
          font-size: 20px;
          font-weight: 600;
          color: #212026;
          line-height: 28px;
        }
        .to-login {
          font-size: 15px;
          font-weight: 400;
          color: #2A68FF;
          line-height: 22px;
        }
      }
      .captch-img {
        flex-shrink: 0;
        width: 90px;
        height: 32px;
        margin-left: 8px;
        cursor: pointer;
      }
      .sms-btn {
        width: 106px;
        height: 38px;
        margin-left: 8px;
      }
      .tips {
        font-size: 12px;
        font-weight: 400;
        color: #71747B;
        line-height: 17px;
        text-align: left;
        margin-top: 4px;
      }
      .btn-reset {
        display: block;
        background: #3269FF;
        border-radius: 4px;
        font-size: 16px;
        width: 286px;
        height: 44px;
        margin: 26px auto 0;
      }
    }

    .el-form-item {
      align-items: flex-end;
      display: flex;
      margin-bottom: 0px;
      height: 66px;
      .el-form-item__content {
        width: 100%;
      }

      .el-input__inner {
        box-shadow: none !important;
        border-bottom-left-radius: 0;
        border-bottom-right-radius: 0;
        border-top-width: 0;
        border-left-width: 0;
        border-right-width: 0;
        border-bottom-width: 1px;
        color: #393939;
        padding-left: 2px;
      }
    }

    .version {
      bottom: 40px;
      color: #758092;
      opacity: 0.5;
      font-size: 14px;
      text-align: center;
      font-weight: 400;
      position: absolute;
      left: 0px;
      right: 0px;
    }
    .flex {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
    }
  }

}
</style>
