<template>
  <el-form ref="userRef" :model="userForm" :rules="rules" label-width="160px">
    <el-form-item :label="$t('profile.userInfoForm.nickName')" prop="nickName">
      <el-input v-model="userForm.nickName" maxlength="30" />
    </el-form-item>
    <el-form-item :label="$t('profile.info.phonenumber')" prop="phonenumber">
      <el-input v-model="userForm.phonenumber" maxlength="11" />
    </el-form-item>
    <el-form-item :label="$t('profile.info.email')" prop="email">
      <el-input v-model="userForm.email" maxlength="50" />
    </el-form-item>
    <el-form-item :label="$t('profile.userInfoForm.sex')">
      <el-radio-group v-model="userForm.sex">
        <el-radio value="0">{{ $t('profile.userInfoForm.male') }}</el-radio>
        <el-radio value="1">{{ $t('profile.userInfoForm.female') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">{{ $t('profile.userInfoForm.save') }}</el-button>
      <el-button type="danger" @click="close">{{ $t('profile.userInfoForm.close') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { updateUserProfile } from '@/api/system/user';
import { propTypes } from '@/utils/propTypes';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const props = defineProps({
  user: propTypes.any.isRequired
});
const userForm = computed(() => props.user);
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const userRef = ref<ElFormInstance>();
const rule: ElFormRules = {
  nickName: [{ required: true, message: t('profile.rule.nickNameRequired'), trigger: 'blur' }],
  email: [
    { required: true, message: t('profile.rule.emailRequired'), trigger: 'blur' },
    {
      type: 'email',
      message: t('profile.rule.emailFormat'),
      trigger: ['blur', 'change']
    }
  ],
  phonenumber: [
    {
      required: true,
      message: t('profile.rule.phonenumberRequired'),
      trigger: 'blur'
    },
    { pattern: /^1[3456789][0-9]\d{8}$/, message: t('profile.rule.phonenumberFormat'), trigger: 'blur' }
  ]
};
const rules = ref<ElFormRules>(rule);

/** 提交按钮 */
const submit = () => {
  userRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await updateUserProfile(props.user);
      proxy?.$modal.msgSuccess(t('profile.message.updateSuccess'));
    }
  });
};
/** 关闭按钮 */
const close = () => {
  proxy?.$tab.closePage();
};
</script>
