<template>
  <div class="personal-info">
    <PageHeader
      title="个人信息"
      :is-back="true"
      :border-bottom="false"
      :background="headerBackground"
    />

    <div class="content-wrapper">
      <div class="form-container">
        <div class="form-item">
          <div class="form-label">头像</div>
          <div class="form-value">
            <div>
              <uni-file-picker
              v-model="imageValue"
              limit="1"
              :del-icon="false"
              disable-preview
              :imageStyles="imageStyles"
              file-mediatype="image"
              style="font-size: 12rpx;margin-left: auto;"
              @select="onSelect"
            >
              <text></text>
            </uni-file-picker>
            </div>
          </div>
        </div>

        <div class="form-item">
          <div class="form-label">姓名</div>
          <div class="form-value">
            <u-input
              v-model="teacherInfo.name"
              :border="false"
              placeholder="请输入姓名"
              :clearable="false"
              :custom-style="{ textAlign: 'right' }"
            ></u-input>
          </div>
        </div>

        <div class="form-merge">
          <!-- <div class="form-item-merge">
            <div class="form-label">所属学校</div>
            <div class="form-value">
              <u-input
                v-model="teacherInfo.schoolName"
                :border="false"
                placeholder="请输入学校名称"
                :clearable="false"
                :custom-style="{ textAlign: 'right' }"
                :disabled="true"
              ></u-input>
            </div>
          </div> -->
          <div class="line" style="height: 1px"></div>
          <div class="form-item-merge">
            <div class="form-label">部门</div>
            <div class="form-value" @click="showCollegePicker = true">
              {{ teacherInfo.collegeName || "请选择部门" }}
              <u-icon name="arrow-right" color="#999" size="24"></u-icon>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="save-btn" @click="saveInfo">保存</div>
    <!-- 学院选择器 -->
    <u-select
      v-model="showCollegePicker"
      :list="collegeList"
      @confirm="confirmCollege"
    ></u-select>
  </div>
</template>

<script>
import PageHeader from "@/components/PageHeader.vue";

export default {
  name: "PersonalInfo",
  components: {
    PageHeader,
  },
  data() {
    return {
      baseUrl: "",
      imageUrl: "",
      imageValue: [],
      imageStyles: {
        width: 52,
        height: 52,
        border: {
          radius: "50%",
        },
      },
      teacherInfo: {
        name: "",
        id: "",
        collegeName: "",
        collegeManagementId: "",
        schoolName: ""
      },
      headerBackground: {
        background: "transparent",
      },
      showCollegePicker: false,
      collegeList: [],
    };
  },
  onLoad() {
    // 从vuex获取教师信息
    const info = this.vuex_teacherInfo || {};
    this.baseUrl = this.$u.http.config.baseUrl;
    this.teacherInfo = {
      ...info,
    };
    this.initAvatar(info);

    this.getSchoolInfo();
  },
  methods: {
    initAvatar(info) {
      const rawUrl = info.headSculptureUrl || info.avatar || "";
      const displayUrl = this.buildAvatarUrl(rawUrl);
      if (displayUrl) {
        this.imageValue = [
          {
            url: displayUrl,
            extname: "",
            name: "",
          },
        ];
      }
      if (info.headSculptureUrl) {
        this.imageUrl = info.headSculptureUrl;
      }
    },
    // 拼装头像地址，兼容相对路径
    buildAvatarUrl(url) {
      const fallback = "/static/common/images/avatar_default.jpg";
      if (!url) return fallback;
      if (/^https?:\/\//i.test(url)) return url;
      const baseUrl = this.baseUrl || this.$u?.http?.config?.baseUrl || "";
      if (baseUrl) return `${baseUrl}/${url}`;
      return url.startsWith("/") ? url : `/${url}`;
    },
    // 获取上传状态
    onSelect(data) {
      const file = (data && data.tempFiles && data.tempFiles[0]) || {};
      const filePath =
        file.path || file.url || (file.image && file.image.location);
      if (!filePath) {
        this.$u.toast("无法获取文件路径");
        return;
      }

      this.$u.api
        .UploadSingleImage({
          filePath,
          name: "file",
          formData: {},
        })
        .then((res) => {
          if (res.succeed) {
            this.imageUrl = res.data.replace(/\\/g, "/") || "";
            this.imageValue = [
              {
                url: `${this.baseUrl}/${this.imageUrl}`,
                extname: file.extname || "",
                name: "",
              },
            ];
            this.teacherInfo.headSculptureUrl = this.imageUrl;
            // this.teacherInfo.avatar = this.imageValue[0].url;
            this.$u.toast("上传成功");
          } else {
            this.$u.toast(res.error || "上传失败");
          }
        });
    },
    // 获取学院和专业信息
    getSchoolInfo() {
      this.$u.api.getData().then((res) => {
        if (res.succeed && res.data) {
          this.handleSchoolInfo(res);
        }
      });
    },
    // 处理获取的接口数据
    handleSchoolInfo(res) {
      // 处理学院信息
      if (res.data && res.data.length > 0) {
        // 设置学院列表
        this.collegeList = res.data.map((item) => ({
          value: item.value,
          label: item.label,
        }));

        // 如果已有选择的学院，则设置对应的学院ID
        if (this.teacherInfo.collegeName) {
          const selectedCollege = res.data.find(
            (item) => item.label === this.teacherInfo.collegeName
          );
          if (selectedCollege) {
            // 如果没有collegeManagementId，则设置它
            if (!this.teacherInfo.collegeManagementId) {
              this.teacherInfo.collegeManagementId = selectedCollege.value;
            }
          }
        }
      }
    },

    // 确认学院选择
    confirmCollege(e) {
      this.teacherInfo.collegeName = e[0].label;
      this.teacherInfo.collegeManagementId = e[0].value;
    },

    // 保存个人信息
    saveInfo() {
      // 表单验证
      if (!this.teacherInfo.name) {
        return this.$u.toast("请输入姓名");
      }
      // if (!this.teacherInfo.schoolName) {
      //   return this.$u.toast("请输入学校名称");
      // }
      if (!this.teacherInfo.collegeName) {
        return this.$u.toast("请选择学院");
      }

      this.$u.vuex("vuex_teacherInfo", this.teacherInfo);

      
      console.log("this.teacherInfo----", this.teacherInfo);
      const persistedInfo = this.vuex_teacherInfo || {};
      let query = {
        ...persistedInfo,
        ...this.teacherInfo,
        collegeName: this.teacherInfo.collegeName || persistedInfo.collegeName,
        collegeManagementId:
          this.teacherInfo.collegeManagementId ||
          persistedInfo.collegeManagementId,
        // schoolName: "江西新能源科技职业技术学院",
      };
      console.log('query',query);
      this.$u.api
        .updateTeacherInfo(query)
        .then((res) => {
          this.$u.toast("保存成功");
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        })
        .catch((err) => {
          this.$u.toast("保存失败，请重试");
        });

      // 模拟保存成功
      this.$u.toast("保存成功");
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    },
  },
};
</script>

<style scoped>
.personal-info {
  height: 100vh;
  background-image: url("@/static/notes/bg.png");
  background-position: center top;
  background-repeat: no-repeat;
  background-size: 100% auto;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20rpx 30rpx 60px;
  overflow: hidden;
}

.form-container {
  border-radius: 8px;
  margin-top: 46rpx;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-radius: 20rpx;
  margin-bottom: 20rpx;
  background-color: #fff;
}

.form-merge {
  display: flex;
  flex-direction: column;
  border-radius: 20rpx;
  background-color: #fff;
}

.form-item-merge {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
}

.line {
  width: 90%;
  height: 1px;
  background-color: #f0f0f0;
  margin: 0 auto;
}

.form-label {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  flex-shrink: 0;
  width: 160rpx;
}

.form-value {
  display: flex;
  align-items: center;
  font-size: 27rpx;
  font-weight: 500;
  color: #333;
  flex: 1;
  justify-content: flex-end;
  text-align: right;
}

.avatar {
  width: 52rpx;
  height: 52rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.save-btn {
  width: 90%;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  color: #fff;
  background: #4f6aff;
  border-radius: 16rpx;
  margin: 60rpx auto;
  font-size: 32rpx;
  font-weight: bold;
  display: fixed;
  bottom: 0;
}
</style>
