<script setup lang="ts">
import type { Pwd, User } from '#/api/system/user/model';

import { defineEmits, defineProps, watch } from 'vue';

import { useVbenForm } from '#/adapter/form';
import { updateProfile, updateProfilePwd } from '#/api/system/user/user';

import { pwdSchema, userInfoSchema } from './config-data';

const props = defineProps<{ user: User }>();

const emit = defineEmits<{ reload: [] }>();

const [InfoFrom, infoFormApi] = useVbenForm({
  schema: userInfoSchema(),
  resetButtonOptions: {
    show: false,
  },
  submitButtonOptions: {
    content: '保存',
  },
  handleSubmit: infoSubmit,
});
//  修改用户信息提交
async function infoSubmit() {
  const { valid } = await infoFormApi.validate();
  if (!valid) {
    return;
  }
  const user = await infoFormApi.getValues<User>();
  await updateProfile(user);
  emit('reload');
}
const [PwdFrom, pwdFormApi] = useVbenForm({
  schema: pwdSchema(),
  resetButtonOptions: {
    show: false,
  },
  submitButtonOptions: {
    content: '保存',
  },
  handleSubmit: pwdHandleSubmit,
});
// 修改密码提交
async function pwdHandleSubmit() {
  const { valid } = await pwdFormApi.validate();
  if (!valid) {
    return;
  }
  const pwd = await pwdFormApi.getValues<Pwd>();
  await updateProfilePwd(pwd);
}
// 监听传递过来的值
watch(
  () => props.user,
  (newValue) => {
    infoFormApi.setValues(newValue);
  },
  { deep: true },
);
</script>

<template>
  <ElCard class="card-box flex-1 p-[24px]">
    <ElTabs model-value="1">
      <ElTabPane label="基本资料" name="1">
        <InfoFrom />
      </ElTabPane>
      <ElTabPane label="修改密码" name="2">
        <PwdFrom />
      </ElTabPane>
    </ElTabs>
  </ElCard>
</template>
