<template>
  <a-button type="outline" size="small" :style="{ marginRight: '10px' }" @click="handleEdit">编辑</a-button>
  <a-drawer
    :width="400"
    :visible="visible"
    unmount-on-close
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #title> 编辑用户</template>
    <a-form
      ref="userEditRef"
      layout="vertical"
      :model="editData"
      :style="{ width: '360px' }"
    >
      <a-form-item
        field="username"
        label="用户名"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '用户名不能为空' }]"
      >
        <a-input v-model="editData.username" />
      </a-form-item>
      <a-form-item
        field="phone"
        label="电话"
        :rules="[
          { required: true, message: '电话不能为空' },
          { match: /^1[3-9]\d{9}$/, message: '请输入正确格式的电话号码' },
        ]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="editData.phone" />
      </a-form-item>
      <a-form-item
        field="email"
        label="邮箱"
        :rules="[
          { required: true, type: 'email', message: '请输入正确格式的邮箱' },
        ]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="editData.email" />
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { PropType, ref } from 'vue';
  import { UserRecord, update } from '@/api/user';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';

  const props = defineProps({
    user: {
      type: Object as PropType<UserRecord>,
      required: true,
    },
  });

  const emit = defineEmits(['refresh']);

  const editData = ref<UserRecord>({ ...props.user });

  const { visible, setVisible } = useVisible(false);

  const userEditRef = ref<FormInstance>();

  const handleEdit = () => {
    setVisible(true);
  };
  const handleSubmit = async () => {
    const valid = await userEditRef.value?.validate();
    if (!valid) {
      const res = await update(editData.value);
      if (res.status === 200) {
        Message.success({
          content: '编辑成功',
          duration: 5 * 1000,
        });
      }
      emit('refresh');
      setVisible(false);
    }
  };
  const handleCancel = async () => {
    userEditRef.value?.resetFields();
    setVisible(false);
  };

</script>

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