<template>
  <view class="user-info-container" :style="{ minHeight: containerHeight + 'rpx' }">
    <!-- 内容区域 -->
    <view class="content">
      <!-- 头像区域 -->
      <view class="avatar-section">
        <view class="app-info">
          <image class="app-logo" :src="configParamContent('login_logo')" mode="aspectFit"></image>
          <text class="app-name">{{ configParamContent('app_name') }}</text>
          <text class="app-subname">申请获取您的头像，昵称</text>
        </view>
      </view>
      
      <!-- 表单区域 -->
      <view class="form-section">
      <!-- 头像 -->
      <view class="form-item">
        <text class="form-label">头像</text>
        <view class="avatar-button">
          <!-- #ifdef MP-WEIXIN -->
          <button class="avatar-btn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
            <image 
              class="avatar-image" 
              :src="userInfo.avatar || '/static/default-avatar.png'" 
              mode="aspectFill"
            ></image>
          </button>
          <!-- #endif -->

          <!-- #ifndef MP-WEIXIN -->
          <button class="avatar-btn" @click="chooseImageH5">
            <image 
              class="avatar-image" 
              :src="userInfo.avatar || '/static/default-avatar.png'" 
              mode="aspectFill"
            ></image>
          </button>
          <!-- #endif -->
        </view>
      </view>
      
      <!-- 昵称 -->
      <view class="form-item">
        <text class="form-label">昵称</text>
        <input 
          class="form-input" 
          type="nickname" 
          v-model="userInfo.name" 
          placeholder="请输入昵称"
          @blur="nameBlur"
          
        />
      </view>
      
      <!-- 手机号 -->
      <view class="form-item">
        <text class="form-label">手机号</text>
        <!-- #ifdef MP-WEIXIN -->
        <view class="phone-container" v-if="!userInfo.phone">
          <button 
            class="get-phone-btn" 
            open-type="getPhoneNumber" 
            @getphonenumber="getPhoneNumber"
          >
            获取手机号
          </button>
        </view>
        <text class="form-label" v-else>{{ userInfo.phone }}</text>
        <!-- #endif -->

        <!-- #ifndef MP-WEIXIN -->
        <input 
          class="form-input" 
          type="number" 
          v-model="userInfo.phone" 
          placeholder="请输入手机号"
        />
        <!-- #endif -->
      </view>
      
      <!-- 所在部门 -->
      <!-- <view class="form-item">
        <text class="form-label">所在部门</text>
        <view class="department-container" @click="showDepartmentPicker">
          <text class="department-text" :class="{ 'active': userInfo.department.title }">{{ userInfo.department.title || '请选择' }}</text>
          <uv-icon name="arrow-down" size="20" color="#000"></uv-icon>
        </view>
      </view> -->
      
      <!-- 备注 -->
      <!-- <view class="form-item ">
        <text class="form-label">备注<text class="form-remark">(非必填)</text></text>
        <input 
          class="form-input" 
          v-model="userInfo.remark" 
        />
      </view> -->

      </view>
      
      <!-- 确定按钮 -->
      <view class="submit-section">
        <view class="submit-btn" @click="submitUserInfo">
          <text class="submit-text">确定</text>
        </view>
      </view>
    </view>
    
    <!-- 部门选择器 -->
    <uv-picker 
      confirm-color="#C70019"
      ref="departmentPicker"
      :columns="departmentColumns"
      keyName="title"
      @confirm="confirmDepartment"
      @cancel="cancelDepartment"
    ></uv-picker>
  </view>
</template>

<script>
export default {
  name: 'UserInfo',
  data() {
    return {
      userInfo: {
        avatar: '',
        name: '',
        phone: '',
        department: {
          title: '',
          id: ''
        },
        remark: ''
      },
      showDepartmentSheet: false,
      // 部门选择器数据
    }
  },
  async onLoad() {
    this.calculateContainerHeight();

    await this.getUserInfo();
  },
  computed: {
    // 部门选择器数据格式转换
    departmentColumns() {
      if (!this.$store.state.departmentList || this.$store.state.departmentList.length === 0) {
        return [[]]
      }

      const departmentNames = this.$store.state.departmentList.map(item => {
        return {
          title: item.title,
          id: item.id
        }
      })
      return [departmentNames]
    }
  },
  methods: {
    // 获取微信用户信息
    async getWechatUserInfo() {
     const { result } = await this.$api.user.queryUser()
      this.userInfo.name = result.name
      this.userInfo.avatar = result.avatar
      this.userInfo.phone = result.phone
    },
    
    // 提交表单
    async getUserInfo(){
      const { result:info } = await this.$api.login.getUserInfo()
      this.userInfo.name = info.name
      this.userInfo.avatar = info.headImage
      this.userInfo.phone = info.phone
    },

    // 选择头像并上传到OSS
    async onChooseAvatar(e) {
      console.log('选择头像回调', e);
      if (e.detail.avatarUrl) {
        try {
          // 显示上传中提示
          uni.showLoading({ title: '上传头像中...' });
          
          // 构造文件对象
          const file = {
            path: e.detail.avatarUrl,
            tempFilePath: e.detail.avatarUrl
          };
          
          // 上传到OSS
          const uploadResult = await this.$utils.uploadImage(file);
          
          uni.hideLoading();
          
          if (uploadResult.success) {
            // 上传成功，更新头像URL
            this.userInfo.avatar = uploadResult.url;
            console.log('头像上传成功', uploadResult.url);
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            });
          } else {

          }
        } catch (error) {
          uni.hideLoading();
          console.error('头像上传异常:', error);
          // 异常情况下使用本地头像
          this.userInfo.avatar = e.detail.avatarUrl;
          uni.showToast({
            title: '头像处理异常，使用本地头像',
            icon: 'none'
          });
        }
      } else {
        uni.showToast({
          title: '头像选择失败',
          icon: 'none'
        });
      }
    },

    // 公众号/H5 选择图片并上传头像
    // #ifndef MP-WEIXIN
    async chooseImageH5() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        })

        const filePath = (res.tempFilePaths && res.tempFilePaths[0])
          || (res.tempFiles && res.tempFiles[0] && (res.tempFiles[0].path || res.tempFiles[0].tempFilePath))

        if (!filePath) {
          uni.showToast({ title: '未选择图片', icon: 'none' })
          return
        }

        uni.showLoading({ title: '上传头像中...' })

        const file = { path: filePath, tempFilePath: filePath }
        const uploadResult = await this.$utils.uploadImage(file)

        uni.hideLoading()

        if (uploadResult && uploadResult.success) {
          this.userInfo.avatar = uploadResult.url
          uni.showToast({ title: '头像上传成功', icon: 'success' })
        } else {
          // 上传失败则先本地显示
          this.userInfo.avatar = filePath
          uni.showToast({ title: '头像已选择', icon: 'none' })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('选择/上传头像异常:', error)
        uni.showToast({ title: '头像处理异常', icon: 'none' })
      }
    },
    // #endif
    

    // 昵称输入失焦
    nameBlur() {
      if (!this.userInfo.name.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
      }
    },
    
    // // 微信昵称审核回调
    // onNicknameReview(e) {
    //   console.log('微信昵称审核回调', e);
    //   if (e.detail.pass) {
    //     // 审核通过，使用微信昵称
    //     this.userInfo.name = e.detail.value;
    //     console.log('微信昵称审核通过:', e.detail.value);
    //   } else {
    //     // 审核不通过
    //     console.log('微信昵称审核不通过');
    //     uni.showToast({
    //       title: '昵称包含敏感词，请重新输入',
    //       icon: 'none'
    //     });
    //   }
    // },
    
    // 显示部门选择器
    showDepartmentPicker() {
      this.$refs.departmentPicker.open();
    },
    
    // 确认部门选择
    confirmDepartment(e) {
      this.userInfo.department = e.value[0];
    },
    
    // 取消部门选择
    cancelDepartment() {
      // 取消操作
    },
    
    // 选择部门（保留原方法以防其他地方使用）
    selectDepartment(item) {
      this.userInfo.department = item.value;
      this.showDepartmentSheet = false;
    },
    
    // 获取手机号
    // #ifdef MP-WEIXIN
    async getPhoneNumber(e) {
      console.log('获取手机号回调', e);
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        // 获取成功，可以通过e.detail.code发送到后端换取手机号
        console.log('获取手机号成功', e.detail);
        const { result:phoneRes } = await this.$api.login.bindPhone({
          code: e.detail.code
        })
        
        this.userInfo.phone = phoneRes
        uni.showToast({
          title: '手机号获取成功',
          icon: 'success'
        });
      } else {
        // 如果失败了就申请开启权限
        uni.showToast({
          title: '手机号获取失败',
          icon: 'error'
        })
      }
    },
    // #endif
    
    // 提交用户信息
    async submitUserInfo() {
      if (!this.userInfo.name?.trim()) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        });
        return;
      }
      
      if (!this.userInfo.phone?.trim()) {
        uni.showToast({
          title: '请输入手机号',
          icon: 'none'
        });
        return;
      }
      
      // 简单手机号格式校验（大陆手机号）
      const phoneReg = /^1[3-9]\d{9}$/
      if (!phoneReg.test(this.userInfo.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      

      
      console.log('提交用户信息', this.userInfo);
      
      try {
        // 提交用户信息
        await this.$api.login.updateUserInfo({
          name: this.userInfo.name,
          phone: this.userInfo.phone,
          avatar: this.userInfo.avatar,

        });

        uni.showToast({
          title: '信息保存成功',
          icon: 'success'
        });
        
        // 跳转到首页
        setTimeout(() => {
          uni.switchTab({
            url: '/pages/index/home'
          });
        }, 1000);
      } catch (error) {
        console.error('保存用户信息失败:', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.user-info-container {
  background-color: #fff;
  box-sizing: border-box;
  padding-top: 200rpx;
}

.content {
  padding: 0 66rpx;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 90rpx;
  margin-top: 192rpx;
  .app-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 22rpx;
    .app-logo {
      width: 92rpx;
      height: 92rpx;
      // border-radius: 20rpx;
      // margin-bottom: 23rpx;
    }
    
    .app-name {
      font-size: 36rpx;
      font-weight: bold;
      color: $primary-text-color;
    }

    .app-subname {
      font-size: 30rpx;
      color: $primary-text-color;
    }
  }
}

.form-item {
  // background: green;
  display: flex;
  align-items: center;
  // margin-bottom: 30rpx;
  height: 114rpx;
  justify-content: space-between;
  
  &:last-child {
    margin-bottom: 45rpx;
  }
  
  .form-label {
    // width: 120rpx;
    // flex: 1;
    font-size: 32rpx;
    color: $primary-text-color;
    // font-weight: 500;
  }
  
  .form-input {
    // flex: 1;
    // height: 80rpx;
    // padding: 0 20rpx;
    // border-radius: 10rpx;
    font-size: 30rpx;
    color: $primary-text-color;
    border: none;
    background-color: transparent;
    text-align: right;
  }
  .form-remark {
    margin-left: 16rpx;
    color: $secondary-text-color;
  }

  .department-container{
    display: flex;
    align-items: center;
    gap: 22rpx;
    color: $secondary-text-color;

    .department-text.active {
      color: $primary-text-color;
    }
  }
}

// 头像按钮
.avatar-button {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  
  .avatar-btn {
    margin: 0;
    padding: 0;
    background: transparent;
    border: none;
    width: 100rpx;
    height: 100rpx;
    border: 2rpx solid #cccccc;
    text-align: left;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    
    &::after {
      border: none;
    }
  }
  
  .avatar-image {
    width: 100rpx;
    height: 100rpx;
    // border-radius: 10rpx;
  }
}


  // background: white;
  .get-phone-btn {
    // margin-left: auto;
    width: 176rpx;
    height: 76rpx;
    background-color: $primary-color;
    color: white;
    border-radius: 38rpx;
    font-size: 22rpx;
    line-height: 76rpx;
    border: none;
    
    &::after {
      border: none;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
  
// }





.submit-section {
  width: 594rpx;
  height: 94rpx;
  margin: 0 auto;
  
  .submit-btn {
    width: 100%;
    height: 94rpx;
    background-color: $primary-color;
    border-radius: 41rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .submit-text {
      font-size: 32rpx;
      // font-weight: 500;
      color: #ffffff;
    }
  }
}
</style>