<template>
  <el-dialog
    v-el-drag-dialog
    :title="$t('ec.navbar.changePwd')"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :append-to-body="true"
  >
    <el-form
      ref="dataForm"
      :model="dataForm"
      :rules="dataRule"
      label-width="150px"
      @keyup.enter.native="dataFormSubmit()"
      @submit.native.prevent
    >
      <el-form-item :label="$t('ec.login.username')">
        <span>{{ userName }}</span>
      </el-form-item>
      <el-form-item :label="$t('ec.login.pwd.old')" prop="password">
        <el-input v-model="dataForm.password" type="password" />
      </el-form-item>
      <el-form-item :label="$t('ec.login.pwd.new')" prop="newPassword">
        <el-input v-model="dataForm.newPassword" type="password" />
      </el-form-item>
      <el-form-item :label="$t('ec.login.pwd.confirm')" prop="confirmPassword">
        <el-input v-model="dataForm.confirmPassword" type="password" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('ec.table.close') }}</el-button>
      <el-button type="primary" :loading="saveLoading" @click="dataFormSubmit()">{{ $t('ec.table.confirm') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
// import { clearLoginInfo } from 'ecip-web/utils'
import { password } from '@/settings'
import { changePwd } from 'ecip-web/api/vue/user/sysrUserApi'
export default {
  data() {
    const validateNewPassword = (rule, value, callback) => {
      if (password && password.reg) {
        const illegalChar = new RegExp('[<>]')
        if (illegalChar.test(value)) {
          callback(new Error(this.$t('ec.login.pwd.illegalError') + ': < or >'))
          return
        }
        if (password.same === false && this.userName === value) {
          callback(new Error(this.$t('ec.login.pwd.sameError')))
          return
        }
        if (!password.sameWithOld && this.dataForm.password === value) {
          callback(new Error(this.$t('ec.login.pwd.sameWithOldError')))
          return
        }
        if (!password.reg.test(value)) {
          callback(new Error(this.$t(password.msg) || this.$t('ec.login.pwd.regError') + password.reg))
          return
        }
      } else {
        if (value && value.length > 0 && value.length < 6) {
          callback(new Error(this.$t('ec.login.pwd.lengthError')))
          return
        }
      }
      callback()
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (this.dataForm.newPassword !== value) {
        callback(new Error(this.$t('ec.login.pwd.confirmError')))
      } else {
        callback()
      }
    }
    return {
      visible: false,
      saveLoading: false,
      dataForm: {
        password: '',
        newPassword: '',
        confirmPassword: ''
      },
      dataRule: {
        password: [
          { required: true, message: this.$t('ec.login.pwd.oldEmpty'), trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: this.$t('ec.login.pwd.newEmpty'), trigger: 'blur' },
          { validator: validateNewPassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: this.$t('ec.login.pwd.confirmEmpty'), trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    userName: {
      get() {
        return this.$store.state.user.username
      }
    },
    mainTabs: {
      get() {
        return this.$store.state.common.mainTabs
      },
      set(val) {
        this.$store.commit('common/updateMainTabs', val)
      }
    }
  },
  methods: {
    // 初始化
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate(async(valid) => {
        if (valid) {
          try {
            this.saveLoading = true
            await changePwd({ oldPassword: this.dataForm.password, loginPwd: this.dataForm.newPassword })
            this.$notify.success(this.$t('ec.login.pwd.changeSuccess'))
            // 登出
            this.visible = false
            this.$nextTick(async() => {
              this.mainTabs = []
              // clearLoginInfo()
              // this.$router.replace({ name: 'login' })
              await this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            })
          } finally {
            this.saveLoading = false
          }
          //
          // this.$http({
          //   url: '/sys/user/savePwd',
          //   method: 'post',
          //   data: {
          //     'oldPassword': this.dataForm.password,
          //     'newPassword': this.dataForm.newPassword
          //   }
          // }).then(({ data }) => {
          //   if (data && data.code === 0) {
          //     this.$message({
          //       message: '操作成功',
          //       type: 'success',
          //       duration: 1500
          //     })
          //     this.visible = false
          //     this.$nextTick(() => {
          //       this.mainTabs = []
          //       clearLoginInfo()
          //       this.$router.replace({ name: 'login' })
          //     })
          //   }
          // })
        }
      })
    }
  }
}
</script>

