feiyu02
2022-11-15 909fd8929d7906f1dca68acc05e36e29b0b9192c
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
package cn.flightfeather.supervision.business.storage
 
import cn.flightfeather.supervision.business.Info
import cn.flightfeather.supervision.business.ScoreItem
import cn.flightfeather.supervision.business.storage.item.*
import cn.flightfeather.supervision.common.utils.Constant
import cn.flightfeather.supervision.common.utils.DateUtil
import cn.flightfeather.supervision.common.utils.ExcelUtil
import cn.flightfeather.supervision.common.utils.UUIDGenerator
import cn.flightfeather.supervision.domain.ds1.entity.*
import cn.flightfeather.supervision.domain.ds1.mapper.*
import cn.flightfeather.supervision.domain.ds2.entity.UserMap
import cn.flightfeather.supervision.domain.ds2.mapper.UserMapMapper
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.hssf.util.HSSFColor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import tk.mybatis.mapper.entity.Example
import java.io.File
import java.io.FileOutputStream
import java.util.*
import javax.annotation.PostConstruct
import kotlin.math.abs
 
/**
 * Date 2022/1/21 13:44
 * Created by feiyu
 * 工地自动评分
 */
@Component
 
class StAutoScore(
    csScoreItem_1: CsScoreItem_1,
    csScoreItem_2: CsScoreItem_2,
    mpScoreItem_1: MpScoreItem_1,
    mpScoreItem_2: MpScoreItem_2,
    stScoreItem_1: StScoreItem_1,
    whScoreItem_1: WhScoreItem_1,
    whScoreItem_2: WhScoreItem_2,
    var sceneType: Constant.ScenseType = Constant.ScenseType.TYPE1, )
{
    companion object {
        private lateinit var instance: StAutoScore
    }
 
    @Autowired
    lateinit var userinfoMapper: UserinfoMapper
 
    @Autowired
    lateinit var userMapMapper: UserMapMapper
 
    @Autowired
    lateinit var scenseMapper: ScenseMapper
 
    @Autowired
    lateinit var evaluationruleMapper: EvaluationruleMapper
 
    @Autowired
    lateinit var evaluationsubruleMapper: EvaluationsubruleMapper2
 
    @Autowired
    lateinit var evaluationMapper: EvaluationMapper
 
    @Autowired
    lateinit var itemevaluationMapper: ItemevaluationMapper
 
    @Autowired
    lateinit var problemlistMapper: ProblemlistMapper
 
    @Autowired
    lateinit var monitorobjectversionMapper: MonitorobjectversionMapper
 
    @Autowired
    lateinit var taskMapper: TaskMapper
 
    @Autowired
    lateinit var inspectionMapper: InspectionMapper
 
    @Autowired
    lateinit var subtaskMapper: SubtaskMapper
 
    //决定是否写h3
    private val hasHead3 = true
 
    private var totalScore = 100//满分
 
    private val itemList = mutableListOf<ScoreItem>()
 
    private val baseRules = mutableListOf<Evaluationrule>()
 
    private val rules = mutableListOf<Pair<Evaluationsubrule2, MutableList<Evaluationsubrule2>>>()
 
    private val topItems = mutableListOf<Evaluationsubrule2>()
 
    // excel文档
    private var workbook = HSSFWorkbook()
    // 文档行数据
    private val rows = mutableListOf<Array<Any>>()
 
    init {
        itemList.apply {
            add(csScoreItem_1)
            add(csScoreItem_2)
            add(mpScoreItem_1)
            add(mpScoreItem_2)
            add(stScoreItem_1)
            add(whScoreItem_1)
            add(whScoreItem_2)
        }
    }
 
    @PostConstruct
    fun init() {
        instance = this
    }
 
 
 
    /**
     * 总任务打分
     * 根据总任务,对下属所有的巡查任务挨个打分
     * @param topTaskId 总任务id
     */
    fun topTaskGrade(topTaskId:String) {
        rows.clear()
        getScoreItem()
        subtaskMapper.selectByTopTask2(topTaskId, sceneType.value.toInt()).forEach {
            sceneGradeP(it)
//            sceneGradeToFile(it)
        }
//        toFile()
    }
 
    /**
     * 单场景打分
     * @param subtask 巡查任务
     */
    fun sceneGrade(subtask: Subtask) {
        // 获取评分规则
        getScoreItem()
 
        sceneGradeP(subtask)
    }
 
    private fun sceneGradeP(subtask: Subtask) {
        val info = itemGrade(subtask)
        val result = totalGrade(info) ?: return
        toDb(info, result)
//        addToFile(rows, info, result.first)
//        toFile()
    }
 
    fun sceneGradeToFile(subtask: Subtask) {
        // 获取评分规则
        getScoreItem()
 
        val info = itemGrade(subtask)
        val result = totalGrade(info) ?: return
        addToFile(rows, info, result.first)
    }
 
    fun grade(subtask: Subtask) {
 
    }
 
    /**
     * 条目打分
     */
    private fun itemGrade(subtask: Subtask): Info {
        // 规则条目得分初始化
        topItems.forEach { s -> s.extension1 = null }
        rules.forEach { p ->
            p.first.extension1 = null
            p.second.forEach { e -> e.extension1 = null }
        }
 
 
        // 获取飞羽监管系统用户信息
        val userInfo = userinfoMapper.selectByExample(Example(Userinfo::class.java).apply {
            createCriteria().andEqualTo("dGuid", subtask.scenseid)
        })?.takeIf { l -> l.isNotEmpty() }?.get(0)
        // 获取飞羽环境系统用户信息
        val tzUserId = userMapMapper.selectByExample(Example(UserMap::class.java).apply {
            createCriteria().andEqualTo("svUserId", userInfo?.guid)
        })?.takeIf { m -> m.isNotEmpty() }?.get(0)?.tzUserId
        val scene = scenseMapper.selectByPrimaryKey(subtask.scenseid)
 
        val info =
            Info(userInfo?.guid, tzUserId, subtask.scenseid, subtask.scensename, sceneType, subTask = subtask, sceneIndex = scene.index)
 
        /** 1. 根据评分规则对应的问题自动判断是否扣分***************************************************************/
        // 获取该次巡查任务下的所有问题
        val pList = problemlistMapper.selectByExample(Example(Problemlist::class.java).apply {
            createCriteria().andEqualTo("stguid", info.subTask?.stguid)
        }).map { it.ptguid }
        // 计算每条评分规则的得分
        rules.forEach { r ->
            // 评分条目
            val rule = r.first
            // 具体评分选项
            val subRule = r.second
            subRule.forEach { sr ->
                sr.problemlist?.split(",")?.forEach { pId ->
                    if (pList.contains(pId)) {
                        sr.extension1 = (0 - (sr.maxscore ?: 0)).toString()
                    }
                }
            }
            var total: Int? = null
            subRule.forEach { sr ->
                if (!sr.extension1.isNullOrBlank()) {
                    total = (total ?: 0) + sr.extension1!!.toInt()
                }
            }
            if (total == null) {
                rule.extension1 = "0"
            } else {
                val s = if (abs(total!!) > rule.maxscore!!) {
                    0 - rule.maxscore!!
                } else {
                    total
                }
                rule.extension1 = s.toString()
            }
        }
        /** 2.部分有特殊评分逻辑的规则进行计算*************************************************************************/
        itemList.forEach { item -> item.execute2(info, rules) }
 
        /** 3. 补全各上级评分项的计分*************************************************************************/
        this.rules.forEach { r ->
            val fatherId = r.first.fatherid
            for (t in topItems) {
                if (t.guid == fatherId) {
                    var s = t.extension1?.toIntOrNull() ?: 0
                    s += r.first.extension1?.toIntOrNull() ?: 0
                    // 限制最高扣分
                    if (abs(s) > (t.maxscore ?: 0)) {
                        s = 0 - (t.maxscore ?: 0)
                    }
                    t.extension1 = s.toString()
                    break
                }
            }
        }
        return info
    }
 
    /**
     * 计算总分
     */
    private fun totalGrade(info: Info): Pair<Evaluation, List<Itemevaluation>>? {
        /** 4. 计算总分*************************************************************************/
        val scene = scenseMapper.selectByPrimaryKey(info.subTask?.scenseid) ?: return null
        val inspection = inspectionMapper.selectByExample(Example(Inspection::class.java).apply {
            createCriteria().andEqualTo("stguid", info.subTask?.stguid)
        })?.takeIf { it.isNotEmpty() }?.let { it[0] }
        var total = 0//总扣除的分数
        topItems.forEach top@{ top ->
            total += top.extension1?.toIntOrNull() ?: 0
        }
        val evaluation = Evaluation()
        baseRules.forEach {
            evaluation.apply {
                guid = UUIDGenerator.generate16ShortUUID()
                iguid = inspection?.guid
                stguid = info.subTask?.stguid
                sguid = info.subTask?.scenseid
                scensetypeid = scene.typeid
                scensetype = scene.type
                subscensetypeid = scene.scensesubtypeid
                subscensetype = scene.scensesubtype
                ertype = it.ruletype?.toByte()
                provincecode = scene.provincecode
                provincename = scene.provincename
                citycode = scene.citycode
                cityname = scene.cityname
                districtcode = scene.districtcode
                districtname = scene.districtname
                towncode = scene.towncode
                townname = scene.townname
                scensename = scene.name
                scenseaddress = scene.location
                evaluatetime = Date()
                evaluatorguid = "admin"
                evaluatorusername = "admin"
                evaluatorrealname = "admin"
                resultscorebef = (totalScore - abs(total)).toString()
                createdate = Date()
                updatedate = Date()
            }
        }
        //子项具体得分
        val itemevaluationList = mutableListOf<Itemevaluation>()
        topItems.forEach { subRule ->
            val item = newItemEvaluation(info, subRule, inspection)
            itemevaluationList.add(item)
        }
        rules.forEach { p ->
            if (p.first.ertype != 2) {
                val item = newItemEvaluation(info, p.first, inspection)
                itemevaluationList.add(item)
            }
            p.second.forEach { r ->
                val item1 = newItemEvaluation(info, r, inspection)
                itemevaluationList.add(item1)
            }
        }
        return Pair(evaluation, itemevaluationList)
    }
 
    /**
     * 将评分记录输出至数据库
     */
    private fun toDb(info: Info, p: Pair<Evaluation, List<Itemevaluation>>) {
        //去除已有记录
        evaluationMapper.deleteByExample(Example(Evaluation::class.java).apply {
            createCriteria().andEqualTo("stguid", info.subTask?.stguid)
        })
        itemevaluationMapper.deleteByExample(Example(Itemevaluation::class.java).apply {
            createCriteria().andEqualTo("stguid", info.subTask?.stguid)
        })
 
        //写入数据库
        evaluationMapper.insert(p.first)
        p.second.forEach { il -> itemevaluationMapper.insert(il) }
    }
 
    /**
     * 转换一条评分至excel中的一行
     */
    private fun addToFile(contents: MutableList<Array<Any>>, info: Info, evaluations: Evaluation) {
        val cList = mutableListOf<Any>()
        // FIXME: 2021/4/28 用户名是否添加账号
//        cList.add("${info.userName}\t${info.userId}")
        cList.add(info.sceneIndex ?: -99)
        cList.add("")
        cList.add("${info.sceneName}")
        //每一项具体得分
        topItems.forEach {
            for (r in rules) {
                if (r.first.fatherid == it.guid || r.first.guid == it.guid) {
                    // FIXME: 2021/4/25 决定是否写h3
                    if (hasHead3) {
                        r.second.forEach { s ->
                            cList.add(s.extension1?.toInt() ?: "")
                        }
                    } else {
                        cList.add(r.first.extension1?.toInt() ?: "")
                    }
                }
            }
        }
        //总分和环信码
        evaluations.let {
            cList.add(it.resultscorebef?.toDoubleOrNull() ?: .0)
            val code = when (it.resultscorebef?.toIntOrNull() ?: 0) {
                in 0..59 -> ExcelUtil.MyCell("不规范", fontColor = HSSFColor.HSSFColorPredefined.RED.index)
                in 60..89 -> ExcelUtil.MyCell("基本规范", fontColor = HSSFColor.HSSFColorPredefined.GOLD.index)
                in 90..100 -> ExcelUtil.MyCell("规范", fontColor = HSSFColor.HSSFColorPredefined.BRIGHT_GREEN.index)
                else -> ExcelUtil.MyCell("超出范围:${it.resultscoreaft}", fontColor = HSSFColor.HSSFColorPredefined.BLACK.index)
            }
            cList.add(code)
        }
        contents.add(cList.toTypedArray())
    }
 
    /**
     * 将评分记录输出为excel
     */
    private fun toFile() {
        val contents = mutableListOf<Array<Any>>()
 
        val h1 = mutableListOf<ExcelUtil.MyCell>()
        h1.add(ExcelUtil.MyCell("表单编号", if (hasHead3) 3 else 2))
        h1.add(ExcelUtil.MyCell("唯一序号", if (hasHead3) 3 else 2))
        h1.add(ExcelUtil.MyCell("场景名称", if (hasHead3) 3 else 2))
        val h2 = mutableListOf<ExcelUtil.MyCell>()
        h2.add(ExcelUtil.MyCell(""))
        h2.add(ExcelUtil.MyCell(""))
        h2.add(ExcelUtil.MyCell(""))
        val h3 = mutableListOf<String>()
        h3.add("")
        h3.add("")
        h3.add("")
        topItems.forEach {
            h1.add(ExcelUtil.MyCell(it.itemname ?: "", 1, 0))
            for (r in rules) {
                if (r.first.fatherid == it.guid || r.first.guid == it.guid) {
                    h2.add(ExcelUtil.MyCell(r.first.itemname ?: "", 1, 0))
                    // FIXME: 2021/4/25 决定是否写h3
                    if (hasHead3) {
                        r.second.forEach { s ->
                            h3.add(s.itemname ?: "")
                            h2.last().colSpan++
                            h1.last().colSpan++
                        }
                    } else {
                        h2.last().colSpan++
                        h1.last().colSpan++
                    }
                }
            }
        }
        // 决定是否写h3
        if (hasHead3) {
            h1.add(ExcelUtil.MyCell("总分", 3, 1))
            h1.add(ExcelUtil.MyCell("防治规范性", 3, 1))
        } else {
            h1.add(ExcelUtil.MyCell("总分", 2, 1))
            h1.add(ExcelUtil.MyCell("防治规范性", 2, 1))
        }
 
        contents.add(h1.toTypedArray())
        contents.add(h2.toTypedArray())
        // 决定是否写h3
        if (hasHead3) {
            contents.add(h3.toTypedArray())
        }
 
        rows.sortBy { it[0] as Int }
        contents.addAll(rows)
 
        // 写入文档
        val fileName = "${sceneType.text}自动评分-${DateUtil().DateToString(Date(), "yyyy-MM-ddhhmmss")}.xls"
        val filePath = "C:\\work\\工作\\第三方监管\\自动评分\\${sceneType.text}\\$fileName"
        val file = File(filePath)
        if (!file.parentFile.exists()) {
            file.parentFile.mkdirs()
        }
        val out = FileOutputStream(File(filePath))
        ExcelUtil.write(emptyList(), contents, workbook)
        workbook.write(out)
        workbook.close()
        out.flush()
        out.close()
    }
 
    /**
     * 获取评分规则
     */
    private fun getScoreItem() {
        this.rules.clear()
        baseRules.clear()
        topItems.clear()
 
        val rule = evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
            createCriteria()
                .andEqualTo("tasktypeid", 99)
                .andEqualTo("scensetypeid", sceneType.value.toByte())
        })
        if (rule.isNotEmpty()) {
            baseRules.addAll(rule)
 
            val ruleId = rule[0].guid
            val rules = evaluationsubruleMapper.selectByExample(Example(Evaluationsubrule2::class.java).apply {
                createCriteria().andEqualTo("erguid", ruleId)
            })
            rules.forEach {
                if (it.ertype == 2) {
                    topItems.add(it)
                }
            }
            topItems.sortBy { it.displayid }
 
            var t = 0
            topItems.forEach {
                t += it.maxscore ?: 0
                val tempRules = mutableListOf<Evaluationsubrule2>()
                for (i in rules) {
                    if (i.fatherid == it.guid && i.ertype == 3) {
                        tempRules.add(i)
                    }
                }
                //评分大项如果没有找到评分小项,则说明其直接对应最小评分项,其本身变成评分项
                if (tempRules.isEmpty()) {
                    tempRules.add(it)
                }
                tempRules.sortBy { t-> t.displayid }
                tempRules.forEach {temp ->
                    val tempSubRules = mutableListOf<Evaluationsubrule2>()
                    for (i in rules) {
                        if (i.fatherid == temp.guid && i.ertype == 4) {
                            tempSubRules.add(i)
                        }
                    }
                    tempSubRules.sortBy {ts-> ts.displayid }
                    this.rules.add(Pair(temp, tempSubRules))
                }
            }
            this.totalScore = t
        }
    }
 
    /**
     * 生成新的一条评分记录
     */
    private fun newItemEvaluation(info: Info, itemRule: Evaluationsubrule2, inspection: Inspection?) = Itemevaluation()
        .apply {
            var rule: Evaluationrule? = null
            for (r in baseRules) {
                if (r.guid == itemRule.erguid) {
                    rule = r
                    break
                }
            }
            ieguid = UUIDGenerator.generate16ShortUUID()
            iguid = inspection?.guid
            stguid = info.subTask?.stguid
            sguid = info.subTask?.scenseid
            sensename = info.subTask?.scensename
            erguid = rule?.guid
            rulename = rule?.rulename
            ruletype = rule?.ruletype?.toInt()
            ertype = itemRule.ertype
            esrguid = itemRule.guid
            name = itemRule.itemname
            value = itemRule.extension1 ?: "0"
            extension1 = (itemRule.extension1 != null).toString()
        }
}