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
package cn.flightfeather.supervision.lightshare.service.Impl
 
import cn.flightfeather.supervision.domain.entity.LedgerMediaFile
import cn.flightfeather.supervision.domain.entity.LedgerRecord
import cn.flightfeather.supervision.domain.entity.LedgerSubType
import cn.flightfeather.supervision.domain.enumeration.SceneType
import cn.flightfeather.supervision.domain.mapper.LedgerMediaFileMapper
import cn.flightfeather.supervision.domain.mapper.LedgerRecordMapper
import cn.flightfeather.supervision.domain.mapper.LedgerSubTypeMapper
import cn.flightfeather.supervision.domain.mapper.UserinfoMapper
import cn.flightfeather.supervision.domain.repository.LedgerMediaFileRep
import cn.flightfeather.supervision.domain.repository.LedgerRep
import cn.flightfeather.supervision.domain.repository.UserInfoRep
import cn.flightfeather.supervision.infrastructure.utils.DateUtil
import cn.flightfeather.supervision.infrastructure.utils.FileUtil
import cn.flightfeather.supervision.infrastructure.utils.UUIDGenerator
import cn.flightfeather.supervision.lightshare.service.LedgerService
import cn.flightfeather.supervision.lightshare.vo.*
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.pagehelper.PageHelper
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import tk.mybatis.mapper.entity.Example
import java.io.File
import java.io.FileNotFoundException
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.*
import javax.servlet.http.HttpServletResponse
import kotlin.collections.ArrayList
import kotlin.math.ceil
 
@Service
class LedgerServiceImpl(
    val ledgerSubTypeMapper: LedgerSubTypeMapper,
    val userinfoMapper: UserinfoMapper,
    val ledgerRecordMapper: LedgerRecordMapper,
    val ledgerMediaFileMapper: LedgerMediaFileMapper,
    private val ledgerMediaFileRep: LedgerMediaFileRep,
    private val userInfoRep: UserInfoRep,
    private val ledgerRep: LedgerRep,
) : LedgerService {
 
    @Value("\${imgPath}")
    lateinit var imgPath: String
 
    private val notInvolvedPath = "ledgerIcons/ledger_not_involved.jpg"
 
    override fun getLedgerType(sceneType: Int): ArrayList<LedgerSubTypeVo> {
        val ledgerSubTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            if (sceneType != SceneType.NoType.value) {
                createCriteria().andEqualTo("lScenetype", sceneType)
            }
        })
        val resultList = ArrayList<LedgerSubTypeVo>()
        ledgerSubTypes.forEach {
            val l = LedgerSubTypeVo(
                it.lsSubtypeid,
                it.lsName,
                it.getlTypeid(),
                it.getlTypename(),
                needUpdate = it.getlNeedupdate(),
                sceneType = it.getlScenetype(),
                iconUrl = it.getlIconurl()
            )
            resultList.add(l)
        }
        return resultList
    }
 
    override fun getUserLedgerSummary(userId: String, sceneType: Int, time: String): List<LedgerSubTypeVo> {
        val c = Calendar.getInstance().apply { this.time = DateUtil.StringToDate(time) }
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH) + 1
 
        val ledgerSubTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            if (sceneType != SceneType.NoType.value) {
                createCriteria().andEqualTo("lScenetype", sceneType)
            }
            orderBy("lTypeid")
        })
        val records = getLedgerRecords(userId, null, sceneType, time)
        val resultList = mutableListOf<LedgerSubTypeVo>()
        ledgerSubTypes.forEach {
            val l = LedgerSubTypeVo(
                it.lsSubtypeid,
                it.lsName,
                it.getlTypeid(),
                it.getlTypename(),
                needUpdate = it.getlNeedupdate(),
                sceneType = it.getlScenetype(),
                iconUrl = it.getlIconurl(),
                realTime = it.getlRealTime(),
                description = it.getlDescription(),
                notRelated = it.getlNotRelatedSwitch() ?: true,
                multigroup = it.getlMultiGroup() ?: false
            )
            for (r in records) {
                if (l.ledgerSubTypeId == r.lsSubtypeid) {
                    // FIXME: 2023/5/6 规则变动,但为了不影响之前的记录,时间为2023年4月及之前的不适用新规则
                    if (year >= 2023 && month > 4) {
                        if (r.lrExtension2 == "notInvolved" && r.lrYear <= year && r.lrMonth < month.toByte()) {
                            continue
                        }
                    }
                    l.ledgerFinished = true
                    l.upLoad = true
//                    l.checkStatus = r.lrVerifyrst?.toIntOrNull() ?: LedgerCheckStatus.UnCheck.value
                    l.onTime = r.lrIssubmitontime
                    l.verified
                    l.verifierName = r.lrVerifierrealname
                    l.verified = r.lrIsverify
                    l.verifyRst = r.lrVerifyrst
                    l.involved = r.lrExtension2 != "notInvolved"
                    break
                }
            }
            resultList.add(l)
        }
 
        return resultList
    }
 
    override fun getLedgerDetail(
        userId: String, ledgerSubTypeId: Int?, sceneType: Int,
        startTime: String, endTime: String,
        page: Int?, perPage: Int, response: HttpServletResponse,
    ): ArrayList<LedgerVo> {
        val result = ArrayList<LedgerVo>()
 
        response.setIntHeader("totalPage", 1)
        response.setIntHeader("currentPage", page ?: 1)
 
        //fixme 此处暂时强制为1页
        if (page != null && page > 1) {
            return result
        }
 
        val startDate = DateUtil.StringToDate(startTime)
        val endDate = DateUtil.StringToDate(endTime)
        val cal = Calendar.getInstance().apply { time = startDate }
        val year = cal.get(Calendar.YEAR)
        val month = cal.get(Calendar.MONTH) + 1
 
//        val records = ledgerRecordMapper.selectByUser(userId, year, month.toByte(), ledgerSubTypeId,
//                sceneType.toString(), page?.minus(1)?.times(perPage), perPage)
 
        val records = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
            createCriteria().andEqualTo("lrSubmitid", userId)
                .andEqualTo("lrYear", year)
                .andEqualTo("lrMonth", month.toByte())
                .apply {
                    ledgerSubTypeId?.let { andEqualTo("lsSubtypeid", it) }
                }
            if (sceneType == SceneType.Restaurant.value) {
                and(createCriteria().andIsNull("lrExtension1")
                    .orEqualTo("lrExtension1", sceneType.toString()))
            } else if (sceneType != SceneType.NoType.value) {
                and(createCriteria().andEqualTo("lrExtension1", sceneType.toString()))
            }
        })
 
        records.forEach {
            val media = ledgerMediaFileMapper.selectByExample(
                Example(LedgerMediaFile::class.java).apply {
                    createCriteria().andEqualTo("lrGuid", it.lrGuid)
                        .andEqualTo("mfIsdelete", false)
                        .andEqualTo("mfFiletype", it.lrEasubmitkind)
                    orderBy("mfSavetime").desc()
                }
            )
            val type = ledgerSubTypeMapper.selectByExample(
                Example(LedgerSubType::class.java).apply {
                    createCriteria().andEqualTo("lsSubtypeid", it.lsSubtypeid)
                }
            )
            result.add(LedgerVo().apply {
                id = it.lrGuid
                this.ledgerSubTypeId = it.lsSubtypeid
                ledgerName = it.lsSubtypename
                ledgerTypeId = type?.get(0)?.getlTypeid()
                ledgerType = type?.get(0)?.getlTypename()
                ledgerFinished = true
                isUpLoad = true
                updateDate = it.lrSubmitdate
                updateType = it.lrUpdatetype
                fileType = it.lrEasubmitkind.toInt()
                path1 = media?.get(0)?.mfPath1
                remark1 = media?.get(0)?.mfDescription1
                path2 = media?.get(0)?.mfPath2
                remark2 = media?.get(0)?.mfDescription2
                this.sceneType = if (it.lrExtension1 == null) SceneType.Restaurant.value else it.lrExtension1.toInt()
            })
        }
 
//        val counts = ledgerRecordMapper.selectCountByExample(Example(LedgerRecord::class.java))
//        val totalPage = Math.ceil(counts.toDouble() / perPage.toDouble()).toInt()
 
        return result
 
    }
 
    override fun getLedgerDetail2(
        userId: String,
        ledgerSubTypeId: Int?,
        sceneType: Int,
        time: String?,
    ): List<LedgerVo> {
        val records = if (time != null) {
            getLedgerRecords(userId, ledgerSubTypeId, sceneType, time)
        } else {
            // FIXME: 2022/10/13 暂时只支持ledgerSubTypeId不为null的情况
            if (ledgerSubTypeId == null) return emptyList()
            PageHelper.startPage<LedgerRecord>(1, 1)
            ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrSubmitid", userId)
                    .andEqualTo("lsSubtypeid", ledgerSubTypeId)
                orderBy("lrSubmitdate").desc()
            })
        }
        val result = ArrayList<LedgerVo>()
        records.forEach {
            val media = ledgerMediaFileMapper.selectByExample(
                Example(LedgerMediaFile::class.java).apply {
                    createCriteria().andEqualTo("lrGuid", it.lrGuid)
                        .andEqualTo("mfIsdelete", false)
                        .andEqualTo("mfFiletype", it.lrEasubmitkind)
                    orderBy("mfSavetime").desc()
                }
            )?.takeIf { it.isNotEmpty() }?.get(0)
            val type = ledgerSubTypeMapper.selectByExample(
                Example(LedgerSubType::class.java).apply {
                    createCriteria().andEqualTo("lsSubtypeid", it.lsSubtypeid)
                }
            )
            result.add(LedgerVo().apply {
 
                id = it.lrGuid
                this.ledgerSubTypeId = it.lsSubtypeid
                ledgerName = it.lsSubtypename
                ledgerTypeId = type?.get(0)?.getlTypeid()
                ledgerType = type?.get(0)?.getlTypename()
                ledgerFinished = true
                isUpLoad = true
                updateDate = it.lrSubmitdate
                updateType = it.lrUpdatetype
                fileType = it.lrEasubmitkind.toInt()
                path1 = media?.mfPath1
                remark1 = media?.mfDescription1
                path2 = media?.mfPath2
                remark2 = media?.mfDescription2
                this.sceneType = if (it.lrExtension1 == null) SceneType.Restaurant.value else it.lrExtension1.toInt()
            })
        }
        return result
    }
 
    override fun uploadLedger(userId: String, ledgerVo: LedgerVo, files: List<Pair<ByteArray, String>>): Boolean {
        val user = userInfoRep.getUser(userId)
 
        ledgerVo.apply {
            if (fileType == null) fileType = 1
            user?.extension2?.toInt()?.let { s -> sceneType = s }
        }
 
        val historyRecord = ledgerRep.selectRecord(userId, ledgerVo.ledgerSubTypeId, ledgerVo.updateDate)
 
        var ledgerMedia: LedgerMediaFile? = null
        if (historyRecord == null) {
            //生成台账更新记录
            val ledgerRecord = ledgerVo.toLedgerRecord(user)
            ledgerVo.id = ledgerRecord.lrGuid
            ledgerRep.insertRecord(ledgerRecord)
            //生成一条多媒体文件记录
            val filePath = ledgerMediaFileRep.saveFile(userId, ledgerVo, files)
            ledgerMediaFileRep.insert(ledgerVo, filePath)
        } else {
            ledgerVo.id = historyRecord.lrGuid
            ledgerMedia = deleteLedgerFile(historyRecord.lrGuid)
            // 去除不涉及标志或复制标志
            historyRecord.lrSubmitdate = Date()
            historyRecord.lrExtension2 = null
            ledgerRep.updateRecord(historyRecord)
            //更新的多媒体文件记录数据
            val filePath = ledgerMediaFileRep.saveFile(userId, ledgerVo, files)
            ledgerMedia?.mfPath1 = filePath
            ledgerMedia?.mfDescription1 = ledgerVo.remark1
            ledgerMedia?.mfSavetime = Date()
            ledgerMediaFileRep.update(ledgerMedia)
        }
 
        return true
    }
 
    override fun uploadLedger(userId: String, ledgerVoList: String, files: Array<MultipartFile>): Boolean {
 
        val mapper = ObjectMapper()
 
        val ledgerVos = mapper.readValue<List<LedgerVo>>(ledgerVoList, object : TypeReference<List<LedgerVo>>() {})
 
        ledgerVos.forEach {
            it.id = it.id ?: UUIDGenerator.generate16ShortUUID()
            it.fileType = it.fileType ?: 1
 
            val userInfo = userinfoMapper.selectByPrimaryKey(userId)
            userInfo?.extension2?.toInt()?.let { s -> it.sceneType = s }
 
            val today = Calendar.getInstance().apply { time = Date() }
                .get(Calendar.DAY_OF_MONTH)
            val cal = Calendar.getInstance().apply { time = it.updateDate ?: Date() }
            val updateYear = cal.get(Calendar.YEAR)
            val updateMonth = cal.get(Calendar.MONTH) + 1
            val updateDay = cal.get(Calendar.DAY_OF_MONTH)
 
            //检查数据库是否已有记录,选择插入或更新
            val tmp = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lsSubtypeid", it.ledgerSubTypeId)
                    .andEqualTo("lrYear", updateYear)
                    .andEqualTo("lrMonth", updateMonth)
                    .andEqualTo("lrSubmitid", userId)
            })
            var ledgerMedia: LedgerMediaFile? = null
            if (tmp.isEmpty()) {
                //生成台账更新记录
                val ledgerRecord = LedgerRecord().apply {
                    lrGuid = UUIDGenerator.generate16ShortUUID()
                    lsSubtypeid = it.ledgerSubTypeId
                    lsSubtypename = it.ledgerName
                    lrYear = updateYear
                    lrMonth = updateMonth.toByte()
                    lrDay = updateDay.toByte()
                    lrEasubmitkind = it.fileType?.toByte() ?: 1
                    lrSubmitid = userId
                    lrSubmitname = userInfo?.acountname ?: ""
                    lrIssubmitontime = today <= 10
                    lrSubmitdate = Date()
                    lrUpdatetype = it.updateType
                    lrExtension1 = it.sceneType.toString()
                }
                it.id = ledgerRecord.lrGuid
                ledgerRecordMapper.insert(ledgerRecord)
            } else {
                val record = tmp[0]
                it.id = record.lrGuid
                ledgerMedia = deleteLedgerFile(record.lrGuid)
                // 去除不涉及标志或复制标志
                record.lrExtension2 = null
                ledgerRecordMapper.updateByPrimaryKey(record)
            }
 
            //对每张图片生成相应的路径并保存
            var picPath = ""
            val time = DateUtil.DateToString(Date(), DateUtil.DateStyle.YYYY_MM)
            files.forEach { file ->
                val fileName = file.originalFilename
                //TODO 此处的文件路径需要修改为动态配置
//                val basePath = "D:/02product/05ledger/images/"
                val basePath = imgPath
                val path = "$time/$userId/${it.ledgerName}/"
                picPath += if (picPath.isEmpty()) {
                    "$path$fileName"
                } else {
                    ";$path$fileName"
                }
                try {
                    //调用文件保存方法
                    FileUtil.uploadFile(file.bytes, basePath + path, fileName!!)
                } catch (e: FileNotFoundException) {
                    e.printStackTrace()
                }
            }
 
            //生成一条多媒体文件记录
            if (ledgerMedia == null) {
                ledgerMedia = LedgerMediaFile().apply {
                    mfGuid = UUIDGenerator.generate16ShortUUID()
                    lrGuid = it.id
                    mfFiletype = it.fileType
                    mfPath1 = picPath
                    mfDescription1 = it.remark1
                    mfSavetime = Date()
                    mfIsdelete = false
                }
                //插入新的多媒体文件记录数据
                ledgerMediaFileMapper.insert(ledgerMedia)
            } else {
                ledgerMedia.mfPath1 = picPath
                ledgerMedia.mfDescription1 = it.remark1
                ledgerMedia.mfSavetime = Date()
                //更新的多媒体文件记录数据
                ledgerMediaFileMapper.updateByPrimaryKey(ledgerMedia)
            }
 
            return true
        }
 
        return false
    }
 
    override fun uploadNoLedger(
        userId: String,
        time: String,
        remark: String?,
        ledgerIdList: List<Int>,
    ): BaseResponse<String> {
        val date = LocalDate.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
        val year = date.year
        val month = date.monthValue
        val day = date.dayOfMonth
        val userInfo = userinfoMapper.selectByPrimaryKey(userId) ?: return BaseResponse(false, "用户不存在")
        ledgerIdList.forEach {
            //去重判断,当该类型台账已存在时,采用覆盖更新操作
            val r = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrSubmitid", userId)
                    .andEqualTo("lsSubtypeid", it)
                    .andEqualTo("lrYear", year)
                    .andEqualTo("lrMonth", month)
            })
            var record = if (r.size > 0) r[0] else null
 
            //生成台账更新记录
            if (record != null) {
                record.lrExtension2 = "notInvolved"
                ledgerRecordMapper.updateByPrimaryKey(record)
                deleteLedgerFile(record.lrGuid)?.let { m ->
                    m.mfPath1 = notInvolvedPath
                    ledgerMediaFileMapper.updateByPrimaryKey(m)
                }
            } else {
                //获取台账类型信息
                val ledgerType = ledgerSubTypeMapper.selectByPrimaryKey(it) ?: return@forEach
                record = LedgerRecord().apply {
                    lrGuid = record?.lrGuid ?: UUIDGenerator.generate16ShortUUID()
                    lsSubtypeid = ledgerType.lsSubtypeid
                    lsSubtypename = ledgerType.lsName
                    lrYear = year
                    lrMonth = month.toByte()
                    lrDay = day.toByte()
                    lrEasubmitkind = 1
                    lrSubmitid = userId
                    lrSubmitname = userInfo.acountname ?: ""
                    lrIssubmitontime = day <= 10
                    lrSubmitdate = Date()
                    lrUpdatetype
                    lrExtension1 = userInfo.extension2
                    lrExtension2 = "notInvolved"
                }
                ledgerRecordMapper.insert(record)
                //生成一条多媒体文件记录
                val ledgerMedia = LedgerMediaFile().apply {
                    mfGuid = UUIDGenerator.generate16ShortUUID()
                    lrGuid = record.lrGuid
                    mfFiletype = 1
                    mfPath1 = notInvolvedPath
                    mfDescription1 = remark
                    mfSavetime = Date()
                    mfIsdelete = false
                }
                ledgerMediaFileMapper.insert(ledgerMedia)
            }
        }
 
        return BaseResponse(true)
    }
 
    override fun getLedgerImg(userId: String, ledgerType: Int): List<String> {
        val result = mutableListOf<String>()
 
        PageHelper.startPage<LedgerRecord>(1, 1)
        val record = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
            createCriteria().andEqualTo("lsSubtypeid", ledgerType)
                .andEqualTo("lrSubmitid", userId)
            orderBy("lrYear").desc().orderBy("lrMonth").desc().orderBy("lrDay").desc()
        }).takeIf { it.isNotEmpty() }?.get(0)
 
        record?.let {
            ledgerMediaFileMapper.selectByExample(Example(LedgerMediaFile::class.java).apply {
                createCriteria().andEqualTo("lrGuid", it.lrGuid)
            }).forEach {
                it.mfPath1?.split(";")?.let { list ->
                    result.addAll(list)
                }
            }
        }
 
        return result
    }
 
    override fun getLedgerImgs(userId: String, ledgerType: List<Int>): List<LedgerVo> {
        val result = mutableListOf<String>()
 
        PageHelper.startPage<LedgerRecord>(1, 1)
        val record = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
            createCriteria().andIn("lsSubtypeid", ledgerType)
                .andEqualTo("lrSubmitid", userId)
            orderBy("lrYear").desc().orderBy("lrMonth").desc().orderBy("lrDay").desc()
        })
 
        return emptyList()
    }
 
    override fun getLedgerRecords(
        userId: String,
        ledgerSubTypeId: Int?,
        sceneType: Int,
        time: String,
    ): List<LedgerRecord> {
        val ledgerSubTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            if (ledgerSubTypeId != null) {
                createCriteria().andEqualTo("lsSubtypeid", ledgerSubTypeId)
            } else if (sceneType != SceneType.NoType.value) {
                createCriteria().andEqualTo("lScenetype", sceneType)
            }
        })
        val c = Calendar.getInstance().apply { this.time = DateUtil.StringToDate(time) }
        val year = c.get(Calendar.YEAR)
        val month = c.get(Calendar.MONTH) + 1
        val map = mutableMapOf<Int, MutableList<Int>>()
        ledgerSubTypes.forEach {
            val p = it.getlPeriod()
            if (!map.containsKey(p)) {
                map[p] = mutableListOf()
            }
            map[p]?.add(it.lsSubtypeid)
        }
        val records = mutableListOf<LedgerRecord>()
        map.forEach { (p, v) ->
            // FIXME: 2020/11/10  此处根据周期和当前月份计算得到当前月份所在周期的始末月,只适用于周期小于等于12个月的情况。后续待修改
            val startMon = ceil(month.toDouble() / p).toInt().minus(1).times(p).plus(1)
            var endMon = startMon + p - 1
            if (endMon > month) endMon = month
            val r = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrSubmitid", userId)
                    .andEqualTo("lrYear", year)
                    .andGreaterThanOrEqualTo("lrMonth", startMon.toByte())
                    .andLessThanOrEqualTo("lrMonth", endMon.toByte())
                    .andIn("lsSubtypeid", v)
            })
            val monMap = mutableMapOf<Int, LedgerRecord>()
            r.forEach {
                if (monMap.containsKey(it.lsSubtypeid)) {
                    val record = monMap[it.lsSubtypeid]!!
                    if (record.lrMonth < it.lrMonth) {
                        monMap[it.lsSubtypeid] = it
                    }
                } else {
                    monMap[it.lsSubtypeid] = it
                }
            }
            monMap.forEach { (_, u) ->
                records.add(u)
            }
        }
 
        return records
    }
 
    override fun copyLedger(userId: String, time: String, copyLedgerList: List<CopyLedgerVo>): BaseResponse<String> {
        val year = time.split("-")[0]
        val month = time.split("-")[1]
        val date = DateUtil.StringToDate(time, DateUtil.DateStyle.YYYY_MM)
        copyLedgerList.forEach {
            //去重判断
            val r = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrSubmitid", userId)
                    .andEqualTo("lsSubtypeid", it.subTypeId)
                    .andEqualTo("lrYear", year)
                    .andEqualTo("lrMonth", month)
            })
            if (r.size > 0) {
                return@forEach
            }
 
            val y = it.time?.split("-")?.get(0) ?: return@forEach
            val m = it.time?.split("-")?.get(1) ?: return@forEach
            ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrSubmitid", userId)
                    .andEqualTo("lsSubtypeid", it.subTypeId)
                    .andEqualTo("lrYear", y)
                    .andEqualTo("lrMonth", m)
            }).forEach record@{ lr ->
                //获取记录对应的文件信息
                val fileList = ledgerMediaFileMapper.selectByExample(Example(LedgerMediaFile::class.java).apply {
                    createCriteria().andEqualTo("lrGuid", lr.lrGuid)
                })
                if (fileList.size == 0) return@record
                val file = fileList[0] ?: return@record
 
                //修改记录信息,复制为新的台账
                lr.lrGuid = UUIDGenerator.generate16ShortUUID()
                lr.lrYear = year.toInt()
                lr.lrMonth = month.toByte()
                lr.lrIssubmitontime = true
                lr.lrSubmitdate = date
                lr.lrExtension2 = "copy"//表明是复制的台账
                ledgerRecordMapper.insert(lr)
 
                //修改对应的文件信息
                file.apply {
                    mfGuid = UUIDGenerator.generate16ShortUUID()
                    lrGuid = lr.lrGuid
                    mfSavetime = Date()
                }
                ledgerMediaFileMapper.insert(file)
            }
        }
 
        return BaseResponse(true)
    }
 
    override fun checkLedger(
        verifierId: String,
        remark: String?,
        recordList: List<LedgerCheckVo>,
    ): BaseResponse<Boolean> {
        val recordIdList = mutableListOf<String?>()
        recordList.forEach { recordIdList.add(it.recordId) }
        val records = ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
            createCriteria().andIn("lrGuid", recordIdList)
                .andIsNotNull("lrGuid")
        })
        return if (records.isEmpty()) {
            BaseResponse(false, "所选记录不存在")
        } else {
            records.forEach {
                for (r in recordList) {
                    if (r.recordId == it.lrGuid) {
                        it.lrVerifierid = verifierId
                        it.lrVerifierrealname
                        it.lrVerifydate = Date()
                        it.lrIsverify = r.result
                        it.lrVerifyrst = r.remark
                        it.lrAiverifytime = if (it.lrAiverifytime == null) 0 else it.lrAiverifytime++
                        it.lrIsai = false
 
                        ledgerRecordMapper.updateByPrimaryKey(it)
                        continue
                    }
                }
            }
            BaseResponse(true)
        }
    }
 
    /**
     * 删除台账的文件记录
     * @param lrGuid 台账记录id
     */
    private fun deleteLedgerFile(lrGuid: String): LedgerMediaFile? {
        return ledgerMediaFileRep.select(lrGuid)?.apply {
            if (this.mfPath1 != notInvolvedPath) {
                this.mfPath1.split(";").forEach { p ->
                    val path = imgPath + p
                    FileUtil.deleteFile(path)
                }
//                this.mfPath1 = notInvolvedPath
//                ledgerMediaFileMapper.updateByPrimaryKey(this)
            }
        }
    }
}