riku
2022-06-17 3a5c011d9509d3bc0367921f463676c81ff2e374
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
package cn.flightfeather.supervision.lightshare.service.impl
 
import cn.flightfeather.supervision.domain.ds1.entity.Problemlist
import cn.flightfeather.supervision.domain.ds1.entity.Subtask
import cn.flightfeather.supervision.domain.ds1.entity.Task
import cn.flightfeather.supervision.domain.ds1.mapper.ProblemlistMapper
import cn.flightfeather.supervision.domain.ds1.mapper.SubtaskMapper
import cn.flightfeather.supervision.domain.ds1.mapper.TaskMapper
import cn.flightfeather.supervision.common.utils.Constant
import cn.flightfeather.supervision.common.utils.DateUtil
import cn.flightfeather.supervision.lightshare.service.EvaluationService
import cn.flightfeather.supervision.lightshare.service.SubtaskService
import cn.flightfeather.supervision.lightshare.service.TaskService
import cn.flightfeather.supervision.lightshare.service.UserinfoService
import cn.flightfeather.supervision.lightshare.vo.*
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import tk.mybatis.mapper.entity.Example
import java.util.*
import kotlin.collections.ArrayList
 
@Service
class TaskServiceImpl(val taskMapper: TaskMapper) : TaskService {
 
    @Autowired
    lateinit var subtaskService: SubtaskService
 
    @Autowired
    lateinit var subtaskMapper: SubtaskMapper
 
    @Autowired
    lateinit var problemListMapper: ProblemlistMapper
 
    @Autowired
    lateinit var userinfoMapper: UserinfoService
 
    @Autowired
    lateinit var evaluationService: EvaluationService
 
    //获取某顶层任务下某场景的街镇排名和场景排名
    override fun getRank(topTaskId: String, sceneTypeId: String, sceneId: String?): RankVo {
        val rankVo = RankVo()
        var taskId = topTaskId
//        if (sceneId != null) {
//            taskId = evaluationService.getTopTaskByScene(sceneId)?: topTaskId
//        }
        val mapSceneRank = taskMapper.selectSceneRank(taskId, sceneTypeId)
        val mapTownRank = taskMapper.selectTownRank(taskId, sceneTypeId)
        val sceneRanks = mutableListOf<RankVo.SceneRank>()
        val townRanks = mutableListOf<RankVo.TownRank>()
        mapSceneRank.forEach {
            if (!it.isEmpty()) {
                val sceneRank = RankVo.SceneRank()
                sceneRank.sceneTypeId = it.get("sceneTypeId").toString()
                sceneRank.sceneTypeName = it.get("sceneTypeName").toString()
                sceneRank.sceneNameId = it.get("sceneNameId").toString()
                sceneRank.sceneName = it.get("sceneName").toString()
                val tmpScoreAft = if (it.get("scoreAft") == null) "" else it.get("scoreAft").toString()
                val tmpScoreBef = if (it.get("scoreBef") == null) "" else it.get("scoreBef").toString()
                if (tmpScoreAft.isBlank() && !tmpScoreBef.isBlank()) {
                    sceneRank.score = it.get("scoreBef").toString().toInt()
                } else if (!tmpScoreAft.isBlank()) {
                    sceneRank.score = it.get("scoreAft").toString().toInt()
                }
                //2018.12.27 by riku 当前规范等级结果记录放弃不用,通过分数来得出规范等级
//                if (it["standardAft"] == null) {
//                    sceneRankVo.standard = it["standardBef"].toString()
//                } else {
//                    sceneRankVo.standard = it["standardAft"].toString()
//                }
                if (sceneRank.score >= 100) {
                    sceneRank.standard = "规范"
                    sceneRank.standardOrder = 1
                } else if (sceneRank.score in 78..99) {
                    sceneRank.standard = "基本规范"
                    sceneRank.standardOrder = 2
                } else if (sceneRank.score in 54..77) {
                    sceneRank.standard = "不规范"
                    sceneRank.standardOrder = 3
                } else if (sceneRank.score in 0..53) {
                    sceneRank.standard = "严重不规范"
                    sceneRank.standardOrder = 4
                }
                sceneRanks.add(sceneRank)
            }
        }
        sceneRanks.sortWith(kotlin.Comparator { o1, o2 -> o2.score - o1.score })
        mapTownRank.forEach {
            if (!it.isEmpty()) {
                val townRank = RankVo.TownRank()
                townRank.sceneTypeId = it.get("sceneTypeId").toString()
                townRank.sceneTypeName = it.get("sceneTypeName").toString()
                townRank.townCode = it.get("townCode").toString()
                townRank.townName = it.get("townName").toString()
                try {
                    townRank.averageScore = it.get("averageScore").toString().toFloat().toInt()
                } catch (e: Exception) {
                }
                try {
                    townRank.standardRate = it.get("standardRate").toString().toFloat()
                } catch (e: Exception) {
                }
                val s =it.get("hasScoredNum").toString()
                try {
                    townRank.hasScoredNum = it.get("hasScoredNum").toString().toInt()
                } catch (e: Exception) {
                }
                try {
                    townRank.totalSceneNum = it.get("totalSceneNum").toString().toInt()
                } catch (e: Exception) {
                }
                townRanks.add(townRank)
            }
        }
        townRanks.sortWith(kotlin.Comparator { o1, o2 -> o2.averageScore - o1.averageScore })
        rankVo.sceneRanks = sceneRanks
        rankVo.townRanks = townRanks
 
        val taskVo = findByID(taskId)
        rankVo.topTaskId = taskId
        rankVo.topTaskName = taskVo.name
 
        return rankVo
    }
 
    //获取某顶层任务下各场景的任务总频次及完成点次
    override fun getFrequency(topTaskId: String): TaskFrequencyVo {
        val taskFrequencyVo = TaskFrequencyVo()
        val frequencyInfos = mutableListOf<TaskFrequencyVo.FrequencyInfo>()
 
        val map1 = taskMapper.selectTotalFrequency(topTaskId)
        taskFrequencyVo.topTaskId = map1[0].get("topTaskId").toString()
        taskFrequencyVo.topTaskName = map1[0].get("topTaskName").toString()
 
        val map2 = taskMapper.selectClearFrequency(topTaskId)
 
        for (i in map1.indices) {
            val frequencyVo = TaskFrequencyVo.FrequencyInfo()
            frequencyVo.sceneTypeId = map1[i].get("sceneTypeId").toString()
            frequencyVo.sceneTypeName = map1[i].get("sceneTypeName").toString()
            try {
                frequencyVo.totalFrequency = map1[i].get("totalFrequency").toString().toInt()
            } catch (e: Exception) {
            }
            try {
                frequencyVo.clearFrequency = map2[i].get("clearFrequency").toString().toInt()
            } catch (e: Exception) {
            }
            frequencyInfos.add(frequencyVo)
        }
 
        taskFrequencyVo.frequencyInfos = frequencyInfos
        return taskFrequencyVo
    }
 
    //根据type获取不同形式的顶层任务和日任务
    override fun getAllbyCondition(type: Int): List<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        //获取所有顶层任务
        if (type == 0)
            return getAllTop()
        //获取未完成顶层任务及对应日任务列表
        else if (type == 1){
            val tmp = getAllTop()
            tmp.forEach {
                if (it.runingstatus != Constant.TaskProgress.RUNINGSTATUS3.text) {
                    it.daytaskList = getDayTaskByTaskID(it.tguid!!)
                    taskVoList.add(it)
                }
            }
        }
 
        return taskVoList
    }
 
    //根据日期获取日任务
    override fun findByDate(date: String): TaskVo {
        val taskVo = TaskVo()
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        //gsguid不为空为日任务,日任务开始时间和结束时间在同一天,过滤开始时间就ok
        criteria.andEqualTo("starttime", dateUtil.StringToDate(date.substring(0, 10)))
        criteria.andIsNotNull("tsguid")
        val tasklist = taskMapper.selectByExample(example)
        if (tasklist.isNotEmpty()) {
            BeanUtils.copyProperties(tasklist[0], taskVo)
        }
        return taskVo
    }
 
    //根据顶层任务id获取日任务
    override fun getDayTaskByTaskID(taskid: String): List<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        criteria.andEqualTo("tsguid", taskid)
        example.orderBy("starttime").asc()
        val tasklist = taskMapper.selectByExample(example)
        if (!tasklist.isEmpty()) {
            tasklist.forEach {
                val taskVo = TaskVo()
                BeanUtils.copyProperties(it, taskVo)
                taskVoList.add(taskVo)
            }
        }
        return taskVoList
    }
 
    override fun getAllTop(): List<TaskVo> {
        return findTopTask()
    }
 
    //根据区县获取顶层任务,并按时间降序排列
    override fun getByDistrictCode(districtCode: String, date: Date): List<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        val example = Example(Task::class.java)
//        val criteria = example.createCriteria()
//        criteria.andIsNull("tsguid")
//                .andEqualTo("districtcode", districtCode)
//                .andLessThanOrEqualTo("endtime", date)
//        example.or(
                example.createCriteria().andIsNull("tsguid")
                        .andEqualTo("districtcode", districtCode)
                        .andLessThan("starttime", date)
                        .andGreaterThanOrEqualTo("endtime", date)
//        )
        example.orderBy("starttime").desc()
        val tasklist = taskMapper.selectByExample(example)
        if (!tasklist.isEmpty()) {
            tasklist.forEach {
                val taskVo = TaskVo()
                BeanUtils.copyProperties(it, taskVo)
                taskVoList.add(taskVo)
            }
        }
        return taskVoList
    }
 
    //获取所有顶层任务
    override fun findTopTask(): List<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        criteria.andIsNull("tsguid")
        example.orderBy("starttime").desc()
        val tasklist = taskMapper.selectByExample(example)
        if (!tasklist.isEmpty()) {
            tasklist.forEach {
                val taskVo = TaskVo()
                BeanUtils.copyProperties(it, taskVo)
                taskVoList.add(taskVo)
            }
        }
        return taskVoList
    }
 
    //根据名称获取任务
    override fun findByName(name: String): TaskVo {
        val taskVo = TaskVo()
        val task = Task()
        task.name = name
        val taskre = taskMapper.selectOne(task)
        if (taskre != null) {
            BeanUtils.copyProperties(taskre, taskVo)
        }
        return taskVo
    }
 
    //根据顶层任务ID查询上一次任务
    override fun findLastTask(task: Task): Task {
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        //根据地址相信,任务类型判断
        criteria.andEqualTo("citycode", task.citycode)
        criteria.andEqualTo("districtcode", task.districtcode)
        criteria.andEqualTo("towncode", task.towncode)
        criteria.andEqualTo("provincecode", task.provincecode)
        criteria.andEqualTo("typeno", task.typeno)
        criteria.andNotEqualTo("tguid", task.tguid)
        criteria.andIsNull("tsguid")
        //根据时间排序
        example.orderByClause = "T_SetTime desc"
        val tasks = taskMapper.selectByExample(example)
        //有数据就获取第一条数据,没有就返回新对象
        return if (tasks.isEmpty()) Task() else tasks[0]
    }
 
    val dateUtil = DateUtil()
 
    //根据顶层列表,日期,和执行人员ID,用户类型获取日任务
    override fun getDayTaskList(taskVoList: List<TaskVo>, date: String, guid: String, userType: String): List<TaskVo> {
        if (taskVoList.isEmpty()) return taskVoList
        taskVoList.forEach {
            val example = Example(Task::class.java)
            val criteria = example.createCriteria()
            //构造查询条件
            criteria.andEqualTo("tsguid", it.tguid)
            val dateTemo = dateUtil.StringToDate(date)
            //条件过滤
            criteria.andBetween("starttime", dateTemo, dateUtil.addSecond(dateUtil.addMonth(dateTemo!!, 1)!!, 1))
            if (userType == "1") {
                criteria.andLike("executorguids", "%$guid%")
            }
            //根据sql条件查询
            val taskList = taskMapper.selectByExample(example)
            val taskVoList1 = mutableListOf<TaskVo>()
            taskList.forEach {
                val taskVo = TaskVo()
                BeanUtils.copyProperties(it, taskVo)
                taskVoList1.add(taskVo)
            }
            it.daytaskList = taskVoList1
        }
        return taskVoList
    }
 
    override fun getDayTask(taskId: String, userId: String, userType: String): List<DayTaskProgressVo> {
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        //构造查询条件
        criteria.andEqualTo("tsguid", taskId)
        if (userType == "1") {
            criteria.andLike("executorguids", "%$userId%")
        }
 
        val resultList = ArrayList<DayTaskProgressVo>()
 
        //根据sql条件查询
        taskMapper.selectByExample(example).forEach {
            val exampleTotal = Example(Subtask::class.java).apply {
                createCriteria().andEqualTo("tsguid", it.tguid)
            }
 
            val total = subtaskMapper.selectCountByExample(exampleTotal)
 
            val exampleComplete = exampleTotal.apply {
                and().andEqualTo("status", Constant.TaskProgress.RUNINGSTATUS3.text)
            }
            val complete = subtaskMapper.selectCountByExample(exampleComplete)
 
            var changed = 0
            problemListMapper.findUnchangedCount(it.tguid ?: "").forEach {i ->
                //结果表示该子任务未整改问题数
                if (i == 0) {
                    changed++
                }
            }
 
            //审核是否完成
            var check = false
            with(subtaskMapper.selectByExample(exampleTotal)) breaking@{
                forEach {
                    problemListMapper.selectByExample(Example(Problemlist::class.java).apply {
                        createCriteria().andEqualTo("stguid", it.stguid)
                    }).forEach {problem ->
                        if (problem.extension3 == Constant.PROBLEM_UNCHECKED) {
                            check = true
                            return@breaking
                        }
                    }
                }
            }
 
           resultList.add(DayTaskProgressVo(
                    it.tguid, it.starttime, taskId, complete, changed, total, check
            ))
        }
 
        return resultList
    }
 
    //根据顶层列表,日期,和执行人员ID获取日任务
    override fun getDayTaskList(taskVoList: List<TaskVo>, date: String, guid: String): List<TaskVo> {
        if (taskVoList.isEmpty()) return taskVoList
        taskVoList.forEach {
            val example = Example(Task::class.java)
            val criteria = example.createCriteria()
            //构造查询条件
            criteria.andEqualTo("tsguid", it.tguid)
            val dateTemo = dateUtil.StringToDate(date)
            //条件过滤
            criteria.andBetween("starttime", dateTemo, dateUtil.addSecond(dateUtil.addMonth(dateTemo!!, 1)!!, 1))
            criteria.andLike("executorguids", "%$guid%")
            //根据sql条件查询
            val taskList = taskMapper.selectByExample(example)
            val taskVoList1 = mutableListOf<TaskVo>()
            taskList.forEach {
                val taskVo = TaskVo()
                BeanUtils.copyProperties(it, taskVo)
                taskVoList1.add(taskVo)
            }
            it.daytaskList = taskVoList1
        }
        return taskVoList
    }
 
    override fun getMonthTaskList(date: String, guid: String): List<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        //参数检查
        if (date.length < 7) {
            return taskVoList
        }
        val startDate = DateUtil().StringToDate(date.substring(0, 7)) ?: return taskVoList
        //查询一个月任务
        var endDate = DateUtil().addMonth(startDate, 1) ?: return taskVoList
        endDate = DateUtil().addSecond(endDate, -1)!!
        //构造查询条件
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        //添加日期过滤
 
        //T_StartTime>='2018-1-1 0:00:00.0' AND T_StartTime<'2018-2-1 0:00:00.0'
        //T_EndTime>='2018-1-1 0:00:00.0' AND T_EndTime<'2018-2-1 0:00:00.0'
        criteria.andBetween("starttime", startDate, endDate).andIsNull("tsguid").andLike("executorguids", "%$guid%")
        example.or(
            example.createCriteria().orBetween(
                "endtime",
                startDate,
                endDate
            ).andIsNull("tsguid").andLike("executorguids", "%$guid%")
        )
        example.or(
            example.createCriteria().orLessThan("starttime", startDate).andGreaterThan(
                "endtime",
                endDate
            ).andIsNull("tsguid").andLike("executorguids", "%$guid%")
        )
        //criteria.orLessThan("starttime",startDate).andGreaterThan("endtime",endDate)
        //添加人员id过滤
//        if (StringUtils.hasText(guid)) {
//            criteria.andLike("executorguids", "%$guid%")
//        }
//        criteria.andIsNull("tsGuid")
//        example.and()
        //根据sql条件查询
        //example.and(criteria1)
 
        val taskList = taskMapper.selectByExample(example)
        //entity转vo
        taskList.forEach {
            val taskVo = TaskVo()
            BeanUtils.copyProperties(it, taskVo)
            taskVoList.add(taskVo)
        }
        return taskVoList
    }
 
    override fun getMonthTaskList(date: String, guid: String, userType: String): List<TaskVo> {
//        val taskVoList = mutableListOf<TaskVo>()
//        //条件不足就返回
//        if (date.length < 7) {
//            return taskVoList
//        }
//        //时间转换
//        val d1 = DateUtil().StringToDate(date.substring(0, 7)) ?: return taskVoList
//        var startDate: Date? = null
//        var endDate: Date? = null
//        //根据type类型,得到要查询的范围
//        when (type) {
//            "Middle" -> {
//                startDate = DateUtil().addMonth(d1, -1);endDate = DateUtil().addMonth(d1, 2)
//            }
//            "Left" -> {
//                startDate = DateUtil().addMonth(d1, -3);endDate = d1
//            }
//            "Right" -> {
//                startDate = DateUtil().addMonth(d1, 1);endDate = DateUtil().addMonth(d1, 4)
//            }
//            else -> {
//                startDate = d1;endDate = DateUtil().addMonth(d1, 1)
//            }
//        }
//
//        //构造查询条件
//        val example = Example(Task::class.java)
//        val criteria = example.createCriteria()
//        //添加日期过滤
//        criteria.andBetween("starttime", startDate, endDate)
//        criteria.andIsNull("tsguid")
//        //criteria.orBetween()
//        //添加人员id过滤
//        if (StringUtils.hasText(guid)) {
//            criteria.andLike("executorguids", guid)
//        }
//        //根据sql条件查询
//        val taskList = taskMapper.selectByExample(example)
//        //entity转vo
//        taskList.forEach {
//            val taskVo = TaskVo()
//            BeanUtils.copyProperties(it, taskVo)
//            taskVoList.add(taskVo)
//        }
//        return taskVoList
        val taskVoList = mutableListOf<TaskVo>()
        //参数检查
        if (date.length < 7) {
            return taskVoList
        }
        val startDate = DateUtil().StringToDate(date.substring(0, 7)) ?: return taskVoList
        //查询一个月任务
        var endDate = DateUtil().addMonth(startDate, 1) ?: return taskVoList
        endDate = DateUtil().addSecond(endDate, -1)!!
        //构造查询条件
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        //获取用户信息
        val userInfo = userinfoMapper.findOne(guid)
        val districtCode = userInfo.dGuid
 
        //添加日期过滤
 
        //T_StartTime>='2018-1-1 0:00:00.0' AND T_StartTime<'2018-2-1 0:00:00.0'
        //T_EndTime>='2018-1-1 0:00:00.0' AND T_EndTime<'2018-2-1 0:00:00.0'
        criteria.andBetween("starttime", startDate, endDate).andIsNull("tsguid");
        if (userType == "1") {
            criteria.andLike("executorguids", "%$guid%")
        } else if (userType == "2") {
            criteria.andEqualTo("districtcode", districtCode)
        }
 
        val criteria2 = example.createCriteria()
        criteria2.orBetween(
                "endtime",
                startDate,
                endDate
        ).andIsNull("tsguid");
        if (userType == "1") {
            criteria2.andLike("executorguids", "%$guid%")
        } else if (userType == "2"){
            criteria2.andEqualTo("districtcode", districtCode)
        }
        example.or(criteria2)
 
        val criteria3 = example.createCriteria()
        criteria3.orLessThan("starttime", startDate).andGreaterThan(
                "endtime",
                endDate
        ).andIsNull("tsguid");
        if (userType == "1") {
            criteria3.andLike("executorguids", "%$guid%")
        } else if (userType == "2"){
            criteria3.andEqualTo("districtcode", districtCode)
        }
        example.or(criteria3)
        //criteria.orLessThan("starttime",startDate).andGreaterThan("endtime",endDate)
        //添加人员id过滤
//        if (StringUtils.hasText(guid)) {
//            criteria.andLike("executorguids", "%$guid%")
//        }
//        criteria.andIsNull("tsGuid")
//        example.and()
        //根据sql条件查询
        //example.and(criteria1)
 
        val taskList = taskMapper.selectByExample(example)
        //entity转vo
        taskList.forEach {
            val taskVo = TaskVo()
            BeanUtils.copyProperties(it, taskVo)
            taskVoList.add(taskVo)
        }
        return taskVoList
    }
 
    override fun find(task: Task): List<Task> = taskMapper.select(task)
 
    //根据ID查询
    override fun findByID(id: String): TaskVo {
        val taskVo = TaskVo()
        val task = taskMapper.selectByPrimaryKey(id)
        if (task != null) {
            BeanUtils.copyProperties(task, taskVo)
        }
        return taskVo
    }
 
    //获取全部
    override fun findAll(): MutableList<TaskVo> {
        val taskVoList = mutableListOf<TaskVo>()
        val taskList = taskMapper.selectAll()
        taskList.forEach {
            val taskVo = TaskVo()
            BeanUtils.copyProperties(it, taskVo)
            taskVoList.add(taskVo)
        }
        return taskVoList
    }
    
    override fun save(task: Task): Int {
        // FIXME: 2021/10/9 按照当前的逻辑,此函数主要用于新建顶层任务以及日任务,但是日任务内容的生成逻辑目前由前端app完成,因此会出现一个bug:
        // FIXME: 2021/10/9 当前端多个用户同时在同一个顶层任务下的新的一天创建任务时,会出现同一天有多个日任务,此时前端后续查看只能看到其中一个日任务下的子任务
        // FIXME: 2021/10/9 因此在此处添加一个临时的判断,用于合并同一顶层任务下同一天内的多个日任务
        // FIXME: 2021/10/9 另外对于顶层任务也添加类似逻辑,由于顶层任务的任务名称默认系统自动生成,因此暂时只判断同名的顶层任务,当存在同名顶层任务时,不做保存操作
 
        var result = 0
        // 1、首先判断是顶层任务还是日任务
        if (task.levelnum == 2) {
            //2.1、 是顶层任务时,判断是否已有同名任务
            val r = taskMapper.selectCountByExample(Example(Task::class.java).apply {
                createCriteria().andEqualTo("levelnum", task.levelnum)
                    .andEqualTo("name", task.name)
            })
            //2.2、 如果没有同名任务,则插入
            if (r == 0) {
                result = taskMapper.insert(task)
            }
        } else {
            //3.1、 当是日任务时,判断在同一个顶层任务下,是否有同名的日任务
            val r  =taskMapper.selectByExample(Example(Task::class.java).apply {
                createCriteria().andEqualTo("tsguid", task.tsguid)
                    .andEqualTo("name", task.name)
            })
            if (r.size > 0) {
                //3.2、 当存在同名日任务时,需要将当前日任务下属的所有子任务修改至已有同名日任务下,并舍弃当前上传的日任务
                //      同时,由于目前的任务内容生成逻辑在前端完成,因此为了保证下属的子任务已经入库,此处新建一个线程延时执行
                Thread {
                    Thread.sleep(3000)
                    val dayTask = r[0]
                    val subTasks = subtaskMapper.selectByExample(Example(Subtask::class.java).apply {
                        createCriteria().andEqualTo("tsguid", task.tguid)
                    })
                    subTasks.forEach {
                        it.tsguid = dayTask.tguid
                        subtaskMapper.updateByPrimaryKey(it)
                    }
                }.start()
            } else {
                //3.3、 当没有同名日任务时,直接插入
                result = taskMapper.insert(task)
            }
        }
        return result
    }
 
    //修改日任务信息,若有子任务,子任务也修改
    override fun update(task: Task): Int {
        var re = 1
        taskMapper.updateByPrimaryKeySelective(task)
        val subtasks = subtaskService.findByDayTaskID(task.tguid!!)
        if (subtasks.isNotEmpty()) {
            re += subtasks.size
            subtasks.forEach {
                val subtask = Subtask()
                BeanUtils.copyProperties(it, subtask)
                subtask.planstarttime = task.starttime
                subtask.planendtime = task.endtime
                subtaskService.update(subtask)
            }
        }
        return re
    }
 
    override fun delete(id: String) = taskMapper.deleteByPrimaryKey(id)
 
    //获取所有未完成的顶层任务的完成情况
    override fun getTaskProgress(userid: String): List<TaskVo> {
        val taskProgressVolist = mutableListOf<TaskVo>()
        val regex: Regex = userid.toRegex()
        val example = Example(Task::class.java)
        val criteria = example.createCriteria()
        criteria.orEqualTo("runingstatus", Constant.TaskProgress.RUNINGSTATUS1.text)
        criteria.orEqualTo("runingstatus", Constant.TaskProgress.RUNINGSTATUS2.text)
        criteria.andIsNull("tsguid")
        example.orderBy("starttime").asc()
        val result = taskMapper.selectByExample(example)
        if (result.isNotEmpty()){
            result.forEach {
                var mytotalcount = 0
                var mycompletecount = 0
                if (it.tsguid == null) {
                    val subtaskVo: List<SubtaskVo> = subtaskService.findByTaskID(it.tguid!!)
                    var completecount = 0
                    subtaskVo.forEach {
                        if (it.executorguids!!.contains(regex)) {
                            mytotalcount++
                            if (Objects.equals(it.status!!, Constant.TaskProgress.RUNINGSTATUS3.text))
                                mycompletecount++
                        }
                        if (Objects.equals(it.status!!, Constant.TaskProgress.RUNINGSTATUS3.text))
                            completecount++
                    }
                    val taskProgressVo = TaskVo()
                    BeanUtils.copyProperties(it, taskProgressVo)
                    taskProgressVo.tguid = it.tguid
                    taskProgressVo.name = it.name
                    taskProgressVo.levelnum = it.levelnum
                    taskProgressVo.totaltask = subtaskVo.size
                    taskProgressVo.completetask = completecount
                    taskProgressVo.mytotaltask = mytotalcount
                    taskProgressVo.mycompletetask = mycompletecount
                    val daytaskVolist = getDayTaskByTaskID(it.tguid!!)
                    val daytasklist = mutableListOf<TaskVo>()
                    if (daytaskVolist.isNotEmpty()){
                        daytaskVolist.forEach {
                            var mytotalcount1 = 0
                            var mycompletecount1 = 0
                            val subtaskVolist = subtaskService.findByDayTaskID(it.tguid!!)
                            var completecount1 = 0
                            subtaskVolist.forEach {
                                if (it.executorguids!!.contains(regex)) {
                                    mytotalcount1++
                                    if (Objects.equals(it.status!!, Constant.TaskProgress.RUNINGSTATUS3.text))
                                        mycompletecount1++
                                }
                                if(Objects.equals(it.status, Constant.TaskProgress.RUNINGSTATUS3.text))
                                    completecount1++
                            }
                            val daytaskProgressVo = TaskVo()
                            BeanUtils.copyProperties(it, daytaskProgressVo)
                            daytaskProgressVo.tguid = it.tguid
                            daytaskProgressVo.name = it.name
                            daytaskProgressVo.totaltask = subtaskVolist.size
                            daytaskProgressVo.completetask = completecount1
                            daytaskProgressVo.mytotaltask = mytotalcount1
                            daytaskProgressVo.mycompletetask = mycompletecount1
                            daytasklist.add(daytaskProgressVo)
                        }
                    }
                    taskProgressVo.daytaskList = daytasklist
                    taskProgressVolist.add(taskProgressVo)
                }
            }
        }
        return taskProgressVolist
    }
 
}