lmw
2024-06-17 f571288a24fcf10143dcc8015ffbbf38dbc0c614
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
package com.dollearn.student.ui.course
 
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Paint
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import cn.sinata.xldutils.gone
import cn.sinata.xldutils.invisible
import cn.sinata.xldutils.utils.SpanBuilder
import cn.sinata.xldutils.utils.myToast
import cn.sinata.xldutils.utils.showAllowingStateLoss
import cn.sinata.xldutils.visible
import com.dollearn.student.R
import com.dollearn.student.WeparkApplication
import com.dollearn.student.dialog.ChooseCouponDialog
import com.dollearn.student.dialog.ChooseStudentDialog
import com.dollearn.student.dialog.ConfirmShopDialog
import com.dollearn.student.dialog.PayDialog
import com.dollearn.student.network.HttpManager
import com.dollearn.student.network.entity.*
import com.dollearn.student.network.request
import com.dollearn.student.ui.TransparentStatusBarActivity
import com.dollearn.student.ui.home.PayResultActivity
import com.dollearn.student.ui.home.adapter.HomeBannerAdapter
import com.dollearn.student.ui.home.adapter.LessonCountAdapter
import com.dollearn.student.ui.home.adapter.StudentAdapter
import com.dollearn.student.utils.Const
import com.dollearn.student.utils.event.EmptyEvent
import com.dollearn.student.utils.extention.clickDelay
import com.dollearn.student.utils.interfaces.StringCallback
import com.dollearn.student.utils.pay.PayListener
import com.dollearn.student.utils.pay.PayUtil
import kotlinx.android.synthetic.main.activity_join_course.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.textColorResource
import java.math.BigDecimal
 
class JoinCourseActivity : TransparentStatusBarActivity(), PayListener {
    override fun setContentView() = R.layout.activity_join_course
    private val isContinue by lazy {
        try {
            intent.getBooleanExtra("isContinue", false)
        } catch (_: Exception) {
            false
        }
    }
 
    private val orderId by lazy { intent.getStringExtra("orderId") } //续课有此字段
 
    private val bannerImg = arrayListOf<Banner>()
    private val bannerAdapter by lazy {
        HomeBannerAdapter(bannerImg, this)
    }
 
    private val paymentId by lazy { intent.getStringExtra("paymentId") } //如果不是空 表示来支付的
 
    private val course by lazy { intent.getParcelableExtra<Course>("course")!! }
    private val courseCount by lazy { intent.getIntExtra("courseCount",0) } //从福利折扣进来的时候有此字段,需要默认选择此课时
 
    private val arrayListOf = arrayListOf<String>()
    private val lessonCountAdapter = LessonCountAdapter(arrayListOf)
 
    private val students = arrayListOf<Student>()
    private val studentAdapter = StudentAdapter(students, StudentAdapter.TYPE_COURSE_DETAIL)
 
    private val couponList = arrayListOf<Coupon>()
    private var chooseCouponId = 0L//已选优惠券id
    private var chooseCouponMoney = 0.0//已选优惠券价格
 
    private var payPrice = 0.0
    private var payCoin = 0
 
 
    override fun initClick() {
        tv_add_student.clickDelay {
            ChooseStudentDialog.show(
                supportFragmentManager,
                ChooseStudentDialog.TYPE_COURSE,
                students,
                object : ChooseStudentDialog.ResultCallback {
                    override fun checked(list: List<Student>) {
                        students.clear()
                        students.addAll(list)
                        studentAdapter.notifyDataSetChanged()
                        refreshPrice(course!!.list[lessonCountAdapter.checked])
                    }
                })
        }
        tv_coupon.clickDelay {
            val chooseCouponDialog = ChooseCouponDialog()
            chooseCouponDialog.arguments =
                bundleOf("list" to couponList, "checked" to chooseCouponId)
            chooseCouponDialog.callback = object : StringCallback {
                override fun onResult(rst: String) {
                    chooseCouponId = rst.toLong()
                    val coupon = couponList.filter { it.id == chooseCouponId }.firstOrNull()
                    chooseCouponMoney = (coupon?.favorable?:"0.0").toDouble()
                    tv_coupon.text = "-${coupon?.favorable}元"
                    refreshPrice(course!!.list[lessonCountAdapter.checked],true)
                }
            }
            chooseCouponDialog.showAllowingStateLoss(supportFragmentManager, "coupon")
        }
        tv_action.clickDelay {
            if (students.isNullOrEmpty())
                myToast("请选择运动营成员")
            else
                ConfirmShopDialog.show(supportFragmentManager,
                    course.storeCoverDrawing ?: "",
                    course.storeName,
                    course.storeAddress,
                    if (course.distance == null) "" else "${course.distance}km",
                    object : StringCallback {
                        override fun onResult(rst: String) {
                            PayDialog.show(supportFragmentManager, false, object : StringCallback {
                                override fun onResult(rst: String) {
                                    pay(rst.toInt())
                                }
 
                            }, payPrice, payCoin)
                        }
                    })
        }
    }
 
    @SuppressLint("SetTextI18n")
    override fun initView() {
        banner.adapter = bannerAdapter
        if (isContinue){
            tv_action.text = "续课"
            tv_add_student.invisible() //安雪晖:续课不能修改成员
            studentAdapter.delable = false
        }
        if (!paymentId.isNullOrEmpty())
            tv_action.text = "立即支付"
 
        rv_lesson_count.layoutManager = GridLayoutManager(this, 3)
        rv_student.layoutManager = LinearLayoutManager(this)
        rv_student.adapter = studentAdapter
        studentAdapter.delCallback = object : StringCallback {
            override fun onResult(rst: String) {
                students.removeAt(rst.toInt())
                studentAdapter.notifyDataSetChanged()
                refreshPrice(course!!.list[lessonCountAdapter.checked])
            }
        }
        course?.apply {
            bannerImg.addAll(detailDrawing.split(",").map { Banner(url = it) })
            bannerAdapter.notifyDataSetChanged()
            banner.currentItem = 1
            tv_name.text = name
            tv_week.text = "毎${weeks.joinToString("、") { it }}"
            tv_time.text = times?.joinToString(" | ")
            tv_shop.text = storeName
            tv_address.text = storeAddress
            arrayListOf.addAll(list.map { "${it.classHours}课时" })
            if (courseCount!=0) //有默认选中的课时
                lessonCountAdapter.checked = list.map { it.classHours }.indexOf(courseCount)
            rv_lesson_count.adapter = lessonCountAdapter
            lessonCountAdapter.setOnItemClickListener { view, position ->
                lessonCountAdapter.checked = position
                refreshPrice(list[position])
                lessonCountAdapter.notifyDataSetChanged()
            }
            if (!student.id.isNullOrEmpty()) {
                student.stuId = student.id
                students.add(student)
                studentAdapter.notifyDataSetChanged()
            }
            refreshPrice(list[lessonCountAdapter.checked])
            when(type){
                2->{ //假期班
                    gp_count.gone()
                    mll_class_yxq.visible()
                    mtv_class_yxq.text = time
                    mtvtag.text = "假期班"
                }
                3->{ //体验课
                    gp_count.gone()
                    mll_class_yxq.visible()
                    mtvtag.text = "体验课"
                    cl_time.gone()
                }
                else->{
                    mtvtag.text = "常规班"
                }
            }
        }
        PayUtil.addPayListener(this)
        EventBus.getDefault().register(this)
    }
 
    @Subscribe
    fun onSwitch(e: EmptyEvent) {
 
    }
 
    private fun refreshPrice(data: Lesson?,changeByCoupon:Boolean = false) {
        val size = if (students.size == 0) 1 else students.size
        data?.apply {
            //1.是否有玩湃币价格 —— 独立判断
            payCoin = playPaiCoin * size
            if (payCoin == 0)
                tv_coin_price.gone()
            else {
                tv_coin_price.visible()
                tv_coin_price.text = SpanBuilder("玩湃币:%d币".format(payCoin)).color(
                    this@JoinCourseActivity,
                    0,
                    4,
                    R.color.textColor
                ).build()
            }
 
            //2.支付价 —— 独立判断
            if (paymentPrice == 0.0 || paymentPrice == null) { //没有支付价tv_price.gone()
                tv_vip_price.gone()
            } else { //有支付价,显示支付价,并判断是否有会员价或划线价
                payPrice = paymentPrice * size
                if (!changeByCoupon){ //如果是选择优惠券后导致的价格变化 不用重新获取可用优惠券
                    chooseCouponMoney = 0.0
                    chooseCouponId = 0L
                    getCoupon(payPrice)
                }
                payPrice = sub(payPrice ,chooseCouponMoney)
                tv_price.text = "¥%s".format(payPrice.toString())
 
                //3.会员价或划线价
                if (paymentPrice <= vipPrice ?: 0.0) { //a.支付价==会员价,说明我是会员,展示划线价; b.支付价小于会员价,说明是折扣价,展示划线价
                    if (originalPrice ?: 0.0 != 0.0 && originalPrice != paymentPrice) { //有划线价且划线价不等于支付价,才显示划线价
                        tv_vip_price.text = "¥%.2f".format((originalPrice?:0.0)*size)
                        tv_vip_price.textColorResource = R.color.textColor66
                        tv_vip_price.paintFlags =
                            tv_vip_price.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
                    } else //否则啥也不展示
                        tv_vip_price.gone()
                } else if (vipPrice ?: 0.0 != 0.0) {
                    tv_vip_price.text =
                        SpanBuilder("会员价:¥%s".format(((vipPrice?:0.0)*size).toString())).color(
                            this@JoinCourseActivity,
                            0,
                            4,
                            R.color.textColor
                        ).build()
                } else
                    tv_vip_price.gone()
            }
        }
    }
 
    private fun sub(d1:Double,d2:Double):Double{
        val b1 = BigDecimal(d1.toString())
        val b2 = BigDecimal(d2.toString())
        return b1.subtract(b2).toDouble()
    }
 
    private fun getCoupon(price: Double) {
        HttpManager.queryAvailableCouponList(
            course!!.id,
            price,
            WeparkApplication.lat,
            WeparkApplication.lon
        ).request(this) { _, data ->
            couponList.clear()
            couponList.addAll(data ?: arrayListOf())
            if (chooseCouponId !in couponList.map { it.id }) { //之前选中的优惠券不在可用列表
                chooseCouponId = 0
                chooseCouponMoney = 0.0
                tv_coupon.text = "去选择"
            }
            cl_coupon.visibility = if (data.isNullOrEmpty()) View.GONE else{
                tv_coupon_count.text = "(${data.size}张可用)"
                View.VISIBLE
            }
        }
    }
 
    private fun pay(payType: Int) {
        if (!paymentId.isNullOrEmpty())
            HttpManager.payment(
                payType,
                course.id,
                paymentId!!,
                course.list[lessonCountAdapter.checked].classHours,
                students.joinToString(";") { it.id ?: "" },
                if (chooseCouponId == 0L) 2 else 1,
                chooseCouponId
            ).request(this, false, success = { _, data ->
//                if (chooseCouponId!=0L){
//                    getCoupon(payPrice)
//                }
                if (payType == 2) {
                    PayUtil.aliPay(this, data?.orderInfo ?: "")
                } else if (payType == 3) {
                    EventBus.getDefault().post(EmptyEvent(Const.EventCode.REFRESH_USER)) //玩湃币支付后刷新首页
                    onPaySuccess()
                } else {
                    PayUtil.initWeChatPay(this, Const.WX_APP_ID)
                    PayUtil.weChatPay(data!!)
                }
            }) { _, msg ->
                startActivityForResult<PayResultActivity>(1, "type" to if (isContinue) PayResultActivity.TYPE_COURSE_CONTINUE_FAILED else PayResultActivity.TYPE_COURSE_FAILED, "msg" to msg)
            }
        else {
            HttpManager.paymentCourse(
                payType,
                course.id,
                course.list[lessonCountAdapter.checked].id,
                if (payType == 3) payCoin.toDouble() else payPrice+chooseCouponMoney,
                students.joinToString(";") { it.id ?: "" },
                chooseCouponId,orderId
            ).request(this, false, success = { _, data ->
                if (chooseCouponId!=0L){
                    getCoupon(payPrice)
                }
                if (payType == 2) {
                    PayUtil.aliPay(this, data?.orderInfo ?: "")
                } else if (payType == 3) {
                    EventBus.getDefault().post(EmptyEvent(Const.EventCode.REFRESH_USER)) //玩湃币支付后刷新首页
                    onPaySuccess()
                } else {
                    PayUtil.initWeChatPay(this, Const.WX_APP_ID)
                    PayUtil.weChatPay(data!!)
                }
            }) { _, msg ->
                startActivityForResult<PayResultActivity>(
                    1,
                    "type" to if (isContinue) PayResultActivity.TYPE_COURSE_CONTINUE_FAILED else PayResultActivity.TYPE_COURSE_FAILED,
                    "msg" to msg
                )
            }
        }
 
    }
 
    override fun onPaySuccess() {
        startActivityForResult<PayResultActivity>(
            1,
            "type" to if (isContinue) PayResultActivity.TYPE_COURSE_CONTINUE_SUC else PayResultActivity.TYPE_COURSE_SUC,
            "lessonId" to course.list[lessonCountAdapter.checked].id
        )
        finish()
    }
 
    override fun onPayCancel() {
    }
 
    override fun onPayError(msg: String) {
        startActivityForResult<PayResultActivity>(
            1,
            "type" to if (isContinue) PayResultActivity.TYPE_COURSE_CONTINUE_FAILED else PayResultActivity.TYPE_COURSE_FAILED
        )
    }
 
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK&&requestCode == 1) {
            tv_action.postDelayed({
                PayDialog.show(supportFragmentManager, false, object : StringCallback {
                    override fun onResult(rst: String) {
                        pay(rst.toInt())
                    }
 
                }, payPrice, payCoin)
            }, 500)
        }
    }
 
    override fun onDestroy() {
        super.onDestroy()
        PayUtil.removePayListener(this)
        PayUtil.unregisterApp()
        EventBus.getDefault().unregister(this)
    }
}