<template>
  <view class="user-profile">
    <!-- 头像区域 -->
    <view class="avatar-container">
      <image :src="tempAvatarUrl || user.errandAvatarUrl || '../../static/logo.png'" mode="aspectFill" class="avatar" @tap="chooseImage"></image>
      <text class="edit-text">点击修改头像</text>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="label">昵称</text>
        <input type="text" v-model="user.errandName" class="input-field"/>
      </view>
      <view class="form-item gender-item">
        <text class="label">性别</text>
        <radio-group class="gender-container">
          <label>
            <radio :checked="user.gender === 0" value="male" @click="user.gender = 0"></radio>
            <text>男</text>
          </label>
          <label>
            <radio :checked="user.gender === 1" value="female" @click="user.gender = 1"></radio>
            <text>女</text>
          </label>
        </radio-group>
      </view>
      <view class="form-item">
        <text class="label">手机</text>
        <input type="text" v-model="user.errandPhone" class="input-field"/>
      </view>
	  <view class="form-item">
	    <text class="label">范围</text>
	    <input type="text" v-model="user.distributionScope" class="input-field"/>
	  </view>
    </view>

    <!-- 保存按钮 -->
    <button class="save-button" @click="saveUser">保 存</button>
  </view>
</template>

<script setup>
import {
  apiImageUrl
} from '../../API/api';
import { onMounted, ref } from 'vue';
import { onShow } from "@dcloudio/uni-app";

const user = ref({ errandName: '未登录', errandAvatarUrl: '', gender: '', errandPhone: '',distributionScope:'' });
const tempAvatarUrl = ref('');

// 获取当前用户信息
const getCurrentUser = () => {
  uni.request({
    url: apiImageUrl + '/api/errand/get/current',
    method: 'POST',
    header: {
      'cookie': uni.getStorageSync("cookie")
    },
    success(res) {
      console.log(res);
      if (res.data.code === 0 && res.data.data) { // 检查HTTP状态码和业务状态码，并确保有返回的数据
        Object.assign(user.value, res.data.data); // 更新用户信息
      }
    },
    fail(err) {
      console.error('请求失败:', err);
    }
  });
};

// 页面显示时获取用户信息
onShow(() => {
  getCurrentUser();
});

// 组件挂载时也获取用户信息
onMounted(() => {
  getCurrentUser();
});

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePaths = res.tempFilePaths;
      tempAvatarUrl.value = tempFilePaths[0];
      uploadImage(tempFilePaths[0]);
    }
  });
};

// 上传图片
const uploadImage = (filePath) => {
  uni.uploadFile({
    url: apiImageUrl + '/api/file/upload/server',
    filePath,
    name: 'file',
    formData: {
      biz: 'user_avatar'
    },
    success: (res) => {
      const data = JSON.parse(res.data);
      if (data.code === 0) {
        user.value.errandAvatarUrl = data.data.url; // 注意这里应该是errandAvatarUrl而非avatarUrl
        tempAvatarUrl.value = '';
      }
    },
    fail: (err) => {
      console.error('上传失败:', err);
    }
  });
};

// 保存用户信息
const saveUser = () => {
  const updatedUser = {
    distributionScope: user.value.distributionScope,
    errandName: user.value.errandName,
    errandPhone: user.value.errandPhone,
    gender: user.value.gender,
    id: user.value.id,
    state: 0
  };

  uni.request({
    url: apiImageUrl + '/api/errand/update/my',
    method: 'POST',
    data: updatedUser,
    header: {
      'Content-Type': 'application/json',
      'cookie': uni.getStorageSync("cookie")
    },
    success(res) {
      if (res.data.code === 0) {
        uni.showToast({
          title: '更新成功',
          icon: 'success'
        });
        // 更新成功后重新获取用户信息
        getCurrentUser();
      } else {
        uni.showToast({
          title: '更新失败',
          icon: 'none'
        });
      }
    },
    fail(err) {
      console.error('请求失败:', err);
    }
  });
};
</script>
<style scoped>
.user-profile {
  background: linear-gradient(to bottom, #5e7dec,white);
  padding: 20px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100vh;
}

.avatar-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.avatar-container .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.edit-text {
  color: white;
  margin-top: 10px;
}

.form-container {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.label {
  width: 35px;
  text-align: right;
  margin-right: 10px;
}

.gender-item {
  align-items: flex-start;
}

/* 确保性别选项水平显示 */
.gender-container {
  display: flex;
  flex-direction: row; /* 默认值为row，这里明确指定是为了清晰 */
}

.gender-container label {
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.input-field {
  flex: 1;
  box-sizing: border-box;
  border: 1px solid #ddd;
  border-radius: 4px;
  height: 45px;
  border-radius: 15px;
}

.save-button {
  background-color: transparent; /* 设置背景为透明 */
  color: white;
  padding: 0px 20px; /* 增加内边距以便按钮看起来更舒适 */
  border: 2px solid #5e7dec; /* 添加边框以增强立体感 */
  border-radius: 20px;
  margin-top: 20px;
  width: 100%;
  max-width: 300px;
  cursor: pointer;
  transition: all 0.3s ease; /* 应用到所有属性的过渡效果 */
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); /* 添加阴影以增加立体感 */
}

.save-button:hover {
  background-color: rgba(94, 125, 236, 0.1); /* 鼠标悬停时轻微改变背景颜色 */
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.2); /* 增强阴影效果 */
}

.save-button:active {
  transform: translateY(2px); /* 点击时向下移动，模拟按下的效果 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 减弱阴影效果 */
}
</style>