<template>
  <el-form
    ref="loginForm"
    class="login-form"
    status-icon
    :rules="loginRules"
    :model="loginForm"
    label-width="0"
  >
    <el-form-item prop="phone">
      <el-input
        v-model="loginForm.phone"
        size="small"
        auto-complete="off"
        :placeholder="$t('ec.login.phone')"
        :readonly="readonly"
      >
        <i
          slot="prefix"
          class="fa fa-user-o"
        />
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        size="small"
        :type="passwordType"
        auto-complete="off"
        :placeholder="$t('ec.login.pwd.new')"
      >
        <i
          slot="suffix"
          class="el-icon-view el-input__icon"
          @click="showPassword('passwordType')"
        />
        <i
          slot="prefix"
          class="el-icon-lock"
        />
      </el-input>
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input
        v-model="loginForm.confirmPassword"
        size="small"
        :type="confirmPasswordType"
        auto-complete="off"
        :placeholder="$t('ec.login.pwd.confirm')"
      >
        <i
          slot="suffix"
          class="el-icon-view el-input__icon"
          @click="showPassword('confirmPasswordType')"
        />
        <i
          slot="prefix"
          class="el-icon-lock"
        />
      </el-input>
    </el-form-item>

    <el-form-item prop="code">
      <el-input
        v-model="loginForm.code"
        size="small"
        auto-complete="off"
        :placeholder="$t('ec.login.code')"
        @keyup.enter.native="handleSubmit"
      >
        <i slot="prefix" class="fa fa-shield" />
        <el-button slot="append" size="mini" type="primary" :disabled="!canClick" @click="sendCode">{{ sendText }}</el-button>
      </el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        :style="`background:${defaultTheme}`"
        type="primary"
        size="small"
        class="login-submit"
        :loading="loading"
        @click.native.prevent="handleSubmit"
      >{{ $t('ec.login.pwd.confirmModify') }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import config, {password} from '@/settings'
// import { getCaptcha } from 'ecip-web/api/user'
import { changePwdSmsCode, validateSmsCodeChangePwd } from 'ecip-web/api/user'

export default {
  name: 'CodePwd',
  props: [],
  data() {
    return {
      sendText: this.$t('ec.login.sendCode'),
      readonly: true,
      canClick: true,
      wait: 60,
      loading: false,
      enableTenant: config.enableTenant,
      loginCaptcha: config.loginCaptcha,
      loginForm: {
        // 租户ID
        tenantId: '000000',
        // 用户名
        phone: '',
        // 旧密码
        oldPassword: '',
        // 新密码
        password: '',
        // 确认密码
        confirmPassword: '',
        // 账户类型
        type: 'account',
        // 验证码的值
        code: '',
        // 验证码的索引
        key: '',
        // 预加载白色背景
        image: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
      },
      loginRules: {
        phone: [
          { required: true, message: this.$t('ec.login.usernameEmpty'), trigger: 'blur' }
        ],
        code: [
          { required: true, message: this.$t('ec.login.codeEmpty'), trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: this.$t('ec.login.pwd.oldEmpty'), trigger: 'blur' }
        ],
        password: [
          { required: true, message: this.$t('ec.login.pwd.newEmpty'), trigger: 'blur' },
          { validator: this.validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: this.$t('ec.login.pwd.confirmEmpty'), trigger: 'blur' },
          { validator: this.validateConfirm, trigger: 'blur' }
        ]
      },
      oldPasswordType: 'password',
      passwordType: 'password',
      confirmPasswordType: 'password',
      redirect: undefined,
      otherQuery: {}
    }
  },
  computed: {
    defaultTheme() {
      return this.$store.state.settings.defaultTheme
    },
    curUsername() {
      return this.$store.state.user.username
    },
    curPhone() {
      return this.$store.state.user.userInfo && this.$store.state.user.userInfo.phone
    },
    userId() {
      return this.$store.state.user.id
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query
        if (query) {
          this.redirect = query.redirect
          this.otherQuery = this.getOtherQuery(query)
        }
      },
      immediate: true
    }
  },
  created() {
  },
  mounted() {
    this.loginForm.phone = this.curPhone || ''
    this.readonly = this.userId !== ''
  },
  methods: {
    async sendCode() {
      const loading = this.$loading({
        lock: true,
        text: this.$t('ec.login.wait'),
        spinner: 'el-icon-loading'
      })
      try {
        await changePwdSmsCode({ phone: this.loginForm.phone })
      } finally {
        loading.close()
      }
      this.$notify.success(this.$t('ec.login.sendSuccess'))
      if (!this.canClick) return
      this.canClick = false
      this.sendText = this.wait + this.$t('ec.login.resendCodeAfter')
      const clock = window.setInterval(() => {
        this.wait--
        this.sendText = this.wait + this.$t('ec.login.resendCodeAfter')
        if (this.wait < 0) {
          window.clearInterval(clock)
          this.sendText = this.$t('ec.login.resendCode')
          this.wait = 3
          this.canClick = true // 这里重新开启
        }
      }, 1000)
    },
    validateNewPassword(rule, value, callback) {
      if (config.password.same === false && this.loginForm.phone === value) {
        callback(new Error(this.$t('ec.login.pwd.sameError')))
        return
      }
      if (config.password && config.password.reg) {
        if (!config.password.reg.test(value)) {
          callback(new Error(this.$t(config.password.msg) || this.$t('ec.login.pwd.regError') + config.password.reg))
          return
        }
      } else {
        if (value && value.length > 0 && value.length < 6) {
          callback(new Error(this.$t('ec.login.pwd.lengthError')))
          return
        }
      }
      callback()
    },
    validateConfirm(rule, value, callback) {
      if (!this.loginForm.password) {
        callback()
        return
      }
      if (!value) {
        callback(new Error(this.$t('ec.login.pwd.confirmEmpty')))
      } else if (value !== this.loginForm.password) {
        callback(new Error(this.$t('ec.login.pwd.confirmError')))
      } else {
        callback()
      }
    },
    showPassword(passwordType) {
      this[passwordType] === ''
        ? (this[passwordType] = 'password')
        : (this[passwordType] = '')
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== 'redirect') {
          acc[cur] = query[cur]
        }
        return acc
      }, {})
    },
    handleSubmit() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          const loading = this.$loading({
            lock: true,
            text: this.$t('ec.login.wait'),
            spinner: 'el-icon-loading'
          })
          validateSmsCodeChangePwd({ userId: this.userId, phone: this.loginForm.phone, code: this.loginForm.code,
            loginPwd: this.loginForm.password }).then(res => {
            if (!res.success) {
              this.$notify({ message: res.message, type: 'error', offset: 50,
                duration: 2 * 1000 })
              return
            }
            // this.$notify({ title: '成功', message: '密码修改成功', type: 'success' })
            // debugger
            // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
            this.loading = false
            loading.close()
            this.$store.dispatch('user/resetToken').then(() => {
              this.$message({
                message: this.$t('ec.login.pwd.changeAndRelogin'),
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              }, 2000)
            })
            // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          }).catch(() => {
            this.loading = false
            loading.close()
            // this.$notify({ message: error.message, type: 'error', offset: 50,
            //   duration: 5 * 1000 })
          })
          // this.$store.dispatch('user/login', Object.assign({ enableTenant: config.enableTenant }, this.loginForm)).then(() => {
          //   this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
          //   this.loading = false
          //   loading.close()
          // }).catch(() => {
          //   this.loading = false
          //   loading.close()
          // })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style>
</style>
