<template>
  <div>
    <el-row type="flex" justify="center">
      <el-col :md="24" :lg="16" :style="{ marginBottom: '10px' }">
        <el-card>
          <div>
            <el-form
              ref="editPasswordFormRef"
              :model="editPasswordForm"
              :label-width="100"
              label-position="right"
              :rules="passwordValidate"
            >
              <el-form-item label="原密码" prop="oldPass" :error="oldPassError">
                <el-input
                  type="password"
                  v-model="editPasswordForm.oldPass"
                  placeholder="请输入现在使用的密码"
                ></el-input>
              </el-form-item>
              <el-form-item label="新密码" prop="newPass">
                <el-input
                  type="password"
                  v-model="editPasswordForm.newPass"
                  placeholder="请输入密码（数字和字母8～16位）"
                ></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="rePass">
                <el-input
                  type="password"
                  v-model="editPasswordForm.rePass"
                  placeholder="请再次输入新密码"
                ></el-input>
              </el-form-item>
            </el-form>
            <el-button
              type="primary"
              :loading="savePassLoading"
              @click="saveEditPass"
              >保存</el-button
            >
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { changePwd } from '@/api/user'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { reactive, toRefs, ref } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  setup() {
    const editPasswordFormRef = ref(null)

    const valideRePassword = (rule, value, callback) => {
      if (value !== state.editPasswordForm.newPass) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    const store = useStore()
    const state = reactive({
      oldPassError: '',
      savePassLoading: false,
      editPasswordForm: {
        oldPass: '',
        newPass: '',
        rePass: ''
      },
      passwordValidate: {
        oldPass: [
          { required: true, message: '请输入原密码', trigger: 'change' }
        ],
        newPass: [
          { required: true, message: '请输入新密码', trigger: 'change' },
          { min: 6, message: '请至少输入6个字符', trigger: 'change' },
          { max: 16, message: '最多输入16个字符', trigger: 'change' }
        ],
        rePass: [
          { required: true, message: '请再次输入新密码', trigger: 'change' },
          { validator: valideRePassword, trigger: 'change' }
        ]
      }
    })
    const router = useRouter()
    const saveEditPass = () => {
      editPasswordFormRef.value.validate(async (valid) => {
        if (valid) {
          state.savePassLoading = true
          const response = await changePwd(
            store.getters.userInfo.userId,
            state.editPasswordForm.oldPass,
            state.editPasswordForm.newPass
          )
          state.savePassLoading = false
          if (response.BussinessCode !== 0) {
            ElMessage.error(response.BussinessMsg)
            return
          }
          ElMessage.success('密码修改成功')
          // 退出登录
          store.dispatch('user/logout')
          router.push('login')
          //退出清空所有本地存储
          localStorage.clear()
        }
      })
    }

    return {
      ...toRefs(state),
      saveEditPass,
      editPasswordFormRef
    }
  }
}
</script>
