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
package com.example.firstapp.activity
 
import android.app.AlertDialog
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.navigation.ui.AppBarConfiguration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.firstapp.R
import com.example.firstapp.adapter.CardAdapter
import com.example.firstapp.database.service.RetrofitClient
import com.example.firstapp.databinding.ActivityVipBinding
import com.example.firstapp.model.CardData
import com.example.firstapp.model.MemberBenefitItem
import com.example.firstapp.pay.PayAbility
import com.example.firstapp.utils.Log
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.launch
 
 
class VipActivity : AppCompatActivity() {
 
    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityVipBinding
    private var isPaymentSelected = false // 全局变量,默认未选中
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
 
        binding = ActivityVipBinding.inflate(layoutInflater)
        setContentView(binding.root)
 
        setSupportActionBar(binding.toolbar)
 
        // 显式设置 MaterialToolbar 的标题
        supportActionBar?.title = ""
 
        // 如果不需要 ActionBar 的导航功能,可以禁用
//        supportActionBar?.setDisplayHomeAsUpEnabled(false)
//        supportActionBar?.setDisplayShowHomeEnabled(false)
 
 
        // 返回事件
        binding.ivBack.setOnClickListener{
            finish()
        }
 
//        会员卡片初始化
        vipCardInit()
 
//        会员权益初始化
        memberBenefitInit()
 
        // 支付宝点击事件
        handleAlipayClick()
 
        // 微信点击事件
        handleWechatClick()
 
        // 勾选协议点击事件
        handlePrototalClick()
    }
 
 
    private fun handlePrototalClick(){
        val protocol: CheckBox = findViewById(R.id.protocol_checkbox);
 
        // 监听 RadioButton 选中状态
        protocol.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            isPaymentSelected = isChecked // 更新全局变量
            if(isChecked){
                protocol.background = ContextCompat.getDrawable(this, R.drawable.checkbox_round_selected)
            }else{
                protocol.background = ContextCompat.getDrawable(this, R.drawable.checkbox_round)
            }
        })
    }
 
    // 这里添加alipay_layout的点击事件
    private fun handleAlipayClick() {
        // 绑定按钮
        val btnAlipay: LinearLayout = findViewById(R.id.alipay_layout);
        btnAlipay.setOnClickListener(View.OnClickListener {
            // 判断协议是否勾选
            if (!isPaymentSelected){
                // 这里需要弹出框
                showConfirmDialog()
            }else{
                doAlipay()
            }
 
 
        })
    }
 
    private fun doAlipay(){
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.apiService.getPayOrderInfo()
                var orderInfo=response.data
                Log.d("AliPayHelper","获取订单信息时: ${response}")
                // 这里调用支付宝
                PayAbility.aliPay(this@VipActivity, orderInfo, Observer {
                    when (it.resultStatus) {
                        "9000" -> {
//                                Snackbar.make(binding.root, "支付成功", Snackbar.LENGTH_LONG).show()
                            runOnUiThread {
                                Toast.makeText(this@VipActivity, "支付成功", Toast.LENGTH_LONG).show()
                            }
                        }
                        else -> {
//                                Snackbar.make(binding.root, "支付失败", Snackbar.LENGTH_LONG).show()
 
                            runOnUiThread {
                                Toast.makeText(this@VipActivity, "支付失败", Toast.LENGTH_LONG).show()
                            }
                        }
                    }
                })
 
            } catch (e: Exception) {
                Toast.makeText(this@VipActivity, e.message, Toast.LENGTH_LONG).show()
                Log.d("AliPayHelper","获取订单信息时发生错误: ${e.message}")
            }
        }
    }
 
    private fun showConfirmDialog() {
        val dialogView = LayoutInflater.from(this).inflate(R.layout.vip_protocol_dialog_custom, null)
 
        val dialog = AlertDialog.Builder(this)
            .setView(dialogView)
            .create()
 
        // 设置自定义背景
        dialog.window?.setBackgroundDrawableResource(R.drawable.dialog_background)
 
        // 获取按钮并设置点击事件
        val btnConfirm = dialogView.findViewById<Button>(R.id.btnConfirm)
        btnConfirm.setOnClickListener {
            // 将协议勾选上
            val protocol: CheckBox = findViewById(R.id.protocol_checkbox);
            protocol.isChecked = true
 
            doAlipay()
            dialog.dismiss()
        }
 
        // 显示对话框
        dialog.show()
    }
    private fun showConfirmDialog2() {
        // 创建标题 TextView 并居中
        val titleView = TextView(this).apply {
            text = "确认开通"
            textSize = 20f
            gravity = Gravity.CENTER
            setPadding(20, 20, 20, 20)
        }
 
        // 创建内容 TextView 并居中
        val messageView = TextView(this).apply {
            text = "请阅读并同意《会员协议》?"
            textSize = 16f
            gravity = Gravity.CENTER
            setPadding(40, 20, 40, 20)
        }
 
        AlertDialog.Builder(this)
            .setCustomTitle(titleView)  // 自定义标题
            .setView(messageView)  // 自定义内容
            .setPositiveButton("继续开通") { _, _ ->
 
 
 
                // 确认支付
                doAlipay()
            }
            .setNegativeButton("取消") { dialog, _ ->
                dialog.dismiss() // 关闭对话框
            }
            .show()
    }
 
    // 这里添加alipay_layout的点击事件
    private fun handleWechatClick() {
 
        // 绑定按钮
        val wechatAlipay: LinearLayout = findViewById(R.id.wechat_layout);
        wechatAlipay.setOnClickListener(View.OnClickListener {
            lifecycleScope.launch {
                try {
                    // 判断协议是否勾选
                    if (!isPaymentSelected){
 
                        Toast.makeText(this@VipActivity, "请勾选协议", Toast.LENGTH_LONG).show()
                        return@launch // 直接 return,不往下执行
                    }
                    Toast.makeText(this@VipActivity, "功能暂未开放", Toast.LENGTH_LONG).show()
                    return@launch
 
 
                } catch (e: Exception) {
                    Toast.makeText(this@VipActivity, e.message, Toast.LENGTH_LONG).show()
                    Log.d("AliPayHelper","获取订单信息时发生错误: ${e.message}")
                }
            }
        })
 
 
    }
 
 
    private fun vipCardInit() {
        val recyclerView = findViewById<RecyclerView>(R.id.recycler_view)
        recyclerView.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
 
        val cardList = listOf(
            CardData.ContinueMonthly(
                "首月限时特惠",
                "连续包月",
                "首次开通",
                "9.9",
                "次月起12元/月",
                "自动续费可随时取消"
            ),
            CardData.Yearly(
                "折合9元/月",
                "年卡",
                "108",
                "168"
            ),
            CardData.SingleMonth(
                "1个月",
                "15"
            )
        )
 
        val adapter = CardAdapter(cardList) { cardViewList, cardData, cardView ->
            handleVipCardClick(cardViewList, cardData, cardView)
        }
 
        recyclerView.adapter = adapter
    }
 
    private fun memberBenefitInit() {
        val container = findViewById<ConstraintLayout>(R.id.dynamicContainer)
 
        // 传递过来的数据列表
        val itemList = listOf(
            MemberBenefitItem(R.mipmap.vip_life_insurance, "自定义更多分类", true),
            MemberBenefitItem(R.mipmap.vip_ad_no, "自动去广告", false),
            MemberBenefitItem(R.mipmap.vip_ling, "公众号提醒待办", true),
            MemberBenefitItem(R.mipmap.vip_circle_pie, "数据统计", false)
        )
 
        var previousViewId = R.id.dynamicContainer
 
        for ((index, item) in itemList.withIndex()) {
            val iconView = ImageView(this).apply {
                id = View.generateViewId()
                setImageResource(item.iconRes)
                layoutParams = ConstraintLayout.LayoutParams(
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, resources.displayMetrics).toInt(),
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, resources.displayMetrics).toInt()
                )
            }
 
            val textView = TextView(this).apply {
                id = View.generateViewId()
                text = item.text
                textSize = 16f
                setTextColor(Color.parseColor("#DFC08E"))
            }
 
            val checkView = ImageView(this).apply {
                id = View.generateViewId()
                setImageResource(R.drawable.ic_check)
                layoutParams = ConstraintLayout.LayoutParams(
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, resources.displayMetrics).toInt(),
                    TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30f, resources.displayMetrics).toInt()
                )
            }
 
            container.addView(iconView)
            container.addView(textView)
            container.addView(checkView)
 
            val constraintSet = ConstraintSet()
            constraintSet.clone(container)
 
            // Icon 位置
            constraintSet.connect(
                iconView.id,
                ConstraintSet.TOP,
                previousViewId,
                if (index == 0) ConstraintSet.TOP else ConstraintSet.BOTTOM,
                16
            )
            constraintSet.connect(
                iconView.id,
                ConstraintSet.START,
                ConstraintSet.PARENT_ID,
                ConstraintSet.START,
                16
            )
 
            // Text 位置
            constraintSet.connect(textView.id, ConstraintSet.TOP, iconView.id, ConstraintSet.TOP)
            constraintSet.connect(
                textView.id,
                ConstraintSet.START,
                iconView.id,
                ConstraintSet.END,
                8
            )
 
            // Check 位置
            constraintSet.connect(checkView.id, ConstraintSet.TOP, iconView.id, ConstraintSet.TOP)
            constraintSet.connect(
                checkView.id,
                ConstraintSet.END,
                ConstraintSet.PARENT_ID,
                ConstraintSet.END,
                16
            )
 
            constraintSet.applyTo(container)
 
            previousViewId = iconView.id
        }
    }
 
    /**
     * 会员卡样式点击事件
     */
    private fun handleVipCardClick(cardViewList: MutableList<CardView>, cardData: CardData, cardView: CardView) {
        // 处理点击事件,修改样式
        // 修改所有的边框色都是灰色
        cardViewList.forEach { card ->
            card.foreground = ContextCompat.getDrawable(this, R.drawable.gray_border_shape)  // 设置自定义背景
        }
 
        // 单独将点击的卡片边框颜色改为金色
//            cardView.setCardBackgroundColor(Color.parseColor("#FF0000")) // 举例:设置背景颜色
        cardView.foreground = ContextCompat.getDrawable(this, R.drawable.gold_border_shape)  // 设置自定义背景
        val title = when (cardData) {
            is CardData.ContinueMonthly -> cardData.title
            is CardData.Yearly -> cardData.title
            is CardData.SingleMonth -> cardData.title
        }
        val price = when (cardData) {
            is CardData.ContinueMonthly -> cardData.price
            is CardData.Yearly -> cardData.price
            is CardData.SingleMonth -> cardData.price
        }
 
 
        val alipayAmount:TextView = findViewById(R.id.alipay_amount);
        val wechatAmount:TextView = findViewById(R.id.wechat_amount);
        alipayAmount.text=price
        wechatAmount.text=price
        // 处理点击事件,这里我们只是简单地展示一个 Toast
        Toast.makeText(this, "点击了: ${title}", Toast.LENGTH_SHORT).show()
    }
 
}