<template>
  <Layer :layer="layer" @confirm="submit" ref="layerDom">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right: 30px">
      <el-form-item label="用户名：" prop="name"> {{ username }} </el-form-item>
      <el-form-item label="原密码：" prop="old">
        <el-input v-model="form.old" placeholder="请输入原密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码：" prop="new">
        <el-input v-model="form.new" placeholder="请输入新密码" show-password></el-input>
      </el-form-item>
    </el-form>
  </Layer>
</template>

<script>
import { defineComponent, ref } from 'vue'
import { useStore } from 'vuex'
import { changePassword } from '@/api/settings/user-settings'
import Layer from '@/components/layer'
export default defineComponent({
  components: {
    Layer,
  },
  props: {
    layer: {
      type: Object,
      default: () => {
        return {
          show: false,
          title: '',
          showButton: true,
        }
      },
    },
  },
  setup(props, ctx) {
    const ruleForm = ref(null)
    const layerDom = ref(null)
    const store = useStore()
    const username = store.getters['user/info'].name
    let form = ref({
      codeRs: store.getters['user/info'].codeRs,
      name: '',
      old: '',
      new: '',
    })
    const rules = {
      old: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
      new: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
    }
    function submit() {
      if (ruleForm.value) {
        ruleForm.value.validate((valid) => {
          if (valid) {
            let params = {
              oldPassword: form.value.old,
              newPassword: form.value.new,
            }
            changePassword(params).then(() => {
              layerDom.value && layerDom.value.close()
              store.dispatch('user/loginOut')
            })
          } else {
            return false
          }
        })
      }
    }
    return {
      username,
      form,
      rules,
      layerDom,
      ruleForm,
      submit,
    }
  },
})
</script>

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