<template>
  <el-form
    ref="loginForm"
    class="login-form"
    status-icon
    :rules="loginRules"
    :model="loginForm"
    label-width="0"
  >
    <el-form-item prop="username">
      <el-input
        v-model="loginForm.username"
        size="small"
        auto-complete="off"
        :placeholder="$t('ec.login.username')"
        :readonly="readonly"
      >
        <i
          slot="prefix"
          class="fa fa-user-o"
        />
      </el-input>
    </el-form-item>
    <el-form-item prop="oldPassword">
      <el-input
        v-model="loginForm.oldPassword"
        size="small"
        :type="oldPasswordType"
        auto-complete="off"
        :placeholder="$t('ec.login.pwd.old')"
      >
        <i
          slot="suffix"
          class="el-icon-view el-input__icon"
          @click="showPassword('oldPasswordType')"
        />
        <i
          slot="prefix"
          class="el-icon-lock"
        />
      </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>
      <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 from '@/settings'
// import { getCaptcha } from 'ecip-web/api/user'
import { changePassword } from 'ecip-web/api/user'

export default {
  name: 'AccountPwd',
  props: [],
  data() {
    return {
      loading: false,
      readonly: true,
      enableTenant: config.enableTenant,
      loginCaptcha: config.loginCaptcha,
      loginForm: {
        // 租户ID
        tenantId: '000000',
        // 用户名
        username: '',
        // 旧密码
        oldPassword: '',
        // 新密码
        password: '',
        // 确认密码
        confirmPassword: '',
        // 账户类型
        type: 'account',
        // 验证码的值
        code: '',
        // 验证码的索引
        key: '',
        // 预加载白色背景
        image: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
      },
      loginRules: {
        tenantId: [
          { required: false, message: '请输入租户ID', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { validator: this.validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', 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.username = this.curUsername || ''
    this.readonly = this.userId !== ''
  },
  methods: {
    validateNewPassword(rule, value, callback) {
      if (config.password && config.password.reg) {
        if (config.password.same === false && this.loginForm.username === value) {
          callback(new Error(this.$t('ec.login.pwd.sameError')))
          return
        }
        if (!config.password.reg.test(value)) {
          callback(new Error(config.password.msg || `新密码不符合正则${config.password.reg}校验`))
          return
        }
      } else {
        if (value && value.length > 0 && value.length < 6) {
          callback(new Error('新密码长度不能小于6'))
          return
        }
      }
      callback()
    },
    validateConfirm(rule, value, callback) {
      if (!this.loginForm.password) {
        callback()
        return
      }
      if (!value) {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.loginForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } 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'
          })
          changePassword({ userId: this.userId, username: this.loginForm.username, oldPassword: this.loginForm.oldPassword, loginPwd: this.loginForm.password }).then(response => {
            // this.$notify({ title: '成功', message: '密码修改成功', type: 'success' })
            // this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
            this.loading = false
            loading.close()
            this.$store.dispatch('user/resetToken').then(() => {
              this.$message({
                message: '密码修改成功，即将跳转到登录页面，请重新登录',
                type: 'success',
                duration: 2000
              })
              setTimeout(() => {
                this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
              }, 2000)
              // this.$confirm('密码修改成功，请重新登录', '重新登录', {
              //   confirmButtonText: '重新登录',
              //   cancelButtonText: '取消',
              //   type: 'warning'
              // }).then(() => {
              //   location.reload()
              // })
            })
          }).catch(() => {
            this.loading = false
            loading.close()
          })
          // 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>
