<template>
  <view class="page">
    <BackBar title="个人资料" />
    <view class="info">
      <view class="info-item border">
        <view class="label"><text class="must">*</text>头像</view>
        <view class="form-content">
          <image
            v-if="form.personalPhoto"
            :src="form.personalPhoto ? form.personalPhoto : defaultAvatar"
            mode=""
            class="photo_img"
            @click="handlePreview"
          >
          </image>
          <text v-else class="placeholder" @click="() => popupRef.open()">请上传头像</text>
          <image :src="arrow" mode="" class="arrow" @click="() => popupRef.open()"></image>
        </view>
      </view>
      <view class="info-item border">
        <view class="label"><text class="must">*</text>姓名</view>
        <input
          v-model="form.name"
          type="text"
          disabled
          class="input_box"
          placeholder="请输入姓名"
          placeholder-style="color:#A9AAB5;text-align: right;font-size:30rpx;"
        />
      </view>
      <view class="info-item border" @click="jumpPage('/pages/inspector/personalData/editPhone')">
        <view class="label"><text class="must">*</text>手机号</view>
        <view class="form-content">
          <input
            v-model="form.phone"
            type="number"
            class="input_box"
            placeholder="请输入手机号"
            placeholder-style="color:#A9AAB5;text-align: right;font-size:30rpx;"
          />
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
      </view>
      <view class="info-item border">
        <view class="label"><text class="must">*</text>微信号</view>
        <view class="form-content">
          <input
            v-model="form.wechatNumber"
            type="text"
            class="input_box"
            placeholder="请输入微信号"
            placeholder-style="color:#A9AAB5;text-align: right;font-size:30rpx;"
          />
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
      </view>
    </view>
    <view class="info">
      <view class="info-item border">
        <view class="label">擅长科目</view>
        <view class="form-content" @click="jumpPage('/pages/inspector/personalData/subject')">
          <!-- <picker
                        range-key="name"
                        :value="currentIndex"
                        :range="subjectList"
                        @change="bindPickerChange"
                    >
                        <view v-if="!!currentIndex" class="placeholder">{{
                            subjectList[currentIndex]?.name
                        }}</view>
                    </picker> -->
          <view v-if="!form.specializedSubject" class="placeholder">请选择擅长科目</view>
          <view v-else class="row-content">
            <text
              v-for="item of form.specializedSubject.split(',')"
              :key="item"
              class="subject-tag"
              >{{ item }}</text
            >
          </view>
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
      </view>
      <view class="info-item border">
        <view class="label"><text class="must">*</text>个人简介</view>
        <view
          class="form-content"
          @click="jumpPage('/pages/inspector/personalData/personalInformation')"
        >
          <view v-if="!form.personalInformation" class="placeholder"> 输入有竞争力的简介哦~ </view>
          <view v-else class="input_box_textarea"> {{ form.personalInformation }} </view>
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
      </view>
    </view>
    <view class="info">
      <view class="info-title">教育经历</view>
      <view class="info-item border">
        <view class="label"><text class="must">*</text>学历</view>
        <view class="form-content" @click="showPopup = true">
          <!-- <picker
                        range-key="name"
                        :value="currentIndex"
                        :range="subjectList"
                        @change="bindPickerChange"
                    >
                        <view v-if="!!currentIndex" class="placeholder">{{
                            subjectList[currentIndex]?.name
                        }}</view>
                    </picker> -->
          <view v-if="form.degree">{{ form.degree }}</view>
          <view v-else class="placeholder">请选择擅长科目</view>
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
      </view>
      <view class="info-item border">
        <view class="label"><text class="must">*</text>学校</view>
        <input
          v-model="form.gradSchool"
          type="text"
          maxlength="50"
          class="input_box"
          placeholder="请输入学校名"
          placeholder-style="color:#A9AAB5;text-align: right;font-size:30rpx;"
        />
      </view>
    </view>
    <view class="info">
      <view class="info-title">资质证书</view>
      <!-- <view  class="all_img"> -->
      <view v-if="form.qualification?.length > 0" class="info-item">
        <view class="label">证书名称</view>
        <view
          class="form-content"
          @click="jumpPage('/pages/inspector/personalData/certificateView')"
        >
          <view>{{ form.qualification?.map(item => item.name).join('、') }}</view>
          <image :src="arrow" mode="" class="arrow"></image>
        </view>
        <!-- </view> -->

        <!-- <view v-for="(i, idx) in tempImageUrl" :key="idx" class="certificate_img">
          <image :src="i.url" mode="" class="show_certificate" @click="previewImg(idx)"></image>
          <image
            :src="`${OSS_URL}/iconfont/close_icon.png`"
            mode=""
            class="close_icon"
            @click="deleteImg(idx)"
          ></image>
        </view> -->
      </view>
      <view v-else class="upload-row" @click="addQualification"> + 添加 </view>
    </view>
    <view class="footer">
      <button class="logout-btn" @click="handLogout">退出登录</button>
      <button class="footer-btn" @click="submitSave">保存</button>
    </view>
    <!-- 弹出框选项 -->
    <view class="picker_box">
      <uni-popup ref="popupRef" is-mask-click animation type="bottom">
        <view class="popup_box">
          <view class="header_title"> 选择上传方式 </view>
          <view class="method_list">
            <view v-for="i in pickList" :key="i.type" class="item" @click="chooseUploadMethod(i)">
              {{ i.name }}
            </view>
          </view>
          <view class="popup-footer">
            <button class="cancel-btn" @click="clsoePopup">取消</button>
          </view>
        </view>
      </uni-popup>
    </view>
    <Picker
      v-model="showPopup"
      :pickList="columns"
      title="选择学科"
      :pickVal="[pikerIndex]"
      @confirm="confirmSelect"
    />
  </view>
</template>
<script setup lang="ts">
import { user } from '@/store';
const { logout } = user();
import { onLaunch, onShow, onHide, onLoad } from '@dcloudio/uni-app';
import { usepersonalStoreHook } from '@/store/inspector';
import Picker from '../releasePlan/components/picker.vue';
import { getUserInfo, updateTeacherInfo } from '@/api/modules/inspector';
import { ref, reactive, nextTick, onMounted } from 'vue';
import { removeCache } from '@/utils';
const OSS_URL = import.meta.env.VITE_OSS_HOST;
const defaultAvatar = `${OSS_URL}/urm/default_avatar.png`;
const arrow = `${OSS_URL}/iconfont/down_arrow.png`;
const form = ref<any>({});
const popupRef = ref();
const pikerIndex = ref(0);
const popupTitle = ref('');
const currentIndex = ref();
const selectionPopupRef = ref();
const qualification = ref<any[]>([]);
const formStore = usepersonalStoreHook();
const showPopup = ref(false);
const hasQuery = ref(false);
const columns = [
  { name: '大专', value: '大专' },
  { name: '本科', value: '本科' },
  { name: '研究生', value: '研究生' },
  { name: '博士', value: '博士' },
  { name: '其他', value: '其他' },
];
const pickList = ref([
  {
    name: '从相册选择',
    type: 1,
    sourceType: 'album',
  },
  {
    name: '拍照上传',
    type: 2,
    sourceType: 'camera',
  },
]);
// 擅长科目
const subjectList = ref([{ name: '数学' }, { name: '语文' }]);
const handSelect = (type: string) => {
  switch (type) {
    case 'subject':
      popupTitle.value = '请选择擅长科目';
      break;
  }

  selectionPopupRef.value.open();
};
function confirmSelect(val: any) {
  form.value.degree = val.value;
  showPopup.value = false;
}
const bindPickerChange = (e: any) => {
  currentIndex.value = e.detail.value;
};
function handlePreview() {
  if (!form.value.personalPhoto) return;
  uni.previewImage({
    urls: [form.value.personalPhoto],
    current: 0,
  });
}
function addQualification() {
  uni.navigateTo({
    url: '/pages/inspector/personalData/certificateAdd',
  });
}
function chooseUploadMethod(i: any) {
  popupRef.value.close();
  uni.chooseImage({
    count: 1, // 最多可以选择的图片张数
    sizeType: ['compressed', 'original'], // original 原图，compressed 压缩图，默认二者都有
    sourceType: [i.sourceType], // album 从相册选图，camera 使用相机，默认二者都有
    success: res => {
      jumpPage(`/pages/inspector/personalData/cropper?file=${res.tempFilePaths[0]}`);
    },
    fail: err => {
      // 图片接口调用失败的回调函数
      console.log('chooseImage fail', err);
    },
  });
}
// 上传图片
function uploadImage() {
  uni.chooseImage({
    sizeType: ['compressed', 'original'], // original 原图，compressed 压缩图，默认二者都有
    sourceType: ['album', 'camera'],
    // album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
    success: (res: any) => {
      console.log(res, '图片');

      // 成功返回的函数
      res.tempFilePaths.map((item: any) => form.value.qualification.push(item));
    },
    fail: err => {
      // 图片接口调用失败的回调函数
      console.log('chooseImage fail', err);
    },
  });
}
// 查看图片
function previewImg(idx: number) {
  uni.previewImage({
    current: idx,
    urls: form.value.qualification,
  });
}
// 删除图片
function deleteImg(i: number) {
  form.value.qualification.splice(i, 1);
}
// 上传图标加载完毕
function loadUploadIcon(e: any) {
  // wx.hideLoading();
}
// 加载失败
function errorUploadIcon() {
  // wx.hideLoading();
}
function back() {
  uni.navigateBack({ delta: 1 });
}
const clsoePopup = () => {
  popupRef.value.close();
};
function checkedForm() {
  let valid = true;
  const fields = [
    'personalPhoto',
    'phone',
    'name',
    'wechatNumber',
    'personalInformation',
    'degree',
    'gradSchool',
  ];
  fields.forEach(item => {
    if (!form.value[item]) {
      valid = false;
    }
  });
  return valid;
}
// 保存
async function submitSave() {
  if (!checkedForm()) {
    uni.showToast({
      title: '请完善资料后再保存',
      icon: 'none',
    });
    return;
  }
  try {
    uni.showLoading({
      title: '保存中...',
      mask: true,
    });
    const { code } = await updateTeacherInfo(form.value);
    uni.hideLoading();
    if (code === 200) {
      uni.showToast({
        title: '保存成功',
        mask: true,
      });
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/inspector/mine/index',
        });
      }, 1500);
    }
  } catch (error) {
    uni.hideLoading();
  }
}
// 页面跳转
const jumpPage = (path: string) => {
  formStore.SET_FORM(form.value);
  uni.navigateTo({
    url: path,
  });
};
// 获取督学师资料
async function getData() {
  try {
    uni.showLoading({ title: '加载中...' });
    const { code, data } = await getUserInfo();
    if (code === 200) {
      hasQuery.value = true;
      form.value = { ...data };
      formStore.SET_FORM(form.value);
      pikerIndex.value = columns.findIndex(e => e.value === data.degree);
    }
    uni.hideLoading();
  } catch (error) {}
}
async function handLogout() {
  logout();
}
onMounted(() => {
  if (!hasQuery.value) getData();
});
onShow(() => {
  const personalData = formStore.form;
  if (personalData) {
    form.value = personalData;
  }
});
</script>
<style lang="scss" scoped>
.page {
  padding: 0 30rpx 130rpx;
  .info {
    margin-top: 20rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    background-color: #fff;
    border-radius: 20rpx;
    .info-title {
      font-family: 'PingFang SC';
      font-size: 30rpx;
      font-style: normal;
      font-weight: 500;
      line-height: 45rpx;
      color: #0a1f13;
      margin-bottom: 30rpx;
    }
    .info-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      min-height: 60rpx;
    }

    .label {
      font-size: 30rpx;
      line-height: 42rpx;
      color: rgba(51, 51, 51, 1);
      font-weight: 500;

      .must {
        color: red;
      }
    }

    .border {
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f6f6f6;
    }
    .input_box {
      text-align: right;
      width: 420rpx;
      font-size: 30rpx;
      color: rgba(51, 51, 51, 1);
      line-height: 42rpx;
    }
    .input_box_textarea {
      text-align: right;
      width: 420rpx;
      font-size: 30rpx;
      color: rgba(51, 51, 51, 1);
      line-height: 42rpx;
      min-height: 42rpx;
      display: -webkit-box;
      overflow: hidden;
      text-overflow: ellipsis;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
    .placeholder {
      color: #a9aab5;
      text-align: right;
      font-size: 30rpx;
    }
    .form-content {
      display: flex;
      min-height: 80rpx;
      align-items: center;
      max-width: 440rpx;

      .photo_img {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
      }

      .arrow {
        margin-left: 10rpx;
        width: 30rpx;
        height: 30rpx;
        transform: rotate(-90deg);
      }
      .row-content {
        width: 440rpx;
        max-height: 120rpx;
        overflow: hidden;
        overflow-y: auto;
        // text-overflow: ellipsis;
        // white-space: nowrap;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
        .subject-tag {
          padding: 8rpx 24rpx;
          box-sizing: border-box;
          background: #f9f9fb;
          border-radius: 10rpx;
          margin: 0 10rpx 10rpx 0;
          font-size: 30rpx;
          color: #0a1f13;
          line-height: 30rpx;
        }
      }
    }
  }
}
.popup_box {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;

  .header_title {
    margin: 30rpx 0 0 30rpx;
    color: rgba(51, 51, 51, 0.8);
    font-size: 32rpx;
    font-weight: 500;
    text-align: left;
  }

  .method_list {
    text-align: center;
    padding: 0 54rpx;

    .item {
      padding: 30rpx 0;
      border-bottom: 1rpx solid #f6f6f6;
      font-weight: 400;
      height: 45rpx;
      color: rgba(51, 51, 51, 1);
    }
  }
}
.all_img {
  display: flex;

  .certificate_img {
    position: relative;
    margin-right: calc((100vw - 540rpx) / 4);
    width: 120rpx;
    height: 120rpx;

    .show_certificate {
      width: 100%;
      height: 100%;
    }

    &:nth-child(4n) {
      margin-right: 0 !important;
    }

    .close_icon {
      position: absolute;
      top: 0;
      right: 0;
      width: 30rpx;
      height: 30rpx;
      background-color: transparent;
    }
  }
}
.upload-row {
  font-size: 30rpx;
  font-weight: 400;
  color: #615dff;
  margin-top: 30rpx;
}
.footer {
  width: 100vw;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: fixed;
  background: #fff;
  bottom: 0;
  left: 0;
  padding: 0 30rpx;
  box-sizing: border-box;
  border-top: 2rpx solid #f6f6f6;
  .footer-btn {
    width: 420rpx;
    background-color: #615dff;
    color: #fff;
    font-size: 30rpx;
    border-radius: 20rpx;
  }
  .logout-btn {
    width: 220rpx;
    color: #615dff;
    font-size: 30rpx;
    border-radius: 20rpx;
    background-color: #ebebff;
  }
}
.picker_box {
  .popup-footer {
    display: flex;
    justify-content: center;
    padding: 16rpx 0;
    box-sizing: border-box;
    border-top: 2rpx solid #f6f6f6;
  }
  .cancel-btn {
    width: 440rpx;
    height: 90rpx;
    line-height: 90rpx;
    border-radius: 20rpx;
    background: #efefff;
    color: #615dff;
    font-family: 'PingFang SC';
    font-size: 30rpx;
    font-weight: 500;
  }
}
</style>
