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
package com.example.firstapp.ui.profile
 
import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import android.widget.ProgressBar
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.firstapp.database.response.UserInfo
import com.example.firstapp.databinding.ActivityEditProfileBinding
import com.example.firstapp.database.service.ApiService
import com.example.firstapp.database.service.RetrofitClient
import com.example.firstapp.utils.PreferencesManager
import kotlinx.coroutines.launch
import java.io.File
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
 
class EditProfileActivity : AppCompatActivity() {
    private lateinit var binding: ActivityEditProfileBinding
    private var selectedImageUri: Uri? = null
    private var loadingDialog: AlertDialog? = null
 
//    private val pickImage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
//        if (result.resultCode == Activity.RESULT_OK) {
//            result.data?.data?.let { uri ->
//                selectedImageUri = uri
//                Glide.with(this)
//                    .load(uri)
//                    .circleCrop()
//                    .into(binding.ivAvatar)
//            }
//        }
//    }
 
    private val pickImageLauncher = registerForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            selectedImageUri = uri
            // 这里直接处理选中的头像
            Glide.with(this)
                .load(it)
                .into(binding.ivAvatar) // 替换成你的 ImageView id
 
            // 如果需要上传可以用 contentResolver.openInputStream(uri)
        }
    }
 
 
    // 👇 就放在这里
    private val permissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {
            openGallery()
        } else {
            Toast.makeText(this, "需要权限才能选择头像", Toast.LENGTH_SHORT).show()
        }
    }
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEditProfileBinding.inflate(layoutInflater)
        setContentView(binding.root)
 
        // 设置状态栏
        window.statusBarColor = ContextCompat.getColor(this, android.R.color.white)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
        }
 
        // 获取传入的数据
        val currentNickname = intent.getStringExtra("nickname") ?: ""
        val currentAvatarUrl = intent.getStringExtra("avatar_url")
 
        // 设置当前数据
        binding.etNickname.setText(currentNickname)
        if (!currentAvatarUrl.isNullOrEmpty()) {
            Glide.with(this)
                .load(currentAvatarUrl)
                .circleCrop()
                .into(binding.ivAvatar)
        }
 
        // 设置点击事件
        binding.btnBack.setOnClickListener {
            finish()
        }
 
        binding.ivAvatar.setOnClickListener {
//            checkAndRequestPermission()
            checkStoragePermission()
        }
 
        binding.btnSaveBottom.setOnClickListener {
            saveAndFinish()
        }
    }
 
    fun checkStoragePermission() {
        val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            Manifest.permission.READ_MEDIA_IMAGES
        } else {
            Manifest.permission.READ_EXTERNAL_STORAGE
        }
 
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            permissionLauncher.launch(permission)
        } else {
            openGallery()
        }
    }
 
 
    private fun saveAndFinish() {
        lifecycleScope.launch {
            try {
                binding.btnSaveBottom.isEnabled = false
                showLoading()
 
                val newNickname = binding.etNickname.text.toString()
                if (newNickname.isEmpty()) {
                    Toast.makeText(this@EditProfileActivity, "昵称不能为空", Toast.LENGTH_SHORT).show()
                    return@launch
                }
 
                // 准备文件和参数
                val nicknameBody = newNickname.toRequestBody("text/plain".toMediaType())
 
                // 如果选择了新头像,处理文件
                val avatarPart = selectedImageUri?.let { uri ->
                    val inputStream = contentResolver.openInputStream(uri)
                    val file = File(cacheDir, "avatar_temp")
                    inputStream?.use { input ->
                        file.outputStream().use { output ->
                            input.copyTo(output)
                        }
                    }
 
                    val requestFile = file.asRequestBody("image/*".toMediaType())
                    MultipartBody.Part.createFormData("avatar", file.name, requestFile)
                }
 
                // 调用更新接口
                RetrofitClient.apiService.updateProfile(
                    nickname = nicknameBody,
                    avatar = avatarPart
                )
 
                Toast.makeText(this@EditProfileActivity, "保存成功", Toast.LENGTH_SHORT).show()
                // 更新用户信息
                // 从本地获取保存的手机号
                val savedPhone = PreferencesManager.getPhone()
                if (savedPhone.isNullOrEmpty()) {
                    Toast.makeText(this@EditProfileActivity, "用户未登录", Toast.LENGTH_SHORT).show()
                    return@launch
                }
                val response = RetrofitClient.apiService.getUserInfo(savedPhone)
                if (response.code == "0" && response.data != null) {
                    // 保存用户信息
                    val userInfo:UserInfo = response.data
                    // 获取传入的数据
                    val currentNickname = userInfo.name
                    val currentAvatarUrl = userInfo.cover
 
                    // 设置当前数据
                    binding.etNickname.setText(currentNickname)
                    if (!currentAvatarUrl.isNullOrEmpty()) {
                        Glide.with(this@EditProfileActivity)
                            .load(currentAvatarUrl)
                            .circleCrop()
                            .into(binding.ivAvatar)
                    }
 
                }
 
                finish()
 
            } catch (e: Exception) {
                Toast.makeText(this@EditProfileActivity, "保存失败: ${e.message}", Toast.LENGTH_SHORT).show()
            } finally {
                binding.btnSaveBottom.isEnabled = true
                hideLoading()
            }
        }
    }
 
    private fun checkAndRequestPermission() {
        when {
            ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED -> {
                openGallery()
            }
            else -> {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    PERMISSION_REQUEST_CODE
                )
            }
        }
    }
 
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openGallery()
                } else {
                    Toast.makeText(this, "需要存储权限来选择头像", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
 
    private fun openGallery_bak() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
//        pickImage.launch(intent)
    }
 
    private fun openGallery() {
        pickImageLauncher.launch("image/*")
//        val intent = Intent(Intent.ACTION_PICK)
//        intent.type = "image/*"
//        startActivityForResult(intent, 1001)
    }
 
    private fun showLoading() {
        if (loadingDialog == null) {
            loadingDialog = AlertDialog.Builder(this)
                .setView(ProgressBar(this))
                .setCancelable(false)
                .create()
        }
        loadingDialog?.show()
    }
 
    private fun hideLoading() {
        loadingDialog?.dismiss()
    }
 
    private fun String.toRequestBody(mediaType: String): RequestBody {
        return this.toRequestBody(mediaType.toMediaType())
    }
 
    private fun File.asRequestBody(mediaType: String): RequestBody {
        return this.asRequestBody(mediaType.toMediaType())
    }
 
    companion object {
        private const val PERMISSION_REQUEST_CODE = 100
    }