feiyu02
2024-11-19 752e00503f672ddfe2066afb6c235721a3a912b5
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
package cn.flightfeather.supervision.lightshare.service.Impl
 
import cn.flightfeather.supervision.common.score.AutoScore
import cn.flightfeather.supervision.domain.entity.*
import cn.flightfeather.supervision.domain.enumeration.AssessmentRuleType
import cn.flightfeather.supervision.domain.enumeration.SceneType
import cn.flightfeather.supervision.domain.mapper.*
import cn.flightfeather.supervision.domain.repository.EvaluationRep
import cn.flightfeather.supervision.infrastructure.utils.DateUtil
import cn.flightfeather.supervision.infrastructure.utils.UUIDGenerator
import cn.flightfeather.supervision.domain.repository.UserConfigRep
import cn.flightfeather.supervision.lightshare.service.EvaluationService
import cn.flightfeather.supervision.lightshare.service.ItemevaluationService
import cn.flightfeather.supervision.lightshare.vo.*
import com.github.pagehelper.PageHelper
import org.springframework.stereotype.Service
import tk.mybatis.mapper.entity.Example
import java.time.LocalDateTime
import java.util.*
import javax.servlet.http.HttpServletResponse
 
@Service
class EvaluationServiceImpl(
    val evaluationMapper: EvaluationMapper,
    val evaluationruleMapper: EvaluationruleMapper,
    val evaluationsubruleMapper: EvaluationsubruleMapper,
    val userinfoMapper: UserinfoMapper,
    val baseInfoMapper: BaseInfoMapper,
    val companyMapper: CompanyMapper,
    val overallEvaluationMapper: OverallEvaluationMapper,
    val autoScore: AutoScore,
    val itemevaluationService: ItemevaluationService,
    private val userConfigRep: UserConfigRep,
    private val evaluationRep: EvaluationRep,
) : EvaluationService {
 
    override fun findOne(id: String): Evaluation = evaluationMapper.selectByPrimaryKey(id)
 
    override fun findAll(): MutableList<Evaluation> = evaluationMapper.selectAll()
 
    override fun save(evaluation: Evaluation): Int {
        updateRank(evaluation, true)
        return evaluationMapper.insert(evaluation)
    }
 
    override fun update(evaluation: Evaluation): Int {
        updateRank(evaluation, false)
        return evaluationMapper.updateByPrimaryKey(evaluation)
    }
 
    override fun delete(id: String): Int = evaluationMapper.deleteByPrimaryKey(id)
 
    override fun getTotalPoints(
        userId: String,
        evaluatorType: Int,
        startTime: String,
        endTime: String,
        sceneTypeId: Int?,
        erGuid: String?,
        eId: String?,
    ): List<Evaluation> {
        val example = Example(Evaluation::class.java)
        val criteria = example.createCriteria()
        val startDate = DateUtil.StringToDate(startTime)
        val endDate = DateUtil.StringToDate(endTime)
        criteria.andEqualTo("iguid", userId)
            .andBetween("createdate", startDate, endDate)
        example.and(example.createCriteria().apply {
            if (evaluatorType == 0) {
                orEqualTo("evaluatorrealname", evaluatorType.toString())
                    .orIsNull("evaluatorrealname")
            } else {
                andEqualTo("evaluatorrealname", evaluatorType.toString())
            }
        })
        erGuid?.let { criteria.andEqualTo("stguid", erGuid) }
        eId?.let { criteria.andEqualTo("guid", eId) }
        sceneTypeId?.let {
            example.and(example.createCriteria()
                .orEqualTo("scensetypeid", sceneTypeId.toByte())
                .orIsNull("scensetypeid")
            )
        }
 
        return evaluationMapper.selectByExample(example)
    }
 
    override fun getHistoryPoint(
        userId: String,
        page: Int,
        per_page: Int,
        platform: String?,
        period: String?,
        response: HttpServletResponse,
    ): List<AssessmentGradeVo> {
        val userInfo = userinfoMapper.selectByPrimaryKey(userId) ?: return emptyList()
        // FIXME: 2022/11/8 临时添加过度功能,提供微信小程序前端汽修类型的场景单独的评估清单 ,场景类型为 -7
        var sceneType = userInfo.extension2
        if (platform == "weixin" && sceneType == SceneType.VehicleRepair.value.toString()) {
            sceneType = "-7"
        }
        //评分规则下的分级、等级颜色及等级评语
        val pointLevel = mutableListOf<Pair<Int, Int>>()
        val evaluateLevel = mutableListOf<String>()
        val creditTexts = mutableListOf<String>()
        val levelColors = mutableListOf<String>()
        val rule = evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
            createCriteria().andEqualTo("scensetypeid", sceneType)
                .andEqualTo("ruletype", "0")
        })
        if (rule.isNotEmpty()) {
            val r = rule[0]
            r.extension1?.split("#")?.forEach {
                val pStr = it.split(",")
                pointLevel.add(Pair(pStr[0].toInt(), pStr[1].toInt()))
            }
            r.extension2?.split("#")?.forEach {
                evaluateLevel.add(it)
            }
            r.extension3?.split("#")?.forEach {
                creditTexts.add(it)
            }
            r.remark?.split(";")?.forEach {
                levelColors.add(it)
            }
        }
        val example = Example(Evaluation::class.java).apply {
            createCriteria().andEqualTo("iguid", userId)
                .andEqualTo("ertype", AssessmentRuleType.Total.value.toByte())
                .apply {
                    period?.let { andEqualTo("scensename", it) }
                }
            //根据评估人的类型进行筛选,自评和官方评分分开排名
            and(
                createCriteria().orIsNull("evaluatorrealname")
                    .orEqualTo("evaluatorrealname", 0)
            )
            orderBy("createdate").desc()
        }
        val counts = evaluationMapper.selectCountByExample(example)
        val totalPage = Math.ceil(counts.toDouble() / per_page.toDouble()).toInt()
        response.setIntHeader("totalPage", totalPage)
        response.setIntHeader("currentPage", page)
 
        val offset = per_page.times(page - 1)
        PageHelper.offsetPage<Evaluation>(offset, per_page)
 
        val resultList = mutableListOf<AssessmentGradeVo>()
        evaluationMapper.selectByExample(example).forEach {
            resultList.add(AssessmentGradeVo().apply {
                this.userId = userId
                userRealName = userInfo.realname
                this.sceneType = userInfo.extension2?.toIntOrNull() ?: SceneType.NoType.value
                tPGuid = it.guid
                tPRuleGuid = it.stguid
                totalPoint = it.resultscorebef?.toInt() ?: 0
                val l = getEvaluationLevel(totalPoint, pointLevel, evaluateLevel, creditTexts, levelColors)
                level = l["evaluateLevel"]
                color = l["color"]
                creditText = l["creditText"]
                rank = it.promissednum ?: 1
                updateDate = it.createdate
                this.period = it.scensename
            })
        }
 
        return resultList
    }
 
    override fun getCreditInfo(userId: String, period: String?): CreditInfoVo {
        val userinfo = userinfoMapper.selectByPrimaryKey(userId) ?: return CreditInfoVo()
        val baseInfo = baseInfoMapper.selectByPrimaryKey(userId)
        val company = baseInfo?.let { companyMapper.selectByPrimaryKey(it.ciGuid) }
 
        val result = CreditInfoVo(
            userId,
            baseInfo?.biName,
            userinfo?.extension2?.toIntOrNull() ?: SceneType.NoType.value,
            baseInfo?.ciName,
            baseInfo?.biManagementCompany,
            baseInfo?.biContact,
            baseInfo?.biTelephone,
            baseInfo?.biAddress,
            district = company?.ciDistrictName,
            town = company?.ciTownName
        )
 
        val rule = evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
            val c = createCriteria()
            userinfo?.extension2?.toByteOrNull()?.let {
                c.andEqualTo("scensetypeid", it)
                    .andEqualTo("ruletype", "0")
            }
        }).takeIf { it.isNotEmpty() }?.get(0) ?: return result
 
        val periodList = DateUtil.getSuitablePeriod(period)
        val overallEvaluation = overallEvaluationMapper.selectByExample(Example(OverallEvaluation::class.java).apply {
            createCriteria().andEqualTo("biGuid", userinfo?.guid)
                .apply {
                    if (periodList.isNotEmpty()) {
                        andIn("oePeriod", periodList)
                    }
                }
            orderBy("oePublishTime").desc()
        }).takeIf { it.isNotEmpty() }?.get(0) ?: return result
 
        //评分记录对应 的打分周期 ,格式为 YYYY/M-M,某年某月至某月
//        val period = overallEvaluation.oePeriod
        //评分等级分数界限,格式为  0,59#60,89#90,100,表示有三个分数段
        val levels = rule.extension1?.split("#")?.asReversed()
        //评分等级对应的描述,格式为 较差#一般#优秀,对应三个分数段的描述
        val levelDes = rule.extension2?.split("#")?.asReversed()
 
        var creditLevel: Int? = null
        var creditLevelDes: String? = null
 
        if (levels != null && levelDes != null && levels.size == levelDes.size) {
            for (i in levels.indices) {
                val list = levels[i].split(",")
                if (list.size == 2) {
                    val min = list[0].toInt()
                    val max = list[1].toInt()
                    val score = overallEvaluation.oeScore
                    if (score in min..max) {
                        creditLevel = i
                        creditLevelDes = levelDes[i]
                        break
                    }
                }
            }
        }
        val codeLevel =
            when (overallEvaluation.oeCodeLevel) {
                0.toByte() -> "绿码"
                1.toByte() -> "黄码"
                2.toByte() -> "红码"
                else -> null
            }
 
        result.publishTime = DateUtil.DateToString(overallEvaluation.oePublishTime, "YYYY年MM月")
        result.updateTime = DateUtil.DateToString(overallEvaluation.oeUpdateTime, "YYYY年MM月")
        result.creditLevel = creditLevel
        result.creditLevelDes = creditLevelDes
        result.codeLevel = codeLevel
        result.score = overallEvaluation.oeScore?.toString()
 
        return result
    }
 
    override fun getCreditCount(userId: String, condition: UserSearchCondition): BaseResponse<CountVo> {
        if (condition.sceneTypes.size != 1) return BaseResponse(false, "只支持单个场景类型的查询")
 
        val config = userConfigRep.getUserConfigBySubType(userId)
        val condition2 = UserSearchCondition.fromUserConfig(config, condition)
 
        // 绿码
        var level0 = 0
        // 黄码
        var level1 = 0
        // 红码
        var level2 = 0
        condition2.period = condition2.period
            ?: overallEvaluationMapper.getLatestPeriod(condition2)
                    ?: return BaseResponse(false, "无记录")
 
        overallEvaluationMapper.getCreditCount(condition2).forEach {
            when (it.oeCodeLevel?.toInt()) {
                0 -> level0++
                1 -> level1++
                2 -> level2++
            }
        }
        val result = CountVo().apply {
            tag = condition2.period
            countList.addAll(listOf(level0, level1, level2))
        }
 
        return BaseResponse(true, data = result)
    }
 
    override fun getAssessments(
        userId: String,
        condition: AssessmentSearchCondition,
        page: Int,
        perPage: Int,
        response: HttpServletResponse,
    ): List<AssessmentGradeVo> {
        val user = userinfoMapper.selectByPrimaryKey(userId)
        val districtName = user?.extension1
 
        val p = PageHelper.startPage<Evaluation>(page, perPage)
 
        val result = mutableListOf<AssessmentGradeVo>()
        evaluationMapper.getAssessments(districtName ?: "", condition.searchText, "", condition.sceneTypes).forEach {
            //此处由于 PageHelper 的分页操作,会导致结果的数量强制为 perPage的值,包括null
            if (it != null) {
                result.add(AssessmentGradeVo().apply {
                    this.userId = it["userId"] as String?
                    userRealName = it["userRealName"] as String?
                    sceneType = (it["sceneType"] as String?)?.toIntOrNull() ?: SceneType.Restaurant.value
                    tPGuid = it["tPGuid"] as String?
                    tPRuleGuid = it["tPRuleGuid"] as String?
                    totalPoint = (it["totalPoint"] as String?)?.toIntOrNull() ?: 0
                    level = getEvaluationLevel(totalPoint)["evaluateLevel"]
                    rank = (it["rank"] as Int?) ?: -1
                    updateDate = it["updateDate"] as Date?
                })
            }
        }
 
        response.setIntHeader("totalPage", p.pages)
        response.setIntHeader("currentPage", p.pageNum)
 
        return result
    }
 
    override fun autoScore(year: Int, month: Int, sceneType: Int, response: HttpServletResponse): HttpServletResponse {
        autoScore.go()
        return response
    }
 
    override fun uploadScore(
        userId: String,
        period: String,
        ruleId: String?,
        itemList: List<Pair<String, String>>,
    ): Boolean {
        val userinfo = userinfoMapper.selectByPrimaryKey(userId) ?: return false
        var sceneType = userinfo.extension2
 
        // FIXME: 2022/11/8 临时添加过度功能,提供微信小程序前端汽修类型的场景单独的评估清单 ,场景类型为 -7
        if (sceneType == SceneType.VehicleRepair.value.toString()) {
            sceneType = "-7"
        }
 
        //该场景类型下的总得分规则
        val tRule = evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
            createCriteria().andEqualTo("scensetypeid", sceneType)
                .andEqualTo("ruletype", AssessmentRuleType.Total.value)
                .andIsNull("tasktypeid")
        }).takeIf { it.isNotEmpty() }?.get(0)
 
        var totalPoint = 0
        var tEvaluation = Evaluation()
 
        evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
            createCriteria().andEqualTo("scensetypeid", sceneType)
                .andNotEqualTo("ruletype", AssessmentRuleType.Total.value)
                .andIsNull("tasktypeid")
        }).forEach { rule ->
            val subRules = evaluationsubruleMapper.selectByExample(Example(Evaluationsubrule::class.java).apply {
                createCriteria().andEqualTo("erguid", rule.guid)
            })
            if (subRules.isEmpty()) return@forEach
            //总分记录
            val evaluation = Evaluation().apply { guid = UUIDGenerator.generate16ShortUUID() }
            //具体项得分记录
            val itemEvaluationList = mutableListOf<Itemevaluation>()
            //总得分
            var totalScore = 0
 
            //根据上传的选择的条目,生成对应的评分记录
            itemList.forEach {
                for (s in subRules) {
                    if (s.guid == it.first) {
                        var fatherId: String?
                        var subRule = s
                        var score = it.second
                        // 根据上传的条目生成对应的该条目得分记录以及其所有的父项条目的得分记录
                        do {
                            val result =
                                calculateScore(rule, evaluation.guid!!, userId, subRule, score, itemEvaluationList)
                            fatherId = result.first
                            for (s1 in subRules) {
                                if (s1.guid == fatherId) {
                                    subRule = s1
                                    score = result.second ?: "0"
                                    break
                                }
                            }
                        } while (fatherId?.isNotBlank() == true)
                        break
                    }
                }
            }
 
            //规则设定的最大分值
            var maxScore = 0
            subRules.forEach subRules@{ s ->
                //计算应得总分,basic_score:表示基础分,计算在应得总分内;addition_score表示加分,不计算在内
                if (s.ertype == 2 && s.extension1 != "addition_score") {
                    maxScore += s.maxscore ?: 0
                }
                //规则已经打分完毕,则跳过
                itemEvaluationList.forEach { i ->
                    if (i.esrguid == s.guid) {
                        //如果是最大的2级评估规则,计算已获得的总分
                        if (s.ertype == 2) {
                            totalScore += i.value?.toInt() ?: 0
                        }
                        return@subRules
                    }
                }
                //否则如果前端允许不用全部评分,新增一条未评分的记录
                itemEvaluationList.add(Itemevaluation().apply {
                    ieguid = UUIDGenerator.generate16ShortUUID()
                    iguid = userId
                    sguid = evaluation.guid
                    erguid = rule.guid
                    rulename = rule.rulename
                    ruletype = rule.ruletype?.toInt()
                    ertype = s.ertype
                    esrguid = s.guid
                    name = s.itemname
                    value = "0"
                    extension1 = "false"
                })
            }
            //计算总分
            evaluation.apply {
                iguid = userId
                stguid = rule.guid
                scensetypeid = userinfo.extension2?.toByte()
                ertype = rule.ruletype?.toByte()
                scensename = period
                evaluatorguid = userId
                evaluatorusername = userinfo.acountname
                evaluatorrealname = "0"
                resultscorebef = (maxScore + totalScore).toString()
                createdate = Date()
                updatedate = Date()
            }
            save(evaluation)
            itemevaluationService.savelist(itemEvaluationList)
            tEvaluation = evaluation
 
            totalPoint += evaluation.resultscorebef?.toInt() ?: 0
        }
 
        //计算所有表的总分
        tRule?.let {
            tEvaluation.apply {
                guid = UUIDGenerator.generate16ShortUUID()
                stguid = it.guid
                ertype = it.ruletype?.toByte()
                resultscorebef = totalPoint.toString()
            }
            save(tEvaluation)
        }
        return true
    }
 
    override fun updateScore(
        userId: String,
        period: String,
        ruleId: String?,
        itemList: List<Pair<String, String>>,
    ): Boolean {
        TODO("Not yet implemented")
    }
 
    override fun getDetail(userId: String, period: String): GradeDetailVo {
        val list = period.split("-")
        var endM = list[1].toInt()
        val list2 = list[0].split("/")
        val year = list2[0].toInt()
        var startM = list2[1].toInt()
        var st = LocalDateTime.of(year, startM, 1, 0, 0, 0, 0)
        var et = LocalDateTime.of(year, endM, 1, 0, 0, 0, 0).plusMonths(1)
 
        val result = GradeDetailVo()
 
        val userinfo = userinfoMapper.selectByPrimaryKey(userId) ?: return result
        var sceneType = SceneType.getByValue(userinfo.extension2?.toIntOrNull())
        // FIXME: 2022/11/8 临时添加过度功能,提供微信小程序前端汽修类型的场景单独的评估清单 ,场景类型为 -7
        if (sceneType == SceneType.VehicleRepair) {
            sceneType = SceneType.VehicleRepair
        }
 
        //该场景类型下的所有得分规则
        val rule0 = evaluationRep.findRule(sceneType) ?: return result
        //获得得分规则中定义的评估周期(单位:月)
        val rulePeriod = rule0.scensesubtypeid?.toInt() ?: 1
        DateUtil.getStartMonthByPeriod(startM, rulePeriod)?.let {
            startM = it
            endM = startM + rulePeriod - 1
            st = LocalDateTime.of(year, startM, 1, 0, 0, 0, 0)
            et = LocalDateTime.of(year, endM, 1, 0, 0, 0, 0).plusMonths(1)
        }
        //获取最新一期的总分
        val latestEva = evaluationRep.findLatest(rule0.guid, userId, period, st, et)
        //根据总分周期获取相同周期内的子评分
        val latestSubEva = evaluationMapper.selectByExample(Example(Evaluation::class.java).apply {
            createCriteria().andEqualTo("iguid", userId)
                .andEqualTo("scensename", latestEva?.scensename)
                .andNotEqualTo("ertype", AssessmentRuleType.Total.value.toByte())
        })
        latestEva?.let {
            latestSubEva.add(it)
        }
        latestSubEva.forEach { e ->
            val rule = evaluationruleMapper.selectByPrimaryKey(e.stguid)
            //总分规则,生成总体评价
            if (rule.ruletype == AssessmentRuleType.Total.value.toString()) {
                rule?.apply {
                    val pointLevel = mutableListOf<Pair<Int, Int>>()
                    val evaluateLevel = mutableListOf<String>()
                    val creditTexts = mutableListOf<String>()
                    val levelColors = mutableListOf<String>()
                    extension1?.split("#")?.forEach {
                        val pStr = it.split(",")
                        pointLevel.add(Pair(pStr[0].toInt(), pStr[1].toInt()))
                    }
                    extension2?.split("#")?.forEach {
                        evaluateLevel.add(it)
                    }
                    extension3?.split("#")?.forEach {
                        creditTexts.add(it)
                    }
                    remark?.split(";")?.forEach {
                        levelColors.add(it)
                    }
 
                    val l = getEvaluationLevel(e.resultscorebef?.toInt()
                        ?: 0, pointLevel, evaluateLevel, creditTexts, levelColors)
                    result.apply {
                        creditText = l["creditText"]
                        score = e.resultscorebef?.toInt() ?: 0
                        rank = e.promissednum
                        level = l["evaluateLevel"]
                        this.period = latestEva?.scensename
                        time = e.createdate
//                    color = l["color"]
                    }
                }
            }
            //具体评估表
            else {
                val subRules = evaluationsubruleMapper.selectByExample(Example(Evaluationsubrule::class.java).apply {
                    createCriteria().andEqualTo("erguid", rule.guid)
                })
                val itemEvaluations = itemevaluationService.getItemEvaluationList(e.guid!!)
                val ruleMap = result.loseScore
                val ruleMap2 = result.scoring
                //分类别的得分(每个评分表的评分大项的得分)和失分条目
                itemEvaluations.sortedBy { it.ertype }.forEach { item ->
                    val value = item.value?.toInt() ?: 0
                    when (item.ertype) {
                        //分类别的得分
                        2 -> {
                            ruleMap[item.name] = mutableMapOf()
                            ruleMap2[item.name] = mutableMapOf()
                            for (s in subRules) {
                                if (s.guid == item.esrguid) {
                                    val score = if (value <= 0) {
                                        s.maxscore?.plus(value)
                                    } else {
                                        value
                                    }
                                    result.classScore.add(Triple(item.name ?: "",
                                        s.maxscore?.toString() ?: "0",
                                        score.toString()))
                                    break
                                }
                            }
                        }
                        3 -> {
                            if (value != 0 && item.extension1 == "true") {
                                val map = if (value > 0) ruleMap2 else ruleMap
                                for (s in subRules) {
                                    if (s.guid == item.esrguid) {
                                        if (!map.containsKey(s.fathername)) {
                                            map[s.fathername] = mutableMapOf()
                                        }
                                        map[s.fathername]?.put(item.name, mutableListOf())
                                        break
                                    }
                                }
                            }
                        }
                        //失分或得分条目
                        4 -> {
                            if (value != 0 && item.extension1 == "true") {
                                val map = if (value > 0) ruleMap2 else ruleMap
                                for (s in subRules) {
                                    if (s.guid == item.esrguid) {
                                        val d =
                                            Triple(
                                                item.name ?: "",
//                                                if ((item.value?.toInt() ?: 0) < 0) {
//                                                    item.value ?: "0"
//                                                } else {
//                                                    (item.value?.toInt() ?: 0).minus(s.maxscore ?: 0).toString()
//                                                },
                                                item.value ?: "0",
                                                s.remark ?: ""
                                            )
                                        val rule3Name = s.fathername
                                        for (s1 in subRules) {
                                            if (s1.itemname == rule3Name) {
                                                val rule2Name =
                                                    //父id为空,说明此4级评估项直接附属于2级评估项
                                                    if (s1.fathername.isNullOrBlank()) {
                                                        map[rule3Name]?.put(rule3Name, mutableListOf())
                                                        rule3Name
                                                    } else {
                                                        s1.fathername
                                                    }
                                                map[rule2Name]?.get(rule3Name)?.add(d)
                                                break
                                            }
                                        }
 
                                        break
                                    }
                                }
                            }
                        }
                    }
                }
            }
 
        }
 
 
        return result
    }
 
    override fun searchGradeList(
        userId: String,
        condition: UserSearchCondition,
        page: Int,
        perPage: Int,
    ): BaseResponse<List<CreditInfoVo>> {
        if (condition.period == null) return BaseResponse(false, "必须选择周期")
        if (condition.sceneTypes.size > 2) return BaseResponse(false, "场景类型只支持一种")
 
        val config = userConfigRep.getUserConfigBySubType(userId)
        val condition2 = UserSearchCondition.fromUserConfig(config, condition)
 
//        val period = condition.period!!
//        val sceneType = condition.sceneTypes[0]
//        var district = condition.districtName
//        val sort = condition.sorts
//
//        if (district == null) {
//            val userInfo = userinfoMapper.selectByPrimaryKey(userId)
//            district = userInfo?.extension1
//        }
        val p = PageHelper.startPage<Evaluation>(page, perPage)
        val result = evaluationMapper.searchGradeList(condition2).onEach {
                if (it.score == null) it.score = "/"
            }
        return BaseResponse(true, head = DataHead(p.pageNum, p.pages, p.total), data = result)
    }
 
    /**
     * 根据上传的子规则扣分情况,生成子项得分记录
     * @param rule 总规则
     * @param eGuid 总分记录id
     * @param userId 用户id
     * @param subRule 扣分的规则
     * @param score 扣分
     * @param itemEvaluationList 得分记录表
     * @return 评分项的父id和得分
     */
    private fun calculateScore(
        rule: Evaluationrule,
        eGuid: String,
        userId: String,
        subRule: Evaluationsubrule,
        score: String,
        itemEvaluationList: MutableList<Itemevaluation>,
    ): Pair<String?, String?> {
        var result: Pair<String?, String?> = Pair(null, null)
        var exist = false
        for (i in itemEvaluationList) {
            //记录已存在,说明是父项的评分规则下的某个子项的一部分扣分,扣分累加,并且不能超过父项的上限
            if (subRule.guid == i.esrguid) {
                val s = i.value?.toInt()?.plus(score.toInt()) ?: 0
                //加分模式
                if (subRule.extension2 == "add_mode") {
                    if (s > (subRule.maxscore ?: 0)) {
                        i.value = subRule.maxscore?.toString() ?: "0"
                    } else {
                        i.value = s.toString()
                    }
                }
                //默认情况为减分模式
                else {
                    //允许扣除的分数最小值(负数)
                    val min = subRule.minscore?.minus(subRule.maxscore ?: 0) ?: 0
                    if (s < min) {
                        i.value = min.toString()
                    } else {
                        i.value = s.toString()
                    }
                }
                result = Pair(subRule.fatherid, i.value)
                exist = true
                break
            }
        }
        //记录不存在时,说明是子项第一次扣分,新增一条记录
        if (!exist) {
            itemEvaluationList.add(Itemevaluation().apply {
                ieguid = UUIDGenerator.generate16ShortUUID()
                iguid = userId
                sguid = eGuid
                erguid = rule.guid
                rulename = rule.rulename
                ruletype = rule.ruletype?.toInt()
                ertype = subRule.ertype
                esrguid = subRule.guid
                name = subRule.itemname
                value = score
                extension1 = "true"
            })
            result = Pair(subRule.fatherid, score)
        }
        return result
    }
 
    /**
     * 根据分数获取等级
     */
    private fun getEvaluationLevel(
        score: Int,
        pointLevel: MutableList<Pair<Int, Int>> = mutableListOf(),
        evaluateLevel: MutableList<String> = mutableListOf(),
        creditTexts: MutableList<String> = mutableListOf(),
        levelColors: MutableList<String> = mutableListOf(),
    ): Map<String, String> {
        val result = mutableMapOf<String, String>()
        if (pointLevel.isEmpty() || evaluateLevel.isEmpty() || creditTexts.isEmpty() || levelColors.isEmpty()) {
            result["evaluateLevel"] = when (score) {
                in 0..40 -> "极差"
                in 41..64 -> "较差"
                in 65..79 -> "一般"
                in 80..94 -> "良好"
                in 95..Int.MAX_VALUE -> "优秀"
                else -> "极差"
            }
        } else {
            for (i in pointLevel.indices) {
                if (score in pointLevel[i].first..pointLevel[i].second ||
                    (i == pointLevel.size - 1 && score > pointLevel[i].second)
                ) {
                    result["color"] = levelColors[i % levelColors.size]
                    result["creditText"] = creditTexts[i % creditTexts.size]
                    result["evaluateLevel"] = evaluateLevel[i % evaluateLevel.size]
                }
            }
        }
        return result
 
    }
 
    private fun updateRank(evaluation: Evaluation, isInsert: Boolean) {
        if (evaluation.ertype == AssessmentRuleType.Total.value.toByte()) {
            val eList = evaluationMapper.selectByExample(Example(Evaluation::class.java).apply {
                createCriteria().andEqualTo("scensename", evaluation.scensename)
                    .andIsNotNull("scensename")
                    .andEqualTo("ertype", AssessmentRuleType.Total.value)
                //根据评估人的类型进行筛选,自评和官方评分封面开排名
                if (evaluation.evaluatorrealname == null || evaluation.evaluatorrealname == "0") {
                    and(createCriteria().orIsNull("evaluatorrealname")
                        .orEqualTo("evaluatorrealname", evaluation.evaluatorrealname))
                } else {
                    and(createCriteria().andEqualTo("evaluatorrealname", evaluation.evaluatorrealname))
                }
            })
            if (isInsert) {
                eList.add(evaluation)
            } else {
                for (i in eList.indices) {
                    if (evaluation.guid == eList[i].guid) {
                        eList[i].resultscorebef = evaluation.resultscorebef
                        break
                    }
                }
            }
            eList.sortByDescending {
                it.resultscorebef?.toInt() ?: 0
            }
            val updateList = mutableListOf<Evaluation>()
            for (i in eList.indices) {
                if (eList[i].guid == evaluation.guid) {
                    evaluation.promissednum = i + 1
                } else if (eList[i].promissednum != i + 1) {
                    eList[i].promissednum = i + 1
                    updateList.add(eList[i])
                }
            }
            updateList.forEach {
                evaluationMapper.updateByPrimaryKey(it)
            }
        }
    }
}