1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
// pages/profile/personal-info.js
const app = getApp()
const { graphqlRequest } = require('../../lib/utils')
 
Page({
  data: {
    userInfo: {
      avatar: '',
      name: '',
      gender: '',
      phone: '',
      birthday: ''
    },
    currentDate: '',
    saving: false
  },
 
  onLoad(options) {
    this.initCurrentDate()
    this.loadUserInfo()
  },
 
  // 初始化当前日期
  initCurrentDate() {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    this.setData({
      currentDate: `${year}-${month}-${day}`
    })
  },
 
  // 加载用户信息
  async loadUserInfo() {
    try {
      // 先从全局数据获取
      const globalUserInfo = app.globalData.userInfo || {}
      
      // 从后端获取最新用户信息
      const query = `
        query GetUserProfile {
          userProfile {
            id
            name
            avatar
            phone
            gender
            birthday
          }
        }
      `
      
      const result = await graphqlRequest(query)
      let userInfo = globalUserInfo
      
      if (result && result.userProfile) {
        userInfo = result.userProfile
        // 更新全局数据
        app.globalData.userInfo = userInfo
      }
 
      this.setData({
        userInfo: {
          avatar: userInfo.avatar || '',
          name: userInfo.name || '',
          gender: userInfo.gender || '',
          phone: userInfo.phone || '',
          birthday: userInfo.birthday || ''
        }
      })
    } catch (error) {
      console.error('加载用户信息失败:', error)
      // 使用全局数据作为备选
      const globalUserInfo = app.globalData.userInfo || {}
      this.setData({
        userInfo: {
          avatar: globalUserInfo.avatar || '',
          name: globalUserInfo.name || '',
          gender: globalUserInfo.gender || '',
          phone: globalUserInfo.phone || '',
          birthday: globalUserInfo.birthday || ''
        }
      })
    }
  },
 
  // 选择头像
  chooseAvatar() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.uploadAvatar(tempFilePath)
      },
      fail: (err) => {
        console.error('选择头像失败:', err)
        wx.showToast({
          title: '选择头像失败',
          icon: 'none'
        })
      }
    })
  },
 
  // 上传头像
  async uploadAvatar(filePath) {
    wx.showLoading({
      title: '上传中...'
    })
 
    try {
      // 暂时保存本地路径,在保存用户信息时一起处理
      this.setData({
        'userInfo.avatar': filePath,
        localAvatarPath: filePath // 保存本地路径用于后续上传
      })
      
      wx.hideLoading()
      wx.showToast({
        title: '头像选择成功',
        icon: 'success'
      })
    } catch (error) {
      wx.hideLoading()
      wx.showToast({
        title: '头像选择失败',
        icon: 'none'
      })
    }
  },
 
  // 姓名输入
  onNameInput(e) {
    this.setData({
      'userInfo.name': e.detail.value
    })
  },
 
  // 选择性别
  selectGender(e) {
    const gender = e.currentTarget.dataset.gender
    this.setData({
      'userInfo.gender': gender
    })
  },
 
  // 获取手机号
  async getPhoneNumber(e) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      try {
        wx.showLoading({
          title: '获取中...'
        })
        
        // TODO: 调用后端API解密手机号
        const mutation = `
          mutation DecryptPhoneNumber($encryptedData: String!, $iv: String!) {
            decryptPhoneNumber(encryptedData: $encryptedData, iv: $iv) {
              phoneNumber
            }
          }
        `
        
        const variables = {
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv
        }
        
        const result = await graphqlRequest(mutation, variables)
        
        if (result && result.decryptPhoneNumber) {
          this.setData({
            'userInfo.phone': result.decryptPhoneNumber.phoneNumber
          })
          wx.showToast({
            title: '手机号获取成功',
            icon: 'success'
          })
        } else {
          throw new Error('解密失败')
        }
      } catch (error) {
        console.error('获取手机号失败:', error)
        wx.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
      } finally {
        wx.hideLoading()
      }
    } else {
      wx.showToast({
        title: '获取手机号失败',
        icon: 'none'
      })
    }
  },
 
  // 生日选择
  onBirthdayChange(e) {
    this.setData({
      'userInfo.birthday': e.detail.value
    })
  },
 
  // 保存用户信息
  async saveUserInfo() {
    const { userInfo, localAvatarPath } = this.data
 
    // 验证必填字段
    if (!userInfo.name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }
 
    if (!userInfo.gender) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return
    }
 
    if (!userInfo.phone) {
      wx.showToast({
        title: '请获取手机号',
        icon: 'none'
      })
      return
    }
 
    this.setData({ saving: true })
 
    try {
      // 第一步:保存用户基本信息(不包含头像)
      const mutation = `
        mutation SaveUserInfo($input: UserInput!) {
          saveUserInfo(input: $input) {
            id
            name
            avatar
            phone
            gender
            birthday
            wxOpenId
            unionId
          }
        }
      `
      
      const variables = {
        input: {
          name: userInfo.name.trim(),
          phone: userInfo.phone,
          gender: userInfo.gender,
          birthday: userInfo.birthday
        }
      }
      
      const result = await graphqlRequest(mutation, variables)
      
      if (result && result.saveUserInfo) {
        const savedUserInfo = result.saveUserInfo
        
        // 第二步:如果有新头像,上传到COS并保存到t_media
        if (localAvatarPath) {
          await this.uploadAvatarWithUserId(savedUserInfo.id)
        }
        
        // 重新获取用户信息(包含头像)
        await this.loadUserInfo()
        
        // 更新全局用户信息
        app.globalData.userInfo = { ...app.globalData.userInfo, ...this.data.userInfo }
        
        // 保存到本地存储
        wx.setStorageSync('userInfo', app.globalData.userInfo)
 
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
 
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error('保存失败')
      }
    } catch (error) {
      console.error('保存用户信息失败:', error)
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      })
    } finally {
      this.setData({ saving: false })
    }
  },
 
  // 使用用户ID上传头像
  async uploadAvatarWithUserId(userId) {
    const { localAvatarPath } = this.data
    if (!localAvatarPath) return
 
    try {
      // 引入cosUtil
      const cosUtil = require('../../lib/cosUtil')
      
      // 第一步:上传到COS
      const uploadResult = await cosUtil.uploadAvatar(
        localAvatarPath,
        'avatar.jpg',
        (percent) => {
          console.log('头像上传进度:', percent + '%')
        }
      )
 
      // 第二步:保存媒体记录到数据库
      await this.saveMediaRecord({
        targetType: 'player', // 用户头像
        targetId: parseInt(userId),
        path: uploadResult.key,
        fileName: uploadResult.fileName || 'avatar.jpg',
        fileExt: this.getFileExtension(uploadResult.fileName || 'avatar.jpg'),
        fileSize: uploadResult.fileSize,
        mediaType: 1 // 图片
      })
 
      // 清空本地路径
      this.setData({
        localAvatarPath: ''
      })
 
      console.log('头像上传成功:', uploadResult)
    } catch (error) {
      console.error('头像上传失败:', error)
      throw error
    }
  },
 
  // 保存媒体记录到数据库
  async saveMediaRecord(mediaData) {
    const mutation = `
      mutation SaveMediaV2($input: MediaSaveInput!) {
        saveMediaV2(input: $input) {
          success
          message
          mediaId
        }
      }
    `
    
    const variables = {
      input: {
        targetType: mediaData.targetType,
        targetId: mediaData.targetId,
        path: mediaData.path,
        fileName: mediaData.fileName,
        fileExt: mediaData.fileExt,
        fileSize: mediaData.fileSize,
        mediaType: mediaData.mediaType
      }
    }
    
    try {
      const result = await graphqlRequest(mutation, variables)
      console.log('媒体记录保存成功:', result.saveMediaV2)
      return result.saveMediaV2
    } catch (error) {
      console.error('媒体记录保存失败:', error)
      throw error
    }
  },
 
  // 获取文件扩展名
  getFileExtension(fileName) {
    return fileName.split('.').pop().toLowerCase()
  }
})