<template>
  <el-dialog
    v-model="visible"
    :title="userInfo?.phone ? '更换手机号' : '绑定手机号'"
    width="450px"
    @close="handleDialogClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-width="90px"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSave">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import { bindPhone } from "@/api/user";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object,
    default: null
  },
  userId: {
    type: [Number, String],
    default: ""
  }
});

const emit = defineEmits(["update:modelValue", "saved"]);

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value)
});

const loading = ref(false);
const formRef = ref(null);

const form = reactive({
  phone: ""
});

const formRules = {
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

const syncForm = () => {
  form.phone = props.userInfo?.phone || "";
};

const handleSave = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    const res = await bindPhone(props.userId, form.phone);

    if (res.code === 200) {
      ElMessage.success(props.userInfo?.phone ? "手机号更换成功" : "手机号绑定成功");
      visible.value = false;
      emit("saved");
    }
  } catch (error) {
    console.error("保存手机号失败", error);
    if (error !== false) {
      ElMessage.error("保存手机号失败");
    }
  } finally {
    loading.value = false;
  }
};

const handleDialogClose = () => {
  formRef.value?.resetFields();
};

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      syncForm();
    }
  }
);
</script>
