<template>
  <el-dialog v-model="dialogVisible" title="个人信息" width="500px" draggable>
    <div class="form-wrap">
      <el-form :model="form" label-width="72px">
        <el-form-item label="头像">
          <el-upload
            v-model:file-list="form.avatarList"
            :http-request="handleHttpUpload"
            list-type="picture-card"
            :limit="1"
            :on-exceed="onExceed"
            :on-preview="handlePictureCardPreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="简介">
          <el-input v-model="form.intro" type="textarea" :rows="6" placeholder="请输入简介" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="getSaveUserInfo()">确认</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 图片预览 -->
  <el-image-viewer
    v-if="imageViewerVisible"
    :url-list="imageViewerUrlList"
    :initial-index="imageViewerInitialIndex"
    @close="imageViewerVisible = false"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, type FormInstance, type UploadUserFile, UploadRequestOptions } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { getMerchantByPhone, updateMerchantUserInfo } from "@/api/modules/homeEntry";
import { uploadImg } from "@/api/modules/newLoginApi";
import { localGet, localSet } from "@/utils/index";
import defaultAvatar from "@/assets/images/avatar.gif";
import { head } from "lodash";
import { useUserStore } from "@/stores/modules/user";

const emit = defineEmits<{
  avatarUpdated: [avatarUrl?: string];
}>();

const userStore = useUserStore();
const userInfo = localGet("geeker-user")?.userInfo || {};
const dialogVisible = ref(false);

let headImg1 = ref("");
const userId = ref<string | number>(""); // 保存用户ID
const form = reactive({
  avatarList: [] as UploadUserFile[],
  nickname: "",
  intro: ""
});

// 图片预览相关
const imageViewerVisible = ref(false);
const imageViewerUrlList = ref<string[]>([]);
const imageViewerInitialIndex = ref(0);

/** 与 ToolBarRight 右上角用户名一致：优先 name，否则 nickName */
function displayNameLikeHeader(data: Record<string, any> | null | undefined): string {
  if (!data) return "";
  return data.name != null ? String(data.name) : String(data.nickName ?? "");
}

const getUserInfo = async () => {
  const res: any = await getMerchantByPhone({ phone: userInfo.phone });
  if (res.code == 200) {
    // 保存用户ID
    userId.value = res.data.id || res.data.userId || "";
    form.nickname = displayNameLikeHeader(res.data);
    form.intro = res.data.accountBlurb || "";
    // 设置头像
    const headImg = res.data.headImg;
    if (headImg && headImg !== null && headImg !== "") {
      // 如果有头像，使用用户头像
      headImg1.value = headImg; // 初始化 headImg1
      form.avatarList = [
        {
          name: "avatar",
          url: headImg,
          uid: Date.now()
        } as UploadUserFile
      ];
    } else {
      // 如果 headImg 为 null 或空，使用默认头像
      headImg1.value = ""; // 清空 headImg1
      form.avatarList = [
        {
          name: "avatar",
          url: defaultAvatar,
          uid: Date.now()
        } as UploadUserFile
      ];
    }
  }
};
const openDialog = async () => {
  dialogVisible.value = true;
  getUserInfo();
};
//文件上传
const handleHttpUpload = async (options: UploadRequestOptions) => {
  let formData = new FormData();
  formData.append("file", options.file);
  try {
    const res: any = await uploadImg(formData);
    // 上传成功，将URL保存到文件对象中
    const fileUrl = res?.data?.fileUrl || res?.data?.[0] || res?.fileUrl;
    if (fileUrl) {
      headImg1.value = fileUrl;
      // 更新 form.avatarList 中对应文件的 URL
      if (form.avatarList && form.avatarList.length > 0) {
        form.avatarList[0].url = fileUrl;
        form.avatarList[0].response = { fileUrl };
      }
      // 调用 onSuccess 回调，传入响应数据
      options.onSuccess({ fileUrl });
    } else {
      throw new Error("上传失败：未获取到文件URL");
    }
  } catch (error) {
    options.onError(error as any);
    ElMessage.error("文件上传失败，请重试");
  }
};
const getSaveUserInfo = async () => {
  try {
    // 获取头像URL：优先使用新上传的，否则从 avatarList 中获取，最后为空字符串
    let avatarUrl = headImg1.value;
    console.log("保存前 headImg1.value:", headImg1.value);
    console.log("保存前 form.avatarList:", form.avatarList);

    // 如果 headImg1.value 为空，尝试从 form.avatarList 中获取
    if (!avatarUrl && form.avatarList && form.avatarList.length > 0) {
      const avatarFile = form.avatarList[0];
      // 从 file.url 或 file.response 中获取 URL
      const fileUrl = avatarFile.url || (avatarFile.response as any)?.fileUrl || "";
      // 排除默认头像
      if (fileUrl && fileUrl !== defaultAvatar) {
        avatarUrl = fileUrl;
        // 同时更新 headImg1.value，以便后续使用
        headImg1.value = fileUrl;
      }
    }

    console.log("保存时使用的头像URL:", avatarUrl);

    const res: any = await updateMerchantUserInfo({
      id: userId.value,
      name: form.nickname,
      nickName: form.nickname,
      headImg: avatarUrl || "",
      accountBlurb: form.intro
    });

    if (res.code == 200) {
      ElMessage.success(res.msg || "保存成功");
      dialogVisible.value = false;
      // 通知父组件头像已更新，传递新的头像URL（优先使用保存的头像URL）
      const finalAvatarUrl = avatarUrl && avatarUrl.trim() !== "" ? avatarUrl : res.data?.headImg || "";
      console.log("保存成功，传递给父组件的头像URL:", finalAvatarUrl);
      emit("avatarUpdated", finalAvatarUrl);

      // 更新本地存储和 userStore 中的用户信息
      try {
        const merchantRes: any = await getMerchantByPhone({ phone: userInfo.phone });
        if (merchantRes && merchantRes.code == 200 && merchantRes.data) {
          // 更新本地存储
          const geekerUser = localGet("geeker-user");
          if (geekerUser) {
            geekerUser.userInfo = {
              ...geekerUser.userInfo,
              ...merchantRes.data
            };
            localSet("geeker-user", geekerUser);
            // 更新 userStore
            userStore.setUserInfo(geekerUser.userInfo);
          }
        }
      } catch (error) {
        console.error("获取更新后的用户信息失败:", error);
      }

      // 刷新用户信息（用于更新对话框中的数据）
      getUserInfo();
    } else {
      ElMessage.error(res.msg || "保存失败，请重试");
    }
  } catch (error: any) {
    ElMessage.error(error?.msg || error?.message || "保存失败，请重试");
  }
};

defineExpose({ openDialog });

const onExceed = () => {
  ElMessage.warning("仅允许上传一张头像");
};

// 图片预览处理函数
const handlePictureCardPreview = (file: UploadUserFile) => {
  // 如果文件正在上传中，允许预览（使用本地预览）
  if (file.status === "uploading" && file.url) {
    imageViewerUrlList.value = [file.url];
    imageViewerInitialIndex.value = 0;
    imageViewerVisible.value = true;
    return;
  }
  // 获取头像图片的 URL
  const avatarUrl = file.url || (file.response as any)?.fileUrl || "";
  if (!avatarUrl) {
    ElMessage.warning("图片尚未上传完成，无法预览");
    return;
  }
  imageViewerUrlList.value = [avatarUrl];
  imageViewerInitialIndex.value = 0;
  imageViewerVisible.value = true;
};
</script>
