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
package cn.flightfeather.supervision.lightshare.service.Impl
 
import cn.flightfeather.supervision.domain.entity.*
import cn.flightfeather.supervision.domain.enumeration.SceneType
import cn.flightfeather.supervision.domain.enumeration.SelfPatrolTaskStatus
import cn.flightfeather.supervision.domain.mapper.*
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.SelfPatrolService
import cn.flightfeather.supervision.lightshare.vo.BaseResponse
import cn.flightfeather.supervision.lightshare.vo.LedgerSubTypeVo
import cn.flightfeather.supervision.lightshare.vo.LedgerVo
import cn.flightfeather.supervision.lightshare.vo.SelfPatrolTaskVo
import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
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.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.*
 
@Service
class SelfPatrolServiceImpl(
    private val selfPatrolTaskMapper: SelfPatrolTaskMapper,
    private val selfPatrolRecordMapper: SelfPatrolRecordMapper,
    private val selfPatrolMediaFileMapper: SelfPatrolMediaFileMapper,
    private val userinfoMapper: UserinfoMapper,
    private val ledgerSubTypeMapper: LedgerSubTypeMapper,
) : SelfPatrolService {
 
    @Value("\${imgPath}")
    lateinit var imgPath: String
 
    private val notInvolvedPath = "ledgerIcons/ledger_not_involved.jpg"
 
    override fun getPatrolType(sceneType: Int): BaseResponse<List<LedgerSubTypeVo>> {
        val ledgerSubTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            if (sceneType != SceneType.NoType.value) {
                createCriteria().andEqualTo("lScenetype", sceneType)
                    .andEqualTo("lTypeid", -1)
            }
        })
        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 BaseResponse(true, data = resultList)
    }
 
    override fun publishTask(tasks: List<SelfPatrolTask>): BaseResponse<Boolean> {
        var r = 0
        val now = LocalDateTime.now()
        val date = Date()
        tasks.forEach {
            it.spGuid = UUIDGenerator.generate16ShortUUID()
            it.spTaskYear = now.year
            it.spTaskMonth = now.monthValue
            it.spCreateTime = date
            it.spTaskStatus = SelfPatrolTaskStatus.Published.value
            r += selfPatrolTaskMapper.insert(it)
        }
 
        return BaseResponse(r == tasks.size)
    }
 
    override fun getPublishedTask(userId: String, date: String?): BaseResponse<List<SelfPatrolTaskVo>> {
//        val res = selfPatrolTaskMapper.selectByExample(Example(SelfPatrolTask::class.java).apply {
//            createCriteria().andEqualTo("spFromUserId", userId).apply {
//                date?.let {
//                    val time = LocalDate.parse(it)
//                    andEqualTo("spTaskYear", time.year).andEqualTo("spTaskMonth", time.monthValue)
//                }
//            }
//        })
        val ledgerTypes = ledgerSubTypeMapper.selectAll()
        val time = LocalDate.parse(date)
        val res = selfPatrolTaskMapper.getPublishedTask(userId, time?.year, time?.monthValue)
        res.forEach {
            it.sceneType = SceneType.getByValue(it.sceneTypeId).des
            it.total = it.ledgerTypeId?.split(";")?.size ?: 0
            it.ledgerTypeId?.split(";")?.forEach {l ->
                if (it.ledgerTypeName.isNotBlank()) it.ledgerTypeName += ';'
                it.ledgerTypeName += ledgerTypes.find { t -> t.lsSubtypeid.toString() == l }?.lsName
            }
        }
 
        return BaseResponse(true, data = res)
    }
 
    override fun getToTask(userId: String, date: String?): BaseResponse<List<SelfPatrolTask?>> {
        val res = selfPatrolTaskMapper.selectByExample(Example(SelfPatrolTask::class.java).apply {
            createCriteria().andEqualTo("spToUserId", userId).apply {
                date?.let {
                    val time = LocalDate.parse(it)
                    andEqualTo("spTaskYear", time.year).andEqualTo("spTaskMonth", time.monthValue)
                }
            }
            orderBy("spCreateTime").desc()
        })
 
        return BaseResponse(true, data = res)
    }
 
    override fun getTaskRecord(taskId: String): BaseResponse<List<LedgerSubTypeVo>> {
        val task = selfPatrolTaskMapper.selectByPrimaryKey(taskId) ?: return BaseResponse(false, "该应急自巡查任务不存在")
        val sceneTypeId = task.spSceneTypeId
        val typeId = task.spLedgerTypeId
        val ledgerSubTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            createCriteria().andEqualTo("lTypeid", -1)
                .apply {
                    if (sceneTypeId != SceneType.NoType.value) {
                        andEqualTo("lScenetype", sceneTypeId)
                    }
                    andIn("lsSubtypeid", typeId.split(";"))
                }
            orderBy("lTypeid")
        })
        val records = selfPatrolRecordMapper.selectByExample(Example(SelfPatrolRecord::class.java).apply {
            createCriteria().andEqualTo("spGuid", taskId)
        })
 
        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) {
                    l.ledgerFinished = true
                    l.upLoad = true
//                    l.checkStatus = r.lrVerifyrst?.toIntOrNull() ?: LedgerCheckStatus.UnCheck.value
                    l.onTime = r?.srIssubmitontime ?: false
                    l.verified
                    l.verifierName = r?.srVerifierrealname
                    l.verified = r?.srIsverify
                    l.verifyRst = r?.srVerifyrst
                    break
                }
            }
            resultList.add(l)
        }
 
        return BaseResponse(true, data = resultList)
    }
 
    override fun uploadSelfPatrol(
        userId: String,
        taskId: String?,
        list: String,
        files: Array<MultipartFile>,
    ): BaseResponse<Boolean> {
        val mapper = ObjectMapper()
        val ledgerVos = mapper.readValue(list, 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 = selfPatrolRecordMapper.selectByExample(Example(SelfPatrolRecord::class.java).apply {
                createCriteria().andEqualTo("lsSubtypeid", it.ledgerSubTypeId)
                    .andEqualTo("srYear", updateYear)
                    .andEqualTo("srMonth", updateMonth)
                    .andEqualTo("srSubmitid", userId)
                    .andEqualTo("spGuid", taskId)
            })
            var ledgerMedia: SelfPatrolMediaFile? = null
            if (tmp.isEmpty()) {
                checkSelfPatrolFinished(taskId, 1)
                //生成台账更新记录
                val ledgerRecord = SelfPatrolRecord().apply {
                    srGuid = it.id
                    spGuid = taskId
                    lsSubtypeid = it.ledgerSubTypeId
                    lsSubtypename = it.ledgerName
                    srYear = updateYear
                    srMonth = updateMonth.toByte()
                    srDay = updateDay.toByte()
                    srEasubmitkind = it.fileType?.toByte() ?: 1
                    srSubmitid = userId
                    srSubmitname = userInfo?.acountname ?: ""
                    srIssubmitontime = today <= 10
                    srSubmitdate = Date()
                    srUpdatetype = it.updateType
                    srExtension1 = it.sceneType.toString()
                }
                it.id = ledgerRecord.srGuid
                selfPatrolRecordMapper.insert(ledgerRecord)
            } else {
                val record = tmp[0]
                it.id = record?.srGuid
                ledgerMedia = deleteLedgerFile(it.id)
                record?.srExtension2 = null
                selfPatrolRecordMapper.updateByPrimaryKey(record)
            }
 
            //对每张图片生成相应的路径并保存
            var picPath = ""
            val time = DateUtil.DateToString(Date(), DateUtil.DateStyle.YYYY_MM)
            files.forEach { file ->
                val fileName = file.originalFilename
                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: Exception) {
                    e.printStackTrace()
                }
            }
 
            //生成一条多媒体文件记录
            if (ledgerMedia == null) {
                ledgerMedia = SelfPatrolMediaFile().apply {
                    mfGuid = UUIDGenerator.generate16ShortUUID()
                    lrGuid = it.id
                    mfFiletype = it.fileType
                    mfPath1 = picPath
                    mfDescription1 = it.remark1
                    mfSavetime = Date()
                    mfIsdelete = false
                }
                //插入新的多媒体文件记录数据
                selfPatrolMediaFileMapper.insert(ledgerMedia)
            } else {
                ledgerMedia.mfPath1 = picPath
                ledgerMedia.mfDescription1 = it.remark1
                ledgerMedia.mfSavetime = Date()
                selfPatrolMediaFileMapper.updateByPrimaryKey(ledgerMedia)
            }
 
            return BaseResponse(true)
        }
 
        return BaseResponse(false)
    }
 
    override fun uploadNoSelfPatrol(
        userId: String,
        taskId: String?,
        time: String,
        remark: String?,
        idList: 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, "用户不存在")
        idList.forEach {
            //去重判断
            val r = selfPatrolRecordMapper.selectByExample(Example(SelfPatrolRecord::class.java).apply {
                createCriteria().andEqualTo("srSubmitid", userId)
                    .andEqualTo("lsSubtypeid", it)
                    .andEqualTo("srYear", year)
                    .andEqualTo("srMonth", month)
            })
            if (r.size > 0) {
                return@forEach
            }
 
            //获取台账类型信息
            val ledgerType = ledgerSubTypeMapper.selectByPrimaryKey(it) ?: return@forEach
 
            //生成台账更新记录
            val ledgerRecord = SelfPatrolRecord().apply {
                srGuid = UUIDGenerator.generate16ShortUUID()
                spGuid = taskId
                lsSubtypeid = ledgerType.lsSubtypeid
                lsSubtypename = ledgerType.lsName
                srYear = year
                srMonth = month.toByte()
                srDay = day.toByte()
                srEasubmitkind = 1
                srSubmitid = userId
                srSubmitname = userInfo.acountname ?: ""
                srIssubmitontime = day <= 10
                srSubmitdate = Date()
                srUpdatetype
                srExtension1 = userInfo.extension2
                srExtension2 = "notInvolved"
            }
            checkSelfPatrolFinished(taskId, 1)
            selfPatrolRecordMapper.insert(ledgerRecord)
 
            //生成一条多媒体文件记录
            val ledgerMedia = SelfPatrolMediaFile().apply {
                mfGuid = UUIDGenerator.generate16ShortUUID()
                lrGuid = ledgerRecord.srGuid
                mfFiletype = 1
                mfPath1 = "ledgerIcons/self_patrol_not_involved.jpg"
                mfDescription1 = remark
                mfSavetime = Date()
                mfIsdelete = false
            }
            selfPatrolMediaFileMapper.insert(ledgerMedia)
        }
        return BaseResponse(true)
    }
 
    override fun getDetail(userId: String, subTypeId: Int, taskId: String): BaseResponse<LedgerVo?> {
        val records = selfPatrolRecordMapper.selectByExample(Example(SelfPatrolRecord::class.java).apply {
            createCriteria().andEqualTo("srSubmitid", userId)
                .andEqualTo("lsSubtypeid", subTypeId)
                .andEqualTo("spGuid", taskId)
            orderBy("srSubmitdate").desc()
        })
        val result = mutableListOf<LedgerVo>()
        records.forEach {
            if (it == null) return@forEach
 
            val media = selfPatrolMediaFileMapper.selectByExample(
                Example(SelfPatrolMediaFile::class.java).apply {
                    createCriteria().andEqualTo("lrGuid", it.srGuid)
                        .andEqualTo("mfIsdelete", false)
                        .andEqualTo("mfFiletype", it.srEasubmitkind)
                    orderBy("mfSavetime").desc()
                }
            )
            val type = ledgerSubTypeMapper.selectByExample(
                Example(LedgerSubType::class.java).apply {
                    createCriteria().andEqualTo("lsSubtypeid", it.lsSubtypeid)
                }
            )
            result.add(LedgerVo().apply {
                id = it.srGuid
                this.ledgerSubTypeId = it.lsSubtypeid
                ledgerName = it.lsSubtypename
                ledgerTypeId = type?.get(0)?.getlTypeid()
                ledgerType = type?.get(0)?.getlTypename()
                ledgerFinished = true
                isUpLoad = true
                updateDate = it.srSubmitdate
                updateType = it.srUpdatetype
                fileType = it.srEasubmitkind.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.srExtension1 == null) SceneType.Restaurant.value else it.srExtension1.toInt()
            })
        }
        return if (result.isEmpty()) BaseResponse(false, "记录不存在") else BaseResponse(true, data = result[0])
    }
 
    override fun getDetailList(taskId: String): BaseResponse<List<LedgerVo>> {
        // 自巡查任务
        val task = selfPatrolTaskMapper.selectByPrimaryKey(taskId) ?: return BaseResponse(false, "自巡查任务不存在")
        // 自寻查任务包含的台账类型
        val ledgerTypes = ledgerSubTypeMapper.selectByExample(Example(LedgerSubType::class.java).apply {
            createCriteria().andIn("lsSubtypeid", task.spLedgerTypeId.split(";"))
        })
        // 用户上传的自巡查记录
        val records = selfPatrolRecordMapper.selectByExample(Example(SelfPatrolRecord::class.java).apply {
            createCriteria().andEqualTo("spGuid", taskId)
            orderBy("srSubmitdate").desc()
        })
        val result = mutableListOf<LedgerVo>()
        ledgerTypes.forEach {type->
            val it = records.find { record ->
                record?.lsSubtypeid == type.lsSubtypeid
            }
 
            val media = if (it != null) {
                selfPatrolMediaFileMapper.selectByExample(
                    Example(SelfPatrolMediaFile::class.java).apply {
                        createCriteria().andEqualTo("lrGuid", it?.srGuid)
                            .andEqualTo("mfIsdelete", false)
                            .andEqualTo("mfFiletype", it?.srEasubmitkind)
                        orderBy("mfSavetime").desc()
                    }
                )
            } else null
 
            result.add(LedgerVo().apply {
                id = it?.srGuid
                this.ledgerSubTypeId = type.lsSubtypeid
                ledgerName = type.lsName
                ledgerTypeId = type.getlTypeid()
                ledgerType = type.getlTypename()
                ledgerFinished = it != null
                isUpLoad = it != null
                updateDate = it?.srSubmitdate
                updateType = it?.srUpdatetype
                fileType = it?.srEasubmitkind?.toInt()
                path1 = media?.get(0)?.mfPath1
                remark1 = media?.get(0)?.mfDescription1
                path2 = media?.get(0)?.mfPath2
                remark2 = media?.get(0)?.mfDescription2
                this.sceneType = task.spSceneTypeId
            })
        }
        return BaseResponse(true, data = result)
    }
 
    override fun checkSelfPatrolFinished(taskId: String?, justFinishedNum: Int) {
        val task = selfPatrolTaskMapper.selectByPrimaryKey(taskId) ?: return
        val ledgerNum = task.spLedgerTypeId.split(";").size
        val recordNum = selfPatrolRecordMapper.selectCountByExample(Example(SelfPatrolRecord::class.java).apply {
            createCriteria().andEqualTo("spGuid", taskId)
        })
        if (recordNum + justFinishedNum >= ledgerNum) {
            task.spTaskStatus = SelfPatrolTaskStatus.Finished.value
            selfPatrolTaskMapper.updateByPrimaryKey(task)
        }
    }
 
    /**
     * 删除台账的文件记录
     * @param guid 台账记录id
     */
    private fun deleteLedgerFile(guid: String?): SelfPatrolMediaFile? {
        return selfPatrolMediaFileMapper.selectOne(SelfPatrolMediaFile().apply { lrGuid = guid })?.apply {
            if (this.mfPath1 != notInvolvedPath) {
                this.mfPath1.split(";").forEach { p ->
                    val path = imgPath + p
                    FileUtil.deleteFile(path)
                }
//                this.mfPath1 = notInvolvedPath
//                ledgerMediaFileMapper.updateByPrimaryKey(this)
            }
        }
    }
}