<template>
  <div>
    <el-dialog
      top="100px"
      width="600px"
      :title="$t('Navigator.ChangePassword')"
      append-to-body
      :visible="passwordModifyVisible"
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="pwdForm"
        :model="pwdForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item :label="$t('Navigator.OldPassword')" prop="old">
          <el-input
            v-model="pwdForm.old"
            clearable
            type="password"
            :placeholder="$t('Navigator.PleaseEnterYourOldPassword')"
          ></el-input>
        </el-form-item>

        <el-form-item :label="$t('Navigator.NewPassword')" prop="new">
          <el-input
            v-model="pwdForm.new"
            clearable
            type="password"
            :placeholder="$t('Navigator.PleaseEnterANewPassword')"
          ></el-input>
        </el-form-item>

        <el-form-item
          :label="$t('Navigator.RepeatNewPassword')"
          prop="newRepeat"
        >
          <el-input
            v-model="pwdForm.newRepeat"
            clearable
            type="password"
            :placeholder="$t('Navigator.PleaseEnterTheNewPasswordAgain')"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="closeDialog">
          {{ $t('Common.Cancel') }}
        </el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t('Common.Confirm') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { encryptWithRsa } from '@/utils'
  import { updatePassword } from '@/api/user'
  import { validateOldPassword } from '@/api/uc.js'
  export default {
    name: 'PasswordModify',
    props: {
      accountInfo: {
        type: Object,
        default: null,
      },
      passwordModifyVisible: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      const checkOld = (rule, value, cb) => {
        if (value === '') {
          cb(new Error('请输入旧密码'))
        } else {
          cb()
        }
      }
      const checkNewRepeat = (rule, value, cb) => {
        if (value === '') {
          cb(new Error('请再次输入新密码'))
        } else if (value !== this.pwdForm.new) {
          cb(new Error('两次输入密码不一致!'))
        } else {
          cb()
        }
      }
      const checkNew = (rule, value, cb) => {
        if (value === '') {
          cb(new Error('请输入新密码'))
        }
        const { pwdStrategy: config } = this.userInfo
        if (config && config.enable == 1) {
          const { pwdRule, pwdLength } = config
          if (pwdRule) {
            if (value.length < pwdLength) {
              cb(new Error('新密码长度至少为' + pwdLength))
            } else if (pwdRule == 2) {
              var re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])')
              if (!re.test(value)) {
                cb(new Error('新密码必须包含数字、字母'))
              } else {
                cb()
              }
            } else if (pwdRule == 3) {
              var re = new RegExp('(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])')
              if (!re.test(value)) {
                cb(new Error('新密码必须包含数字、字母、特殊字符'))
              } else {
                cb()
              }
            } else if (pwdRule == 4) {
              var re = new RegExp(
                '(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[^a-zA-Z0-9])'
              )
              if (!re.test(value)) {
                cb(new Error('新密码必须包含数字、大小字母、特殊字符'))
              } else {
                cb()
              }
            } else {
              cb()
            }
          }
        } else {
          if (value.length < 6) {
            cb(new Error('新密码长度至少为6'))
          } else if (value === this.pwdForm.old) {
            cb(new Error('新密码不能与旧密码相同'))
          } else {
            cb()
          }
        }
      }
      const validateOldPwd = (rule, value, callback) => {
        const params = {
          oldPwd: encryptWithRsa(this.pwdForm.old),
        }
        validateOldPassword(params).then((res) => {
          if (res.value) {
            callback()
          } else {
            callback(new Error('请输入正确的密码'))
          }
        })
      }
      return {
        userInfo: {},
        pwdForm: {
          old: '',
          new: '',
          newRepeat: '',
        },
        rules: {
          old: [
            { validator: checkOld, trigger: 'blur' },
            { validator: validateOldPwd, trigger: 'blur' },
          ],
          new: [{ validator: checkNew, trigger: 'blur' }],
          newRepeat: [{ validator: checkNewRepeat, trigger: 'blur' }],
        },
      }
    },
    watch: {
      passwordModifyVisible(val) {
        if (val && this.accountInfo) {
          this.userInfo = this.accountInfo.user
        }
      },
    },
    methods: {
      closeDialog() {
        this.$emit('update:passwordModifyVisible', false)
      },
      submitForm() {
        this.$refs['pwdForm'].validate((valid) => {
          if (valid) {
            const jsonData = {
              oldPwd: encryptWithRsa(this.pwdForm.old),
              newPwd: encryptWithRsa(this.pwdForm.new),
            }
            updatePassword(jsonData).then((res) => {
              if (res.state) {
                this.closeDialog()
                this.$message.success(res.message)
                setTimeout(() => {
                  this.$emit('logout')
                }, 300)
              } else {
                this.$message.error(res.message)
              }
            })
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped></style>
