<template>
  <a-form
    :form="form"
    :label-col="{ span: 5 }"
    :wrapper-col="{ span: 12 }"
    @submit="handleSubmitPassword"
  >
    <a-form-item label="当前密码">
      <a-input-password
        v-decorator="[
          'old_password',
          { rules: [{ required: true, message: '请输入当前密码' }, { validator: handleOldPass }] },
        ]"
        name="old_password"
      />
    </a-form-item>
    <a-form-item label="新密码" has-feedback>
      <a-input-password
        v-decorator="[
          'password',
          { rules: [{ required: true, message: '请输入新密码' }, { validator: handlePass }] },
        ]"
        name="password"
      />
    </a-form-item>
    <a-form-item label="确认新密码" has-feedback>
      <a-input-password
        v-decorator="[
          'confirm_password',
          {
            rules: [
              { required: true, message: '请输入确认新密码' },
              { validator: handleConfirmPass },
            ],
          },
        ]"
        name="confirm_password"
      />
    </a-form-item>
    <a-form-item :wrapper-col="{ span: 12, offset: 5 }">
      <a-button
        :class="$style.buttonclass"
        type="primary"
        :loading="isSubmitting"
        html-type="submit"
      >
        确定
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script>
import Vue from 'vue'
import { Message } from 'ant-design-vue'
import store from '@/common/store'
import { router } from '@/common/router-ready'
import loginService from '@/login/login-service'
import axios from '@/common/services/axios-instance'
import components from './_import-components/sd-change-password-import'
import PersonalCenterService from './personal-center-service'
import { getUserInfo } from '@/common/store-mixin'
Vue.use(Message)
const duration = 1
export default {
  name: 'SdChangePassword',
  components,
  props: {
    userinfoAccount: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      isSubmitting: false,
      oldpassword: '',
      password: '',
      form: this.$form.createForm(this),
      userinfo: {},
    }
  },
  mounted() {
    if (this.$route.path === '/sd-change-password') {
      Message.warn('第一次访问需要修改密码')
    }
  },
  created() {
    axios.get('api/admin/flow-mobile/v1/user-classified/info').then((res) => {
      const classified = res.data
      this.classified = res.data
      this.message = `密码必须有 ${classified.includeLower ? '小写字母' : ''} ${
        classified.includeUpper ? '大写字母' : ''
      } ${classified.includeNum ? '数字' : ''} ${classified.includeSpecialChar ? '特殊字符' : ''} ${
        classified.minLength ? `最小${classified.minLength}位字符` : ''
      }`
    })
    axios({
      method: 'get',
      url: 'api/xcoa-mobile/v1/spic-user/getCurrentUser',
    }).then((res) => {
      this.userinfo = res.data
    })
  },
  methods: {
    handleOldPass(rule, value, callback) {
      this.oldpassword = value
      callback()
    },
    handlePass(rule, value, callback) {
      if (this.oldpassword && this.oldpassword === value) {
        callback(new Error('和当前密码输入一致，请重新输入新密码！'))
      }

      if (value && value.indexOf(this.userinfo.account) !== -1) {
        callback(new Error('密码不能包含用户名'))
      }

      if (value && this.classified) {
        if (this.classified.minLength && value.length < this.classified.minLength) {
          callback(new Error(this.message))
        }
        if (this.classified.includeLower && !value.match(/[a-z]+/)) {
          callback(new Error(this.message))
        }
        if (this.classified.includeUpper && !value.match(/[A-Z]+/)) {
          callback(new Error(this.message))
        }
        if (this.classified.includeNum && !value.match(/[0-9]+/)) {
          callback(new Error(this.message))
        }
        if (
          this.classified.includeSpecialChar &&
          !value.match(/[`~!@#$%^&*()_+<>?:"{},.\\/;'[\]]/)
        ) {
          callback(new Error(this.message))
        }
      }
      this.password = value
      callback()
    },
    handleConfirmPass(rule, value, callback) {
      if (this.password && this.password !== value) {
        callback(new Error('两次密码输入不一致！'))
      }
      // Note: 必须总是返回一个 callback，否则 validateFieldsAndScroll 无法响应
      callback()
    },
    handleSubmitPassword(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          this.isSubmitting = true
          const key = Symbol.for()
          Message.loading({ content: '处理中...', key })
          // 调用接口修改密码
          PersonalCenterService.changePassword(
            this.userinfoAccount,
            values.password,
            values.old_password
          )
            .then((res) => {
              if (res) {
                Message.success({ content: '密码修改成功，请重新登录！', key, duration }).then(
                  () => {
                    // 退出重新登录
                    loginService.setTokens({})
                    store.commit('sd/login/setUserInfo', {})
                    router.push('/sd-login')
                  }
                )
              } else {
                Message.error({ content: '密码输入有误，修改失败！', key, duration })
                this.isSubmitting = false
              }
            })
            .catch((e) => {
              Message.error({ content: '密码修改失败，请联系管理员！', key, duration })
              this.isSubmitting = false
            })
        }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.buttonclass {
  float: right;
}
</style>
