riku
2020-10-10 32e17591ca41ba7b79514f0cb2e2ef6eb3e5a384
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package cn.flightfeather.thirdapp.module.inspection
 
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.CardView
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.LinearLayout
import android.widget.TextView
import cn.flightfeather.thirdapp.R
import cn.flightfeather.thirdapp.adapter.AllRecyclerViewAdapter
import cn.flightfeather.thirdapp.bean.Scense
import cn.flightfeather.thirdapp.bean.Subtask
import cn.flightfeather.thirdapp.bean.vo.EvaluationsubruleVo
import cn.flightfeather.thirdapp.module.base.BaseActivity
import cn.flightfeather.thirdapp.util.Constant
import cn.flightfeather.thirdapp.util.DialogUtil2
import cn.flightfeather.thirdapp.util.dp
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_grade_2.*
import org.jetbrains.anko.margin
import org.jetbrains.anko.padding
 
 
/**
 * @author riku
 * Date: 2019/5/28
 * 评分activity
 */
class MenuGradeActivity : BaseActivity() {
 
    //是否已上传总分
    var isUpLoad = false
 
    //erGuid 评分规则id
    var erGuid = ""
 
    private var subtask: Subtask? = null//子任务
    private var inspectionGuid: String? = null//巡查ID
    private var scense: Scense? = null//场景
 
    lateinit var viewModel: MenuGradeViewModel
 
    private var isEdited = false//记录是否编辑过
 
    var ruleTitle: EvaluationsubruleVo? = null
 
    //基础评分项
    private val adapters = ArrayList<AllRecyclerViewAdapter<EvaluationsubruleVo>>()
 
    override fun getLayoutId(): Int = R.layout.activity_grade_2
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = ViewModelProviders.of(this).get(MenuGradeViewModel::class.java)
 
        subtask = intent.getSerializableExtra("subtask") as Subtask?
        inspectionGuid = intent.getSerializableExtra("inspectionGuid") as String?
        scense = intent.getSerializableExtra("scense") as Scense?
 
        title = Constant.DEFAULTGRADETITLE
 
        init()
    }
 
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_confirm, menu)
        return true
    }
 
    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_confirm -> {
                onBackPressed()
            }
        }
        return super.onOptionsItemSelected(item)
    }
 
    override fun onBackPressed() {
        if (isUpLoad || !isEdited) {
            finish()
            return
        }
        onSave()
    }
 
    private fun init() {
        viewModel.getEvaluationRule(subtask, scense?.typeid ?: 0.toByte()) {e ->
            erGuid = e?.guid ?: ""
        }
        inspectionGuid?.let {
            viewModel.getEvaluation(it)
        }
 
        refresh_layout.setColorSchemeColors(
                ContextCompat.getColor(this, R.color.colorPrimary),
                ContextCompat.getColor(this, R.color.colorPrimaryDark),
                ContextCompat.getColor(this, R.color.colorAccent)
        )
        refresh_layout.isEnabled = false
        refresh_layout.isRefreshing = true
        viewModel.ruleItemList.observe(this, Observer { arrayList ->
            arrayList?.let {
                initView(it)
            }
        })
 
    }
 
    private fun initView(ruleItemVoList: ArrayList<EvaluationsubruleVo>) {
        val disposable = Observable.create<ViewGroup> { emitter ->
            viewModel.tmpPoints = 0
            viewModel.ruleItemList.value?.forEach {
                if (it.fatherid.isNullOrEmpty()) {
                    it.fatherid = erGuid
                    viewModel.tmpPoints = it.grade?.toIntOrNull() ?: 0
                    viewModel.baseRules.add(it)
                } else {
                    viewModel.subRules.add(it)
                }
            }
            viewModel.baseRules.sortBy {
                it.displayid
            }
 
            viewModel.baseRules.forEach {
                var gradeView = generateNewLinearLayout(LinearLayout.VERTICAL)
                gradeView = generateNewSingleGrade(gradeView, it) ?: LinearLayout(this)
//                ll_grade.addView(gradeView)
                emitter.onNext(gradeView)
            }
            emitter.onComplete()
        }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    ll_grade.addView(it)
                    tv_no_data.visibility = View.GONE
                }, {
                    it.printStackTrace()
                }, {
                    refresh_layout.isRefreshing = false
//                    val footer = LayoutInflater.from(this).inflate(R.layout.layout_footer_view, null)
//                    ll_grade.addView(footer)
                })
 
 
        disposableList.add(disposable)
    }
 
    /**
     * 创建一个新的LinerLayout布局
     * @return
     */
    private fun generateNewLinearLayout(orientation: Int): LinearLayout {
 
        val linearLayout = LinearLayout(this)
        linearLayout.setPadding(5.dp, 5.dp, 5.dp, 5.dp)
        val layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
 
        linearLayout.layoutParams = layoutParams
        linearLayout.orientation = orientation
 
        return linearLayout
    }
 
    /**
     * 一个规范考核项的内容主体
     * @param linearLayout
     */
    private fun generateNewSingleGrade(
            linearLayout: LinearLayout,
            ruleItemVo: EvaluationsubruleVo
    ): LinearLayout? {
        //打分类别初始化
        try {
            return foo(viewModel.ruleItemList.value!!, ruleItemVo, linearLayout)
        } catch (e: NullPointerException) {
            e.printStackTrace()
        }
        return null
    }
 
    /**
     * 对于每一个规范考核项,生成相应的评分块中的各级标题,及得到具体评分的基本项list: mData
     * @param list
     * @param baseRuleItemVo
     * @param linearLayout
     */
    private fun foo(
            list: ArrayList<EvaluationsubruleVo>,
            baseRuleItemVo: EvaluationsubruleVo,
            linearLayout: LinearLayout
    ): LinearLayout {
        val tmpList = viewModel.getByFatherId(list, baseRuleItemVo.guid ?: "")
 
        //对于没有子项的具体评分项目,生成评分列表(ListView)
        if (tmpList.size == 0) {
            viewModel.mData.add(baseRuleItemVo)
            return linearLayout
        }
        //对于有子项的规范评分考核项,生成为标题(TextView)
        else {
            var newLayout = if (baseRuleItemVo.fatherid == erGuid) {
                generateNewTextView(
                        linearLayout,
                        "${baseRuleItemVo.itemname}(${baseRuleItemVo.maxscore}分)",
                        20
                )
            } else {
                generateNewTextView2(
                        linearLayout,
                        baseRuleItemVo.itemname,
                        "${baseRuleItemVo.maxscore}"
                )
            }
            for (i in tmpList.indices) {
                newLayout = foo(list, tmpList[i], linearLayout)
                if (i == tmpList.size - 1 && viewModel.mData.isNotEmpty()) {
                    val tmpData = ArrayList<EvaluationsubruleVo>()
                    tmpData.addAll(viewModel.mData)
                    newLayout = generateNewListView(tmpData, linearLayout)
                    viewModel.mData.clear()
                }
            }
            return newLayout
        }
    }
 
    /**
     * 新增一个TextView
     * @param linearLayout
     * @param text
     * @param size
     * @return
     */
    private fun generateNewTextView(linearLayout: LinearLayout, text: String, size: Int): LinearLayout {
        val layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        val textView = TextView(this)
        textView.text = text
        textView.layoutParams = layoutParams
        textView.textSize = size.toFloat()
        //        textView.setWidth(0);
        //        textView.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        //        textView.setInputType(InputType.TYPE_CLASS_TEXT);
        textView.gravity = Gravity.CENTER_HORIZONTAL
        textView.setPadding(5.dp, 5.dp, 5.dp, 5.dp)
        textView.setBackgroundColor(0)
        textView.setTextColor(ContextCompat.getColor(this, R.color.colorPrimary))
        textView.setHintTextColor(Color.rgb(199, 199, 199))
 
        linearLayout.addView(textView, layoutParams)
 
        return linearLayout
    }
 
    private fun generateNewTextView2(linearLayout: LinearLayout, title: String, point: String): LinearLayout {
        val layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        val ll = LayoutInflater.from(this).inflate(R.layout.layout_text_grade_title, null) as LinearLayout
        val maxPointView = ll.findViewById<TextView>(R.id.tv_max_point_decade)
        val titleView = ll.findViewById<TextView>(R.id.tv_grade_title_2)
        maxPointView.text = point
        titleView.text = title
        linearLayout.addView(ll, layoutParams)
        return linearLayout
    }
 
    /**
     * 创建一个新的ListView
     * @param mData
     * @param linearLayout
     * @return
     */
    private fun generateNewListView(mData: ArrayList<EvaluationsubruleVo>, linearLayout: LinearLayout): LinearLayout {
 
        mData.sortBy {
            it.displayid
        }
        //*****下面是生成具体评分列表(ListView)*****
        val listView = RecyclerView(this)
        val layoutParams =
                LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
        listView.layoutParams = layoutParams
        listView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        listView.isNestedScrollingEnabled = false
 
        var myAdapter: AllRecyclerViewAdapter<EvaluationsubruleVo>? = null
 
        myAdapter = object : AllRecyclerViewAdapter<EvaluationsubruleVo>(mData, R.layout.item_evalution_grade, this) {
            override fun bindView(holder: MyViewHolder?, obj: EvaluationsubruleVo?, isSelected: Boolean, position: Int) {
                val tmpFatherVo = findByFatherIdVo(viewModel.ruleItemList.value!!, obj?.fatherid)
                val mutiChoice = tmpFatherVo?.mutichoice//单选、多选、全选
                val maxPoint = tmpFatherVo?.maxscore ?: 0//最高分
 
                //设置能否点击
                holder?.setEnabled(R.id.tv_item, true)
                        ?.setEnabled(R.id.TV_grade, true)
                        ?.setEnabled(R.id.ll_item, true)
                        ?.setEnabled(R.id.BT_minus, true)
                        ?.setEnabled(R.id.BT_plus, true)
 
                //基本评分项
                holder?.setText(R.id.tv_item, "${obj?.itemname}")
                        ?.setText(R.id.tv_max_point_decade, "${getString(R.string.minus)}${maxPoint.minus(obj?.maxscore ?: 0)}")
 
                //避免分数为null
                if (obj?.grade == null) {
                    obj?.grade = "0"
                    try {
                        obj?.grade = obj?.defaultvalue
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
                holder?.setText(R.id.TV_grade, obj?.grade.toString())
 
                //根据评分项是否选中变更显示状态(默认单选)
                val colorSelected = ContextCompat.getColor(this@MenuGradeActivity, R.color.colorAccent)
                val colorUnSelected = ContextCompat.getColor(this@MenuGradeActivity, R.color.gray)
                if (obj?.isSelected == true) {
                    holder?.setTextColor(R.id.tv_item, colorSelected)
                            ?.setBackgroudTint(R.id.cl_max_point, colorSelected)
                            ?.setAlpha(R.id.tv_item, 1f)
                            ?.setAlpha(R.id.cl_max_point, 1f)
                } else {
                    holder?.setTextColor(R.id.tv_item, colorUnSelected)
                            ?.setBackgroudTint(R.id.cl_max_point, colorUnSelected)
                            ?.setAlpha(R.id.tv_item, 0.5f)
                            ?.setAlpha(R.id.cl_max_point, 0.5f)
                }
 
                //点击评分项文字选择评分数值
                holder?.setOnClickListener(R.id.ll_item, View.OnClickListener {
                    if (isUpLoad) return@OnClickListener
                    isEdited = true
//                    var maxScore = 0
//                    var minScore = 0
//                    //按照打分方式设定分数范围
//                    maxScore = obj?.maxscore ?: 0
//                    minScore = obj?.minscore ?: 0
//                    showChoiceDialog(
//                        minScore,
//                        (minScore + maxScore) / 2,
//                        maxScore,
//                        obj!!,
//                        adapters
//                    )
//                    obj.isSelected = true
//                    notifyDataSetChanged()
 
                    // fixme: 2020/7/1 评分方式修改为每一项固定分值,单选
 
                    mData.forEach {
                        it.grade = "0"
                        it.isSelected = false
                    }
                    obj?.grade = (0 - maxPoint.minus(obj?.maxscore ?: 0)).toString()//记录扣除的分数,负数
                    obj?.isSelected = true
                    myAdapter?.notifyDataSetChanged()
                })
 
                //减号监听事件
                holder?.setOnClickListener(R.id.BT_minus, View.OnClickListener {
                    if (isUpLoad) return@OnClickListener
                    isEdited = true
 
                    val minScore: Int = obj?.minscore ?: 0
                    obj?.isSelected = true
                    //按照打分方式设定分数范围
                    try {
                        val tmpScore = obj?.grade?.toIntOrNull() ?: 0
 
                        if (tmpScore > minScore) {
                            obj?.grade = (tmpScore - 1).toString()
                            notifyDataSetChanged()
                        }
                    } catch (e: NumberFormatException) {
                        e.printStackTrace()
                    }
                })
 
                //加号监听事件
                holder?.setOnClickListener(R.id.BT_plus, View.OnClickListener {
                    if (isUpLoad) return@OnClickListener
                    isEdited = true
 
                    val maxScore: Int = obj?.maxscore ?: 0
                    obj?.isSelected = true
                    //按照打分方式设定分数范围
                    try {
                        val tmpScore = obj?.grade?.toIntOrNull() ?: 0
 
                        if (tmpScore < maxScore) {
                            obj?.grade = (tmpScore + 1).toString()
                            notifyDataSetChanged()
                        }
                    } catch (e: NumberFormatException) {
                        e.printStackTrace()
                    }
                })
            }
 
        }
 
        listView.adapter = myAdapter
        adapters.add(myAdapter)
 
        val cardView = CardView(this).apply {
            padding = 2.dp
            radius = 6F
            cardElevation = 1.dp.toFloat()
        }
        cardView.addView(listView, layoutParams)
 
        layoutParams.margin = 2.dp
//        setListViewHeightBasedOnChildren(listView)
        linearLayout.addView(cardView, layoutParams)
 
        return linearLayout
    }
 
    /**
     * 通过fatherid找到父评分项( 默认父评分项只有一个)
     * @param ruleItemVos
     * @param fatherId
     * @return
     */
    private fun findByFatherIdVo(
            ruleItemVos: ArrayList<EvaluationsubruleVo>,
            fatherId: String?
    ): EvaluationsubruleVo? {
 
        if (fatherId == null) return null
 
        var resRuleItemVo = EvaluationsubruleVo()
 
        for (i in ruleItemVos.indices) {
            if (ruleItemVos[i].guid == fatherId) {
                resRuleItemVo = ruleItemVos[i]
                break
            }
        }
 
        return resRuleItemVo
    }
 
    /**
     * 分数选择对话框
     * @param lowestScore
     * @param halfScore
     * @param fullScore
     * @param obj
     * @param adapters
     */
    private fun showChoiceDialog(lowestScore: Int, halfScore: Int, fullScore: Int, obj: EvaluationsubruleVo, adapters: ArrayList<AllRecyclerViewAdapter<EvaluationsubruleVo>>) {
        DialogUtil2.Builder(this).apply {
            setContentView(R.layout.dialog_select_point)
            setTitle(getString(R.string.quick_grade))
            setPositiveButton("${fullScore}分", DialogInterface.OnClickListener { dialog, _ ->
                obj.grade = fullScore.toString()
                dialog?.dismiss()
                for (i in adapters.indices) {
                    adapters[i].notifyDataSetChanged()
                }
            })
            setNegativeButton("${halfScore}分", DialogInterface.OnClickListener { dialog, _ ->
                obj.grade = halfScore.toString()
                dialog?.dismiss()
                for (i in adapters.indices) {
                    adapters[i].notifyDataSetChanged()
                }
            })
            setNeutralButton("${lowestScore}分", DialogInterface.OnClickListener { dialog, _ ->
                obj.grade = lowestScore.toString()
                dialog?.dismiss()
                for (i in adapters.indices) {
                    adapters[i].notifyDataSetChanged()
                }
            })
        }.create().show()
    }
 
    private fun onSave() {
        val disposable = Observable.create<Int> { emitter ->
            emitter.onNext(viewModel.calculateGrade(adapters))
            emitter.onComplete()
        }.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(Consumer { totalPoint ->
                    DialogUtil2.Builder(this).apply {
                        setTitle("总分确认")
                        setContent("${totalPoint}分")
                        setPositiveButton(getString(R.string.save), DialogInterface.OnClickListener { dialog, _ ->
                            viewModel.saveGrade(inspectionGuid, subtask?.stguid, scense, totalPoint)
                            dialog?.dismiss()
                            finish()
                        })
                        setNegativeButton(getString(R.string.not_save), DialogInterface.OnClickListener { dialog, _ ->
                            dialog?.dismiss()
                            finish()
                        })
                        setNeutralButton(getString(R.string.cancel), DialogInterface.OnClickListener { dialog, _ ->
                            dialog?.dismiss()
                        })
                    }.create().show()
 
                })
        disposableList.add(disposable)
    }
 
}