<script setup lang="ts">
import { getMemberProfileApi, putMemberProfileApi } from '@/api/member'
import { ref } from 'vue'
import type { gender, profileDetail } from '@/types/member'
import { useMemberStore } from '@/stores'
import { onShowRefreshData } from '@/utils/common'
import { uploadApi } from '@/api/common'
import { reactive } from 'vue'
import { safeTop } from '@/utils/constants'
import changePassword from './components/change-password.vue'
import changePhone from './components/change-phone.vue'

const memberStore = useMemberStore()

const realPhone = ref('')
// 获取用户信息
const profileData = ref<profileDetail>({} as profileDetail)
const getMemberProfileData = async () => {
  const res = await getMemberProfileApi()
  profileData.value = res.result

  realPhone.value = res.result.mobile

  memberStore.setProfile(profileData.value as any)
}

//修改性别
const onGenderChange: UniHelper.RadioGroupOnChange = (event) => {
  profileData.value.gender = event.detail.value as gender
}

//修改生日
const onBirthdayChange: UniHelper.DatePickerOnChange = (event) => {
  profileData.value.birthday = event.detail.value
}

const model = reactive({
  imageUrl: '',
  resultUrl: [],
})

// #ifdef MP-WEIXIN
const onChooseAvatar = (event: UniHelper.ButtonOnChooseavatarEvent) => {
  const { avatarUrl } = event.detail
  if (!avatarUrl) {
    uni.showToast({
      icon: 'error',
      title: '获取头像异常，请稍后再试',
    })
    return
  }
  model.imageUrl = avatarUrl
}
// #endif

// #ifndef MP-WEIXIN
const onChooseUserAvatar = () => {
  uni.chooseImage({
    success: (chooseImageRes) => {
      const tempFilePaths = chooseImageRes.tempFilePaths
      model.imageUrl = tempFilePaths[0]
    },
  })
}
// #endif

const onInputNickName = (event: UniHelper.InputOnInputEvent) => {
  profileData.value.nickname = event.detail.value
}

const onCancel = () => {
  model.imageUrl = ''
}

const onConfirm = (res: any) => {
  // console.log('裁剪结果', res)

  model.imageUrl = ''
  const avatarUrl = res.tempFilePath

  if (!avatarUrl) {
    uni.showToast({
      icon: 'error',
      title: '请选择头像',
    })
  }

  uploadApi(avatarUrl).then((res) => {
    // console.log(res)
    putMemberProfileApi({
      avatar: res.result.url,
    }).then((res) => {
      profileData.value.avatar = res.result.avatar
      memberStore.profile!.avatar = res.result.avatar
    })

    setTimeout(() => {
      uni.showToast({
        icon: 'success',
        title: '修改成功',
      })
    }, 1000)
  })
}

//保存信息
const onSubmit = async () => {
  if (!profileData.value.nickname) {
    uni.showToast({
      icon: 'error',
      title: '请填写用户昵称',
    })
    return
  }
  if (!/^[A-Za-z0-9*]{4,11}$/.test(profileData.value.username)) {
    uni.showToast({
      icon: 'error',
      title: '用户名要求4~11位，仅能包含字母、数字和 * ',
      duration: 3000,
    })
    return
  }
  const res = await putMemberProfileApi({
    username: profileData.value.username,
    nickname: profileData.value.nickname,
    gender: profileData.value.gender,
    birthday: profileData.value.birthday,
  })
  memberStore.profile = Object.assign({}, memberStore.profile, profileData.value)
  uni.showToast({
    icon: 'success',
    title: '修改成功',
  })
}

//修改密码
const changePasswordRef = ref()
const onChangePassword = () => {
  changePasswordRef.value?.open()
}

//修改手机
const changePhoneRef = ref()
const onChangePhone = () => {
  changePhoneRef.value?.open()
}

onShowRefreshData(() => {
  getMemberProfileData()
})
</script>

<template>
  <view class="viewport" v-if="profileData">
    <!-- 导航栏 -->
    <view class="navbar" :style="safeTop">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <t-cropper
      mode="fixed"
      :imageUrl="model.imageUrl"
      :width="160"
      :height="160"
      :radius="80"
      :delay="10"
      @cancel="onCancel"
      @confirm="onConfirm"
    />
    <view class="avatar">
      <!-- #ifdef MP-WEIXIN -->
      <button class="avatar-content" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <shop-user-avatar :url="profileData.avatar || ''" width="200" />
        <text class="text"> 点击修改头像 </text>
      </button>
      <!-- #endif -->
      <!-- #ifndef MP-WEIXIN -->
      <button class="avatar-content" @tap="onChooseUserAvatar">
        <shop-user-avatar :url="profileData.avatar || ''" width="200" />
        <text class="text"> 点击修改头像 </text>
      </button>
      <!-- #endif -->
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">用户名</text>
          <input
            class="input"
            v-model="profileData.username"
            placeholder="请填写用户名"
            placeholder-class="placeholder"
          />
        </view>
        <view class="form-item">
          <text class="label">用户昵称</text>
          <input
            class="input"
            type="nickname"
            v-model="profileData.nickname"
            @blur="onInputNickName"
            placeholder-class="placeholder"
            placeholder="请填写用户昵称"
          />
        </view>
        <view class="form-item">
          <text class="label">用户性别</text>
          <radio-group @change="onGenderChange">
            <label class="radio">
              <radio value="0" color="#ff5f3c" :checked="profileData.gender == '0'" />
              保密
            </label>
            <label class="radio">
              <radio value="1" color="#ff5f3c" :checked="profileData.gender == '1'" />
              男
            </label>
            <label class="radio">
              <radio value="2" color="#ff5f3c" :checked="profileData.gender == '2'" />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">用户生日</text>
          <picker
            @change="onBirthdayChange"
            class="picker"
            mode="date"
            start="1900-01-01"
            :value="profileData.birthday"
          >
            <view v-if="profileData.birthday">{{ profileData.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
          <text class="icon icon-right"></text>
        </view>
        <view class="form-item" @tap="onChangePhone">
          <text class="label">手机号码</text>
          <text class="placeholder">修改手机号码</text>
          <text class="icon icon-right"></text>
        </view>
        <view class="form-item" @tap="onChangePassword">
          <text class="label">登录密码</text>
          <text class="placeholder">修改登录密码</text>
          <text class="icon icon-right"></text>
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @tap="onSubmit" form-type="submit">保 存</button>
    </view>
  </view>

  <change-password ref="changePasswordRef" />

  <change-phone ref="changePhoneRef" :phone="realPhone" v-if="realPhone" />
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  background-repeat: no-repeat;
  background-image: url('~@/static/images/navigator_bg.png');
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    padding-bottom: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

.avatar-content {
  background-color: transparent;
  border: none;
  padding: 0;
  margin: 0;
  outline: none;
  cursor: pointer;

  &::after {
    border: none;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 25rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      font-size: 28rpx;
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #ff5f3c;
  }

  .icon-right {
    position: absolute;
    right: 45rpx;
    color: #cecece;
  }
}
</style>
