<template>
  <div class="flex" v-loading="loading">
    <el-card class="workspace-info w-full" shadow="always" style="padding-bottom: 40px;">
        <template #header>
          <div class="card-header" style="display: flex; align-items: center; justify-content: space-between;">
            <span style="flex-grow: 1; text-align: center;font-weight: bold;">个人信息</span>
            <div class="pull-right">
              <el-button type="primary" @click="openDialog">修改</el-button>
            </div>
          </div>
        </template>
        <ul class="user-info">
          <div class="info-row">
            <li class="info-item">
              <Icon class="mr-5px" icon="ep:user" />
              <span class="info-label">姓名：</span>
              <span class="pull-right">{{ userInfo.nickname }}</span>
            </li>
            <li class="info-item">
              <Icon class="mr-5px" icon="ep:location" />
              <span class="info-label">工作间：</span>
              <span class="pull-right">{{ userInfo.dept ? userInfo.dept.name : '未知部门' }}</span>
            </li>
          </div>

          <div class="info-row">
            <li class="info-item">
              <Icon class="mr-5px" icon="ep:phone" />
              <span class="info-label">手机号码：</span>
              <span class="pull-right">{{ userInfo.mobile }}</span>
            </li>
            <li class="info-item">
              <Icon class="mr-5px" icon="fontisto:email" />
              <span class="info-label">邮箱：</span>
              <span class="pull-right">{{ userInfo.email }}</span>
            </li>
          </div>

          <div class="info-row">
            <li class="info-item">
              <Icon class="mr-5px" icon="ep:user" />
              <span class="info-label">用户类型：</span>
              <span class="pull-right"> {{ userTypeMapping[userInfo.userType] || '未知用户类型' }}</span>
            </li>
            <li class="info-item">
              <Icon class="mr-5px" icon="ep:bell" />
              <span class="info-label">工号：</span>
              <span class="pull-right">{{ userInfo.userNumber }}</span>
            </li>
          </div>

        </ul>
        <div class="info-remark">
          <div style="display: flex; align-items: center;">
            <Icon icon="fontisto:email" />
            <div class="div-label" style="margin-left: 8px;">个人简历：</div>
          </div>
          <div class="remark-content">userInfo.introduction</div>
        </div>
        <div class="info-remark">
          <div style="display: flex; align-items: center;">
            <Icon icon="ep:picture" />
            <div class="div-label" style="margin-left: 8px;">简介：</div>
          </div>
          <div class="remark-content">{{ cleanedremark }}</div>
          <div class="image-container">
            <div v-for="(url, index) in extractedImageUrls" :key="index" class="image-item">
              <img :src="url" />
            </div>
          </div>
        </div>
      </el-card>
      <TForm
        ref="formRef"
        :visible="dialogVisible"
        :form="userInfo"
        @update:visible="dialogVisible = $event"
        @success="handleSuccess"
      />
  </div>
 
</template>

<script lang="ts">
import { defineComponent, reactive, ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useMessage } from '@/hooks/web/useMessage';
import TForm from './TForm.vue';
import { getUserProfile, ProfileVO } from '@/api/system/user/profile'


export default defineComponent({
  components: {
    TForm,
  },
  setup() {
    const { t } = useI18n();
    const message = useMessage();
    const dialogVisible = ref(false);
    const loading = ref(true) // 列表的加载中
    const formRef = ref();

    const form = reactive({
      mobile: '',
      email: '',
      nickname: '',
      password: '',
      sex: undefined,
      remark: '',
      userType: undefined,
      userNumber: '',
      dept: undefined,
      deptId: undefined,
    });

    // 将 userInfo 定义放入 setup 中
const userInfo = ref({} as ProfileVO)
const getUserInfo = async () => {
  try {
    loading.value = true; 
    const users = await getUserProfile();
    console.log(users, 'users');
    userInfo.value = users;
  } catch (error) {
    console.error('获取用户信息失败:', error);
  } finally {
    loading.value = false; // 隐藏加载中
  }
}

const userTypeMapping = {
  '3': '导师',
  '5': '外聘导师',
};

const downloadPDF = () => {
  const url = userInfo.value.introduction
  if (!url) {
    message.error('没有简历文件!');
    return;
  }
  // 先预览
  // const link = document.createElement('a'); // 创建一个链接元素
  // link.href = url; // 设置链接地址
  // link.download = '下载文件.pdf'; // 设置下载文件的名称
  // document.body.appendChild(link); // 将链接添加到文档中
  // link.click(); // 触发下载
  // document.body.removeChild(link); // 下载后移除链接
  // 直接下载
  // 创建一个下载链接
  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error('网络错误');
      }
      return response.blob(); // 将响应转换为 Blob 对象
    })
    .then(blob => {
      const link = document.createElement('a');
      const blobUrl = URL.createObjectURL(blob); // 创建 Blob URL
      link.href = blobUrl;
      link.download = '下载文件.pdf'; // 设置下载文件的名称
      document.body.appendChild(link);
      link.click(); // 触发下载
      document.body.removeChild(link); // 下载后移除链接
      URL.revokeObjectURL(blobUrl); // 释放 Blob URL
    })
    .catch(error => {
      console.error('下载失败:', error);
    });
}

const openDialog = () => {
  loading.value = true; // 显示加载中
  dialogVisible.value = true;
  formRef.value.open(); // 打开弹窗
  loading.value = false; // 关闭加载状态
};

const extractedImageUrls = ref<string[]>([]);
const handleSuccess = (urls) => {
  extractedImageUrls.value = urls;
  console.log('提取到的图片URL:', extractedImageUrls);
  dialogVisible.value = false;
  getUserInfo(); // 更新用户信息
};
const fetchImageUrls = async () => {
  try {
    loading.value = true; // 开始加载
    const res = await getUserProfile();
    const urls = res.remark.match(/<img.*?src="(.*?)"/g);
    if (urls) {
      extractedImageUrls.value = urls.map(url => {
        const match = url.match(/src="(.*?)"/);
        return match ? match[1] : '';
      });
    } else {
      extractedImageUrls.value = [];
    }
  } catch (error) {
    console.error('获取图片 URL 失败:', error);
  } finally {
    loading.value = false; // 完成加载
  }
};
// 创建一个 computed 属性来处理并去掉 <p> 标签
const cleanedremark = computed(() => {
  return userInfo.value.remark ? userInfo.value.remark.replace(/<\/?[^>]+(>|$)/g, '') : '';
});

    // // 表单提交
    // const submit = async () => {
    //   try {
    //     await formRef.value?.validate();
    //     console.log('提交的数据:', form);
    //     await updateDept(form).then((res) => {
    //       console.log('更新成功:', res);
    //     });
    //     message.success('成功');
    //   } catch (error) {
    //     console.error('提交错误:', error);
    //     message.error('错误');
    //   }
    // };


    // // 表单重置
    // const init = async () => {
    //   const res = await getUserProfile();
    //   console.log('获取的数据:', res);
    //   form.id = res.id;
    //   form.address = res.address;
    //   form.supervisor = res.user.nickname;
    //   form.phone = res.phone;
    //   form.email = res.email;
    //   form.name = res.name;
    //   form.leaderUserId = res.user.id;
    //   form.remark = res.remark;
    //   userInfo.value = res.user; 
    // };

    onMounted(async () => {
      // await init();
      await getUserInfo();
      await fetchImageUrls(); // 这里 add 一個方法来加载图片
    });

    return {
      t,
      // form,
      userInfo,   
      loading,
      // init,
      getUserInfo,
      fetchImageUrls,
      formRef,
      dialogVisible,
      openDialog,
      handleSuccess,
      extractedImageUrls,
      cleanedremark,
      userTypeMapping,
      downloadPDF,
    };
  }
});


</script>

<style scoped>
.user-info {
  margin-top: 10px;
  margin-left: 5%;
  margin-right: 5%;
  padding-right: 0;
  padding-left: 0;
  border-right: 0;
  border-left: 0;
  border-radius: 0;
  list-style: none;
}

.info-row {
  display: flex;
  justify-content: space-between; /* 保持并排显示 */
  align-items: center; /* 垂直居中对齐 */
  margin-bottom: 20px; /* 增加行之间的间距 */
}

.info-item {
  flex: 1; /* 每个信息项占据相同的空间 */
  padding: 11px 0; /* 内部上下填充 */
  margin-right: 50px; /* 每个信息项之间的右边距 */
}

/* 仅为每个信息项添加底部边框 */
.info-item:first-child {
  border-bottom: 1px solid #e7eaec;
}

.info-item:last-child {
  border-bottom: 1px solid #e7eaec; 
}

.info-remark {
  margin-top: 30px; /* 与上面的信息分隔 */
  margin-left: 5%; /* 左侧与上面列表保持一致 */
  margin-right: 5%; /* 右侧与上面列表保持一致 */
  /* display: flex;  */
  align-items: center; /* 确保标题与描述对齐 */
  align-items: flex-start;
}

.info-label {
  font-weight: bold; /* 加粗标题 */
  margin-right: 10px; /* 标题与内容之间的间距 */
}

.div-label {
  font-weight: bold; /* 加粗标题 */
  display: block;
  
}

.remark-content {
  white-space: pre-wrap; /* 保持换行 */
  overflow-wrap: break-word; /* 自动断行 */
  margin-right: 5%;
  font-size: 13px; /* 根据需要设置字体大小 */
  margin-top: 20px; /* 内容与标题之间不需要额外间距 */
  letter-spacing: 3px;
  text-indent: 2em; 
  line-height: 2;
}

.pull-right {
  float: right !important;
}

.info-label {
  font-weight: bold;
}

.image-container {
  display: flex; /* 使图片横向排列 */
  flex-wrap: wrap; /* 如果空间不足则换行 */
  gap: 10px; /* 图片之间的间距 */
  margin-left: 20px; /* 左边距，根据需要设置 */
}

.image-item img {
  width: 150px; /* 设置更大的宽度 */
  height: auto; /* 保持高度自动 */
}

</style>