<template>
  <view class="container" :style="{paddingTop: navbarHeight + 'rpx'}">
    <!-- 顶部渐变背景 -->
    <view class="top-gradient"></view>

    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{paddingTop: statusBarHeight + 'px'}">
      <view class="navbar-content">
        <view class="navbar-back" @click="handleBack">
          <view class="iconfont icon-right back-icon"></view>
        </view>
        <text class="navbar-title">账号信息</text>
        <view class="navbar-placeholder"></view>
      </view>
    </view>

    <!-- 第一个卡片：基本信息 -->
    <view class="info-card">
      <view class="info-item" @click="handleAvatar">
        <view class="item-label">头像</view>
        <view class="item-value">
          <image v-if="user.headImg" :src="user.headImg" class="avatar-img" mode="aspectFill"></image>
          <view v-else class="avatar-placeholder">
            <view class="iconfont icon-people"></view>
          </view>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('name')">
        <view class="item-label">姓名</view>
        <view class="item-value">
          <text class="value-text">{{ user.nickName || user.userName || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('intro')">
        <view class="item-label">简介</view>
        <view class="item-value">
          <text class="value-text placeholder">{{ user.intro || '添加一条简介' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('phone')">
        <view class="item-label">手机号码</view>
        <view class="item-value">
          <text class="value-text">{{ user.phonenumber || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item">
        <view class="item-label">接单状态</view>
        <view class="item-value">
          <text class="status-text" :class="{ active: orderStatus }">{{ orderStatus ? '接单中' : '暂停接单' }}</text>
          <switch :checked="orderStatus" @change="handleOrderStatusChange" color="#007AFF" />
        </view>
      </view>
    </view>

    <!-- 第二个卡片：专业和财务信息 -->
    <view class="info-card">
      <view class="info-item" @click="handleEdit('practiceTime')">
        <view class="item-label">从业时间</view>
        <view class="item-value">
          <text class="value-text">{{ user.practiceTime || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('professionalField')">
        <view class="item-label">专业领域</view>
        <view class="item-value">
          <text class="value-text">{{ user.professionalField || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('legalScenarios')">
        <view class="item-label">法律场景</view>
        <view class="item-value">
          <text class="value-text">{{ user.legalScenarios || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('lawFirm')">
        <view class="item-label">所属律所</view>
        <view class="item-value">
          <text class="value-text">{{ user.lawFirm || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('receivingAccount')">
        <view class="item-label">收款账户</view>
        <view class="item-value">
          <text class="value-text">{{ user.receivingAccount || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
      <view class="info-divider"></view>
      <view class="info-item" @click="handleEdit('address')">
        <view class="item-label">联系地址</view>
        <view class="item-value">
          <text class="value-text">{{ user.address || '未设置' }}</text>
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
    </view>

    <!-- 第三个卡片：账号管理 -->
    <view class="info-card">
      <view class="info-item" @click="handleDeregister">
        <view class="item-label">注销账号</view>
        <view class="item-value">
          <view class="iconfont icon-right arrow-icon"></view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { getLawyerInfo, editLawyerUser } from "@/api/api"
  import upload from '@/utils/upload'
  import config from '@/config'

  export default {
    data() {
      return {
        user: {},
        orderStatus: true,
        statusBarHeight: 0
      }
    },
    onLoad() {
      // 获取状态栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0
    },
    onShow() {
      // 从其他页面返回时刷新数据
      this.getLawyerInfoData()
    },
    computed: {
      navbarHeight() {
        // 状态栏高度(px转rpx) + 导航栏高度(88rpx) + 间距(20rpx)
        return (this.statusBarHeight * 2) + 88 + 20
      }
    },
    methods: {
      getLawyerInfoData() {
        getLawyerInfo({ lawyerId: 1 }).then(response => {
          // 处理返回的律师信息
          if (response.data) {
            // 合并律师信息到 user 对象
            this.user = { ...this.user, ...response.data }
            // 如果有接单状态字段，使用它
            if (response.data.orderStatus !== undefined) {
              this.orderStatus = response.data.orderStatus
            }
          }
        }).catch(error => {
          console.error('获取律师信息失败:', error)
        })
      },
      handleAvatar() {
        const that = this
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album'],
          success: function(res) {
            const tempFilePath = res.tempFilePaths[0]
            // 显示上传中提示
            uni.showLoading({
              title: '上传中...',
              mask: true
            })

            // 上传图片，使用 baseUrl1
            upload({
              url: '/file/upload',
              filePath: tempFilePath,
              name: 'file',
              baseUrl: config.baseUrl1
            }).then(response => {
              console.log('上传响应:', response)
              // 上传成功，更新用户头像
              // 根据实际返回的数据结构处理
              let headImg = null
              if (response.data) {
                // 如果 response.data 是字符串，直接使用
                if (typeof response.data === 'string') {
                  headImg = response.data
                } 
                // 如果 response.data 是对象，尝试获取 url 或 imgUrl
                else if (response.data.url) {
                  headImg = response.data.url
                } else if (response.data.imgUrl) {
                  headImg = response.data.imgUrl
                }
              } else if (response.url) {
                headImg = response.url
              } else if (response.imgUrl) {
                headImg = response.imgUrl
              }
              
              if (!headImg) {
                throw new Error('上传失败，未返回图片地址')
              }
              
              // 如果返回的是相对路径，需要拼接 baseUrl1
              if (headImg.startsWith('/')) {
                headImg = config.baseUrl1 + headImg
              }
              
              // 使用 Vue.set 确保响应式更新
              that.$set(that.user, 'headImg', headImg)
              
              // 调用API更新用户信息到服务器
              let params={
                id:that.user.id,
                headImg: headImg
              }      
              editLawyerUser(params).then(response => {
                console.log('更新响应:', response)
              }).catch(error => {
                console.error('更新失败:', error)
              })

            }).then(() => {
              // 更新成功提示
              uni.showToast({
                title: '头像更新成功'
              })
            }).catch(error => {
              uni.hideLoading()
              console.error('上传头像失败:', error)
              uni.showToast({
                title: error.message || '上传失败，请重试',
                icon: 'none'
              })
            })
          },
          fail: function(error) {
            console.error('选择图片失败:', error)
            uni.showToast({
              title: '选择图片失败',
              icon: 'none'
            })
          }
        })
      },
      handleEdit(field) {
        // 根据字段类型跳转到不同的编辑页面
        if (field === 'name') {
          // 跳转到姓名编辑页面
          const currentName = this.user.nickName || this.user.userName || ''
          const userId = this.user.id || 1
          this.$tab.navigateTo(`/pages/mine/info/name?name=${encodeURIComponent(currentName)}&userId=${userId}`)
        } else {
          // 其他字段跳转到通用编辑页面
          this.$tab.navigateTo('/pages/mine/info/edit')
        }
      },
      handleOrderStatusChange(e) {
        this.orderStatus = e.detail.value
        // 这里可以调用API更新接单状态
        // updateOrderStatus(this.orderStatus)
      },
      handleDeregister() {
        this.$modal.confirm('确定要注销账号吗？注销后将无法恢复。').then(() => {
          // 调用注销账号API
          this.$modal.showToast('注销账号功能开发中')
        })
      },
      handleBack() {
        uni.navigateBack()
      }
    }
  }
</script>

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

  .container {
    min-height: 100vh;
    padding: 0 30rpx 20rpx 30rpx;
    background-color: #f5f5f5;
    position: relative;

    // 顶部渐变背景
    .top-gradient {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      height: 800rpx;
      background: linear-gradient(180deg, rgba(59, 130, 246, 0.1) 0%, rgba(147, 197, 253, 0.05) 50%, transparent 100%);
      z-index: 0;
      pointer-events: none;
    }

    // 自定义导航栏
    .custom-navbar {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 999;
      background-color: transparent;
      pointer-events: none;

      .navbar-content {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88rpx;
        pointer-events: auto;
        position: relative;

        .navbar-back {
          position: absolute;
          left: 30rpx;
          width: 60rpx;
          height: 60rpx;
          display: flex;
          align-items: center;
          justify-content: center;

          .back-icon {
            font-size: 36rpx;
            color: #000000;
            transform: rotate(180deg);
          }
        }

        .navbar-title {
          font-size: 36rpx;
          font-weight: 500;
          color: #000000;
        }

        .navbar-placeholder {
          position: absolute;
          right: 30rpx;
          width: 60rpx;
          height: 60rpx;
        }
      }
    }
  }

  .info-card {
    background-color: #ffffff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

    .info-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 32rpx 30rpx;
      min-height: 100rpx;

      .item-label {
        font-size: 32rpx;
        color: #000000;
        font-weight: 400;
      }

      .item-value {
        display: flex;
        align-items: center;
        flex: 1;
        justify-content: flex-end;

        .avatar-img {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          margin-right: 20rpx;
        }

        .avatar-placeholder {
          width: 80rpx;
          height: 80rpx;
          border-radius: 50%;
          background-color: #e0e0e0;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 20rpx;

          .iconfont {
            font-size: 40rpx;
            color: #999999;
          }
        }

        .value-text {
          font-size: 32rpx;
          color: #000000;
          margin-right: 20rpx;

          &.placeholder {
            color: #999999;
          }
        }

        .status-text {
          font-size: 32rpx;
          color: #999999;
          margin-right: 20rpx;

          &.active {
            color: #007AFF;
          }
        }

        .arrow-icon {
          font-size: 28rpx;
          color: #cccccc;
        }
      }
    }

    .info-divider {
      height: 1rpx;
      background-color: #f0f0f0;
      margin: 0 30rpx;
    }
  }
</style>
