<template>
  <el-form
    id="validatePasswordForm"
    ref="validatePasswordForm"
    class="dg-validate-password-form"
    :inline="inline"
    :model="sonFormData"
    :rules="rules"
    :label-width="labelWidth"
    :label-position="labelPosition"
  >
    <el-form-item v-if="sonFormData.hasOwnProperty('oldPassword')" label="旧密码：" prop="oldPassword">
      <el-input
        v-model="sonFormData['oldPassword']"
        :size="inputSize"
        type="password"
        maxlength="32"
        show-password
        @paste.native.capture.prevent="handleFalse"
        @copy.native.capture.prevent="handleFalse"
        @cut.native.capture.prevent="handleFalse"
      ></el-input>
    </el-form-item>
    <el-form-item v-if="captchaImage" label="验证码：" prop="captcha">
      <div class="captcha-row">
        <el-input
          v-model="sonFormData.captcha"
          placeholder="验证码"
          suffix-icon="glyphicon glyphicon-warning-sign form-control-feedback"
          :size="inputSize"
        ></el-input>
        <img
          alt="如果看不清楚，请单击图片刷新！"
          class="captcha-img"
          :style="{ height: { mini: '28px', small: '32px', large: '40px' }[inputSize] || '32px' }"
          :src="captchaImageSrc"
          @click="refreshCode"
        />
      </div>
    </el-form-item>
    <el-form-item label="新密码：" prop="password">
      <el-popover ref="password-popover" placement="right" width="400" trigger="focus">
        <template v-for="(tip, index) in validatorTips">
          <div :key="index" class="validator-tip">
            <i v-if="tip.type === 'success'" class="el-icon-success el-alert--success is-light"></i>
            <i v-if="tip.type === 'error'" class="el-icon-error el-alert--error is-light"></i>
            <i v-else></i>
            <span>{{ tip.text }}</span>
          </div>
        </template>
        <div class="safeness">
          安全程度：
          <span v-for="(span, index) in safenessArray" :key="index" :class="'el-button--' + span.type"></span>
          {{ safenessText }}
        </div>
      </el-popover>
      <el-input
        v-model="sonFormData['password']"
        v-popover:password-popover
        :size="inputSize"
        type="password"
        maxlength="32"
        show-password
        @paste.native.capture.prevent="handleFalse"
        @copy.native.capture.prevent="handleFalse"
        @cut.native.capture.prevent="handleFalse"
      ></el-input>
    </el-form-item>
    <el-form-item label="确认密码：" prop="passwordSure">
      <el-input
        v-model="sonFormData['passwordSure']"
        :size="inputSize"
        type="password"
        maxlength="32"
        show-password
        @paste.native.capture.prevent="handleFalse"
        @copy.native.capture.prevent="handleFalse"
        @cut.native.capture.prevent="handleFalse"
      ></el-input>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'DgValidatePasswordForm',
  props: {
    inline: {
      type: Boolean,
      default: () => false,
    },
    inputSize: {
      type: String,
      default: () => 'mini',
    },
    // rules: {
    //   type: Object,
    //   default: () => {}
    // },
    labelWidth: {
      type: String,
      default: () => '100px',
    },
    labelPosition: {
      type: String,
      default: () => '',
    },
    formData: {
      type: Object,
      default: () => {
        return {}
      },
    },
    captchaImage: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      visible: true,
      sonFormData: {},
      rules: {
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'blur' }],
        captcha: { required: this.captchaImage, message: '请输入验证码' },
        password: [{ required: true, trigger: ['change', 'blur'], validator: this.valiPassword }],
        passwordSure: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: this.valiPasswordSame },
        ],
      },
      validatorTips: [
        { text: '8~32个字符', type: '' },
        { text: '必须包含以下四种字符:大写字母、小写字母、数字、特殊字符~!@#$%^&*()-_=+|[{}];:\'",<.>/?', type: '' },
        { text: '不能与用户名或倒序的用户名相同', type: '' },
      ],
      safenessArray: [{ type: 'info' }, { type: 'info' }, { type: 'info' }],
      safenessText: '',
      checkArr: [
        {
          regexName: 'regexNum',
          value: /\d/,
        },
        {
          regexName: 'regexLower',
          value: /[a-z]/,
        },
        {
          regexName: 'regexUpper',
          value: /[A-Z]/,
        },
        {
          regexName: 'regexSpeChar',
          value: /[~!@#$%^&*()\-_=+\\|[{}\];:'",<.>/?]/,
        },
        // {
        //   regexName: 'regexSpace',
        //   value: /\s/
        // }
      ],
      captchaImageSrc: '',
    }
  },
  watch: {
    formData: {
      deep: true,
      handler: function (newVal) {
        this.sonFormData = newVal
      },
    },
    sonFormData: {
      deep: true,
      handler: function (newVal) {
        this.$emit('update:formData', newVal)
      },
    },
    captchaImage: {
      immediate: true,
      handler(val) {
        this.captchaImageSrc = val
      },
    },
  },
  created() {
    this.sonFormData = this.formData
    console.log(this)
  },
  methods: {
    handleFalse(e) {
      console.log(e)
    },
    // 校验密码
    valiPassword(rule, value, callback) {
      if (value) {
        let length = this.valiPasswordLength(value)
        let user = this.valiPasswordUser(value)
        let level = this.valiPasswordLevel(value)
        if (length && user && level) callback()
        else callback(new Error('密码设置不符合要求'))
      } else {
        this.validatorTips.forEach((tip) => {
          tip.type = ''
        })
        callback(new Error('密码设置不符合要求'))
      }
    },
    // 判断是否8～32位
    valiPasswordLength(value) {
      if (!/^.{8,32}$/.test(value)) {
        this.validatorTips[0].type = 'error'
        return false
      } else {
        this.validatorTips[0].type = 'success'
        return true
      }
    },
    // 判断是否是用户名或倒序的用户名
    valiPasswordUser(value) {
      if (value === this.sonFormData.userName || value === this.sonFormData.userName.split('').reverse().join('')) {
        this.validatorTips[2].type = 'error'
        return false
      } else {
        this.validatorTips[2].type = 'success'
        return true
      }
    },
    // 判断程度包含几种字符
    valiPasswordLevel(value) {
      let level = 0
      this.checkArr.forEach((item) => {
        if (item.value.test(value)) {
          level++
          console.log(item.regexName)
        }
      })
      console.log(level)
      if (level === 4) {
        this.validatorTips[1].type = 'success'
        this.safenessText = '高'
        this.safenessArray.forEach((safeness) => {
          safeness.type = 'success'
        })
        return true
      } else {
        this.validatorTips[1].type = 'error'
        if (level === 2) {
          this.safenessText = '低'
          this.safenessArray.forEach((safeness, index) => {
            if (index === 0) {
              safeness.type = 'danger'
              return
            }
            safeness.type = 'info'
          })
        } else if (level === 3) {
          this.safenessText = '中'
          this.safenessArray.forEach((safeness, index) => {
            if (index === 2) {
              safeness.type = 'info'
              return
            }
            safeness.type = 'warning'
          })
        } else {
          this.safenessText = ''
          this.safenessArray.forEach((safeness) => {
            safeness.type = 'info'
          })
        }
        return false
      }
    },
    // 校验确认密码
    valiPasswordSame(rule, value, callback) {
      if (value === this.sonFormData.password) callback()
      else callback(new Error('两次密码不相同'))
    },
    refreshCode() {
      this.captchaImageSrc = this.captchaImage + (this.captchaImage.includes('?') ? `&` : '?') + `t=${Math.random()}`
    },
  },
}
</script>
