<template>
  <view class="page">
    <BackBar v-if="pageType === 1" title="完善信息" />
    <view class="info">
      <view class="info_item info_header">
        <view class="label"><text class="must">*</text>头像</view>
        <view class="photo">
          <image
            :src="info.avatarUrl ? info.avatarUrl : defaultAvatar"
            mode=""
            class="photo_img"
            @click="handlePreview"
          >
          </image>
          <image :src="arrow" mode="" class="arrow" @click="() => popupRef.open()"></image>
        </view>
      </view>
      <view class="info_item info_nickname">
        <view class="label"><text class="must">*</text>昵称</view>
        <input
          v-model="info.nickName"
          class="input_box"
          placeholder="请输入昵称"
          maxlength="20"
          placeholder-style="color:rgba(169, 170, 181, 1);text-align: right;font-size:30rpx;"
        />
      </view>
    </view>
    <view class="btn">
      <button class="single btn_save" @click="saveUpdate">保存</button>
      <button v-if="pageType === 1" class="single btn_quit" @click="() => (showCustomPopup = true)">
        退出登录
      </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>
      </uni-popup>
    </view>
    <!-- 确认弹窗 -->
    <CustomPopup
      v-model="showCustomPopup"
      titleText="温馨提示"
      @handleConfirmBtn="handleConfirmPopup"
    >
      <view class="confirm_box"> 是否确定退出登录？ </view>
    </CustomPopup>
  </view>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { user } from '@/store';
import { updateUserInfoApi } from '@/api';
import { storeToRefs } from 'pinia';
import router from '@/router/router';
import CustomPopup from '@/components/CustomPopup/index.vue';
// #ifdef H5
import { h5Authorization } from '@/store';
const { authorizedLogin } = h5Authorization();
// #endif
const popupRef = ref(null);
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 { logout, getUserInfo } = user();
const { userInfo } = storeToRefs(user());
const indicatorStyle = ref(`height: 50px;`);
const showCustomPopup = ref(false);
const pageType = ref(); // 1-非首次注册进入
const pickList = ref([
  {
    name: '从相册选择',
    type: 1,
    sourceType: 'album',
  },
  {
    name: '拍照上传',
    type: 2,
    sourceType: 'camera',
  },
]);
const info = ref({
  avatar: '', // 图片id
  avatarUrl: '',
  id: '', // 用户id
  nickName: '',
});

function handlePreview() {
  if (!info.value.avatarUrl) return;
  uni.previewImage({
    urls: [info.value.avatarUrl],
    current: 0,
  });
}

function chooseUploadMethod(i) {
  popupRef.value.close();
  uni.chooseImage({
    count: 1, // 最多可以选择的图片张数
    sizeType: ['compressed', 'original'], // original 原图，compressed 压缩图，默认二者都有
    sourceType: [i.sourceType], // album 从相册选图，camera 使用相机，默认二者都有
    success: res => {
      router.navigateTo({
        path: `/pages/mine/prefectInformation/cropper`,
        query: { file: res.tempFilePaths[0] }
      });
    },
    fail: err => {
      // 图片接口调用失败的回调函数
      console.log('chooseImage fail', err);
    },
  });
}

async function saveUpdate() {
  if (!info.value.nickName || !info.value.avatar) {
    uni.showToast({
      icon: 'none',
      title: '头像、昵称不能为空',
    });
    return;
  }
  uni.showLoading({ title: '更新中...' });
  try {
    await updateUserInfoApi(info.value);
    await getUserInfo();
    uni.hideLoading();
    router.redirectTo('/pages/mine/index');
  } catch (err) {
    uni.hideLoading();
  }
}

function handleConfirmPopup() {
  showCustomPopup.value = false;
  logout();
}

onLoad(option => {
  pageType.value = option.type ? Number(option.type) : undefined;
  uni.$on('filePathMsg', data => {
    info.value.avatarUrl = data.filePath;
    info.value.avatar = data.id;
    pageType.value = data.type;
  });
  for (let key in info.value) {
    info.value[key] = userInfo.value[key];
  }
});
onMounted(() => {
  // #ifdef H5
  if (pageType.value === 1) return;
  authorizedLogin();
  // #endif
});
onUnmounted(() => {
  uni.$off('filePathMsg');
});
</script>

<style lang="scss" scoped>
.page {
  // padding: 30rpx;
  padding: 0 30rpx 30rpx 30rpx;
  .confirm_box {
    margin-top: 50rpx;
  }
  .info {
    padding: 0 30rpx;
    margin: 30rpx 0 100rpx 0;
    background-color: #fff;
    border-radius: 20rpx;

    &_item {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

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

      .must {
        color: red;
      }
    }

    &_header {
      padding: 20rpx 0;
      border-bottom: 1rpx solid rgba(238, 238, 238, 1);
    }

    &_nickname {
      padding: 28rpx 0;

      .input_box {
        text-align: right;
        width: 420rpx;
        font-size: 30rpx;
        color: rgba(51, 51, 51, 1);
        line-height: 42rpx;
      }
    }

    .photo {
      display: flex;
      align-items: center;

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

      .arrow {
        margin-left: 10rpx;
        width: 30rpx;
        height: 30rpx;
        transform: rotate(-90deg);
      }
    }
  }

  .btn {
    .single {
      margin: 0 0 40rpx 0;
      height: 90rpx;
      width: 100%;
      line-height: 90rpx;
      font-size: 30rpx;
      border-radius: 20rpx;

      &::after {
        border: none;
      }
    }

    &_save {
      background-color: rgba(97, 93, 255, 1);
      color: #fff;
    }

    &_quit {
      background-color: rgba(239, 239, 255, 1);
      color: rgba(97, 93, 255, 1);
    }
  }

  .popup_box {
    height: 351rpx;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    overflow: hidden;

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

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

      .item {
        padding: 30rpx 0;
        border-bottom: 1rpx solid rgba(235, 235, 235, 1);
        font-weight: 400;
        height: 45rpx;
        color: rgba(51, 51, 51, 1);
      }
    }
  }
}
</style>
