import request from '../../utils/request.js'

Page({
  data: {
    // 头像相关
    touxiangUrl: '', // 完整头像URL
    touxiangRelative: '', // 头像相对URL（用于上传后更新）
    
    // 打手信息字段
    dashouUid: '', // UID（不可修改）
    dashouNicheng: '', // 昵称
    dashouJieshao: '', // 个人介绍
    dashouDianhua: '', // 电话
    dashouWeixin: '', // 微信
    
    // 页面状态
    isLoading: false, // 是否正在加载
    isDataFromApi: false, // 数据是否来自API（用于显示提示）
    isSubmitting: false, // 是否正在提交
    hasLoadedFromCache: false, // 是否已从缓存加载
    
    // 验证状态
    nichengValid: true,
    dianhuaValid: true,
    weixinValid: true,
    jieshaoValid: true
  },

  onLoad() {
    // 页面加载时初始化数据
    this.initPageData()
  },

  onShow() {
    // 每次页面显示时检查头像是否需要更新
    this.registerNotificationComponent();
    this.checkAvatarUpdate()
  },
   // 🆕 新增：注册通知组件
   registerNotificationComponent() {
    const app = getApp();
    const notificationComp = this.selectComponent('#global-notification');
    
    if (notificationComp && notificationComp.showNotification) {
        console.log('🏪 商城页面注册通知组件');
        app.globalData.globalNotification = {
            show: (data) => notificationComp.showNotification(data),
            hide: () => notificationComp.hideNotification()
        };
    }
},

  // 初始化页面数据
  async initPageData() {
    this.setData({ isLoading: true })
    
    try {
      // 1. 从缓存加载基本信息
      const cachedData = this.loadFromCache()
      
      // 2. 检查是否需要从API加载
      const needApiLoad = this.checkNeedApiLoad(cachedData)
      
      if (needApiLoad) {
        // 从API加载数据
        await this.loadFromApi()
        this.setData({ isDataFromApi: true })
      } else {
        // 使用缓存数据
        this.setDataFromCache(cachedData)
        this.setData({ isDataFromApi: false })
      }
      
      // 3. 构建完整头像URL
      this.buildAvatarUrl()
      
    } catch (error) {
      console.error('初始化页面数据失败:', error)
      wx.showToast({
        title: '数据加载失败',
        icon: 'error',
        duration: 2000
      })
    } finally {
      this.setData({ isLoading: false, hasLoadedFromCache: true })
    }
  },

  // 从缓存加载数据
  loadFromCache() {
    const app = getApp()
    
    return {
      // 从缓存获取头像相对URL
      touxiang: wx.getStorageSync('touxiang') || '',
      
      // 从缓存获取用户ID
      uid: wx.getStorageSync('uid') || '',
      
      // 从缓存获取打手信息
      dsnc: wx.getStorageSync('dsnc') || '',
      dsjieshao: wx.getStorageSync('dsjieshao') || '',
      dsdianhua: wx.getStorageSync('dsdianhua') || '',
      dsweixin: wx.getStorageSync('dsweixin') || ''
    }
  },

  // 检查是否需要从API加载数据
  checkNeedApiLoad(cachedData) {
    // 如果昵称或介绍有一个为空，则需要从API加载
    return !cachedData.dsnc || !cachedData.dsjieshao
  },

  // 设置缓存数据到页面
  setDataFromCache(cachedData) {
    const app = getApp()
    
    // 处理空值显示
    const formatEmptyValue = (value) => {
      return value && value.trim() !== '' ? value : '暂未填写'
    }
    
    this.setData({
      dashouUid: cachedData.uid || '',
      dashouNicheng: cachedData.dsnc || '',
      dashouJieshao: cachedData.dsjieshao || '',
      dashouDianhua: formatEmptyValue(cachedData.dsdianhua),
      dashouWeixin: formatEmptyValue(cachedData.dsweixin),
      touxiangRelative: cachedData.touxiang || ''
    })
  },

  // 从API加载数据
  async loadFromApi() {
    try {
      const res = await request({
        url: '/yonghu/dszjxxhq',
        method: 'POST'
      })
      
      if (res && res.data.code === 200) {
        const data = res.data.data || {}
        
        // 格式化空值
        const formatValue = (value) => {
          if (value === null || value === undefined || value.trim() === '') {
            return '暂未填写'
          }
          return value
        }
        
        // 更新页面数据
        this.setData({
          dashouNicheng: formatValue(data.nicheng),
          dashouJieshao: formatValue(data.jieshao),
          dashouDianhua: formatValue(data.dianhua),
          dashouWeixin: formatValue(data.wechat)
        })
        
        // 更新缓存（即使为空也存储，避免重复请求）
        this.updateCache(data)
        
      } else {
        throw new Error(res?.data?.msg || '获取信息失败')
      }
    } catch (error) {
      console.error('API加载失败:', error)
      throw error
    }
  },

  // 更新缓存
  updateCache(data) {
    // 存储到缓存，确保字段存在（即使为空）
    wx.setStorageSync('dsnc', data.nicheng || '')
    wx.setStorageSync('dsjieshao', data.jieshao || '')
    wx.setStorageSync('dsdianhua', data.dianhua || '')
    wx.setStorageSync('dsweixin', data.wechat || '')
  },

  // 构建完整头像URL
  buildAvatarUrl() {
    const app = getApp()
    
    // 获取头像相对路径
    const touxiangRelative = this.data.touxiangRelative || ''
    
    // 获取全局配置
    const ossImageUrl = app.globalData.ossImageUrl || ''
    const morentouxiang = app.globalData.morentouxiang || ''
    
    // 构建完整URL
    let fullUrl = ''
    
    if (touxiangRelative && touxiangRelative.trim() !== '') {
      fullUrl = ossImageUrl + touxiangRelative
    } else {
      fullUrl = ossImageUrl + morentouxiang
    }
    
    this.setData({ touxiangUrl: fullUrl })
  },

  // 检查头像是否需要更新
  checkAvatarUpdate() {
    const app = getApp()
    const currentAvatar = wx.getStorageSync('touxiang') || ''
    
    // 如果缓存中的头像与当前显示的不同，重新构建URL
    if (currentAvatar !== this.data.touxiangRelative) {
      this.setData({ touxiangRelative: currentAvatar })
      this.buildAvatarUrl()
    }
  },

  // 事件处理函数
  onAvatarTap() {
    // 头像点击事件（后续可扩展为更换头像）
    wx.showToast({
      title: '头像上传功能待实现',
      icon: 'none',
      duration: 2000
    })
  },

  onNichengInput(e) {
    const value = e.detail.value
    this.setData({
      dashouNicheng: value,
      nichengValid: value.length <= 20
    })
  },

  onDianhuaInput(e) {
    const value = e.detail.value
    // 简单的手机号验证
    const isValid = /^1[3-9]\d{9}$/.test(value) || value === '' || value === '暂未填写'
    this.setData({
      dashouDianhua: value,
      dianhuaValid: isValid
    })
  },

  onWeixinInput(e) {
    const value = e.detail.value
    this.setData({
      dashouWeixin: value,
      weixinValid: value.length <= 30
    })
  },

  onJieshaoInput(e) {
    const value = e.detail.value
    this.setData({
      dashouJieshao: value,
      jieshaoValid: value.length <= 200
    })
  },

  // 表单验证
  validateForm() {
    const {
      dashouNicheng,
      dashouDianhua,
      dashouWeixin,
      dashouJieshao,
      nichengValid,
      dianhuaValid,
      weixinValid,
      jieshaoValid
    } = this.data
    
    // 1. 验证昵称
    if (!dashouNicheng || dashouNicheng.trim() === '') {
      wx.showToast({
        title: '昵称不能为空',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    if (dashouNicheng.length > 20) {
      wx.showToast({
        title: '昵称不能超过20字',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    // 2. 验证手机号（非必填，但填写时必须正确）
    if (dashouDianhua && dashouDianhua !== '暂未填写') {
      if (!/^1[3-9]\d{9}$/.test(dashouDianhua)) {
        wx.showToast({
          title: '手机号格式不正确',
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }
    
    // 3. 验证微信号（非必填）
    if (dashouWeixin && dashouWeixin.length > 30) {
      wx.showToast({
        title: '微信号不能超过30字符',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    // 4. 验证个人介绍
    if (dashouJieshao && dashouJieshao.length > 200) {
      wx.showToast({
        title: '介绍不能超过200字',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    
    return true
  },

  // 格式化提交数据
  formatSubmitData() {
    const {
      dashouNicheng,
      dashouDianhua,
      dashouWeixin,
      dashouJieshao
    } = this.data
    
    // 将"暂未填写"转换为空字符串
    const formatValue = (value) => {
      return value === '暂未填写' ? '' : value.trim()
    }
    
    return {
      nicheng: formatValue(dashouNicheng),
      dianhua: formatValue(dashouDianhua),
      wechat: formatValue(dashouWeixin),
      jieshao: formatValue(dashouJieshao)
    }
  },

  // 提交修改
  async onSubmit() {
    // 防止重复提交
    if (this.data.isSubmitting) return
    
    // 表单验证
    if (!this.validateForm()) return
    
    this.setData({ isSubmitting: true })
    
    // 准备提交数据
    const postData = this.formatSubmitData()
    
    try {
      const res = await request({
        url: '/yonghu/dsgxxx',
        method: 'POST',
        data: postData
      })
      
      if (res && res.data.code === 200) {
        // 更新成功
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        })
        
        // 更新本地缓存
        this.updateLocalCache(postData)
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        
      } else {
        // 更新失败
        const errorMsg = res?.data?.msg || '修改失败，请重试'
        wx.showModal({
          title: '修改失败',
          content: errorMsg,
          showCancel: false
        })
        this.setData({ isSubmitting: false })
      }
      
    } catch (error) {
      console.error('提交修改失败:', error)
      wx.showModal({
        title: '请求失败',
        content: error.message || '网络错误，请检查连接',
        showCancel: false
      })
      this.setData({ isSubmitting: false })
    }
  },

  // 更新本地缓存
  updateLocalCache(data) {
    if (data.nicheng !== undefined) {
      wx.setStorageSync('dsnc', data.nicheng)
    }
    if (data.jieshao !== undefined) {
      wx.setStorageSync('dsjieshao', data.jieshao)
    }
    if (data.dianhua !== undefined) {
      wx.setStorageSync('dsdianhua', data.dianhua)
    }
    if (data.wechat !== undefined) {
      wx.setStorageSync('dsweixin', data.wechat)
    }
  }
})