feiyu02
2025-09-18 baf2cc2ce3dfd1235c012a3750132769fcd9ad2f
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
package cn.flightfeather.supervision.lightshare.service.impl
 
import cn.flightfeather.supervision.business.bgtask.ReportTaskCtrl
import cn.flightfeather.supervision.business.report.DataSource
import cn.flightfeather.supervision.business.report.DbMapper
import cn.flightfeather.supervision.business.report.file.ReportOne
import cn.flightfeather.supervision.business.report.file.ReportThree
import cn.flightfeather.supervision.business.report.file.ReportTwo
import cn.flightfeather.supervision.business.report.template.*
import cn.flightfeather.supervision.common.exception.BizException
import cn.flightfeather.supervision.common.utils.*
import cn.flightfeather.supervision.domain.ds1.entity.*
import cn.flightfeather.supervision.domain.ds1.mapper.*
import cn.flightfeather.supervision.domain.ds1.repository.EvaluationRep
import cn.flightfeather.supervision.domain.ds1.repository.EvaluationRuleRep
import cn.flightfeather.supervision.domain.ds1.repository.SceneRep
import cn.flightfeather.supervision.domain.ds2.mapper.LedgerRecordMapper
import cn.flightfeather.supervision.domain.ds2.mapper.LedgerSubTypeMapper
import cn.flightfeather.supervision.domain.ds2.mapper.UserMapMapper
import cn.flightfeather.supervision.lightshare.service.SearchService
import cn.flightfeather.supervision.lightshare.service.TaskService
import cn.flightfeather.supervision.lightshare.vo.*
import com.github.pagehelper.PageHelper
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import tk.mybatis.mapper.entity.Example
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.net.URLEncoder
import java.nio.charset.StandardCharsets
import java.util.*
import javax.servlet.http.HttpServletResponse
 
/**
 * @author riku
 * Date: 2020/6/12
 */
@Service
class SearchServiceImpl(
    val userinfoMapper: UserinfoMapper,
    val subtaskMapper: SubtaskMapper,
    val scenseMapper: ScenseMapper,
    val sceneConstructionSiteMapper: SceneConstructionSiteMapper,
    val sceneMixingPlantMapper: SceneMixingPlantMapper,
    val sceneStorageYardMapper: SceneStorageYardMapper,
    val sceneWharfMapper: SceneWharfMapper,
    val problemlistMapper: ProblemlistMapper,
    val problemtypeMapper: ProblemtypeMapper,
    val townMapper: TownMapper,
    val mediafileMapper: MediafileMapper,
    val scoreMapper: ScoreMapper,
    val inspectionMapper: InspectionMapper,
    val taskMapper: TaskMapper,
    val monitorobjectversionMapper: MonitorobjectversionMapper,
    val evaluationruleMapper: EvaluationruleMapper,
    val evaluationsubruleMapper: EvaluationsubruleMapper2,
    val evaluationMapper: EvaluationMapper,
    val itemevaluationMapper: ItemevaluationMapper,
    val ledgerSubTypeMapper: LedgerSubTypeMapper,
    val ledgerRecordMapper: LedgerRecordMapper,
    val userMapMapper: UserMapMapper,
    val taskService: TaskService,
    private val evaluationRep: EvaluationRep,
    private val evaluationRuleRep: EvaluationRuleRep,
    private val sceneRep: SceneRep,
    @Value("\${filePath}") var filePath: String,
    @Value("\${imgPath}") var imgPath: String,
    private val dbMapper: DbMapper,
    private val reportTaskCtrl: ReportTaskCtrl,
) : SearchService {
 
    override fun writeToFile(config: ExcelConfigVo, mode: Int) {
        val dbMapper = DbMapper(
            scenseMapper,
            problemlistMapper,
            problemtypeMapper,
            subtaskMapper,
            monitorobjectversionMapper,
            sceneConstructionSiteMapper,
            sceneMixingPlantMapper,
            sceneStorageYardMapper,
            sceneWharfMapper,
            taskMapper,
            evaluationruleMapper, evaluationsubruleMapper, evaluationMapper, itemevaluationMapper,
            ledgerSubTypeMapper, ledgerRecordMapper, userinfoMapper, userMapMapper, townMapper
        )
        val dataSource = DataSource(config, dbMapper)
        val t = when (mode) {
            8 -> ReportOne(dataSource)
            9 -> ReportTwo(dataSource)
            10 -> ReportThree(dataSource)
 
            else -> null
        }
//        t?.execute()
        t?.toFile("target/")
    }
 
    override fun getExcel(config: ExcelConfigVo, response: HttpServletResponse): Boolean {
        val dataSource = DataSource(config, dbMapper)
        val t = when (config.mode) {
            1 -> ReportOne(dataSource)
            2 -> ReportTwo(dataSource)
            3 -> ReportThree(dataSource)
 
            else -> ReportOne(dataSource)
        }
        val fileName = t.getReportName()
        val p = "$filePath/autoscore/"
        val file = File(p + fileName)
        if (config.forceUpdate || !file.exists()) {
            val downloadUrl = "/autoscore/${fileName}"
            reportTaskCtrl.startTask(t, downloadUrl)
            return false
        } else {
            val fName = Base64.getEncoder().encodeToString(fileName.toByteArray())
            response.apply {
                setHeader("Content-Disposition", "attachment;filename=$fName")
                setHeader("fileName", fName)
                addHeader("Access-Control-Expose-Headers", "fileName")
                contentType = "application/vnd.ms-excel;charset=UTF-8"
                setHeader("Pragma", "no-cache")
                setHeader("Cache-Control", "no-cache")
                setDateHeader("Expires", 0)
            }
            response.outputStream.write(file.readBytes())
            return true
        }
    }
 
    override fun getSubTaskDetail(config: ExcelConfigVo): SubTaskTableVo {
        val dbMapper = DbMapper(
            scenseMapper,
            problemlistMapper,
            problemtypeMapper,
            subtaskMapper,
            monitorobjectversionMapper,
            sceneConstructionSiteMapper,
            sceneMixingPlantMapper,
            sceneStorageYardMapper,
            sceneWharfMapper,
            taskMapper,
            evaluationruleMapper, evaluationsubruleMapper, evaluationMapper, itemevaluationMapper,
            ledgerSubTypeMapper, ledgerRecordMapper, userinfoMapper, userMapMapper, townMapper
        )
//        val dataSource = DataSource(config, dbMapper)
//        val t = when (config.mode) {
////            1 -> ReportOne(dataSource)
////            2 -> ReportTwo(dataSource)
////            3 -> ReportThree(dataSource)
//            4->DailyReportSummary()
//            else -> ReportOne(dataSource)
//        }
//        val fileName = t.getReportName()
//        val fName = URLEncoder.encode(fileName, "UTF-8")
//
//        val p = Constant.DEFAULT_FILE_PATH + "/files/autoscore/"
//        val file = File(p + fileName)
//        if (config.forceUpdate || !file.exists()) {
//            t.toFile(p)
//        }
 
        return SubTaskTableVo(emptyList(), emptyList())
    }
 
    override fun downloadPic(config: ExcelConfigVo, response: HttpServletResponse): HttpServletResponse {
        val townName = if (config.townCode == null) {
            null
        } else {
            val l = townMapper.selectByExample(Example(Town::class.java).apply {
                createCriteria().andEqualTo("towncode", config.townCode)
            })
            if (l.isNotEmpty()) {
                l[0].townname
            } else {
                null
            }
        }
        val subTaskExample = Example(Subtask::class.java).apply {
            if (config.subTaskIdList != null && config.subTaskIdList.isNotEmpty()) {
                createCriteria().apply {
                    config.subTaskIdList.forEach {
                        orEqualTo("stguid", it)
                    }
                }
            } else {
                createCriteria()
                    .andEqualTo("tguid", config.topTaskGuid)
                    .andGreaterThanOrEqualTo("planstarttime", config.startTime)
                    .andLessThanOrEqualTo("planendtime", config.endTime).apply {
                        config.provinceCode?.let {
                            andEqualTo("provincecode", it)
                        }
                        config.cityCode?.let {
                            andEqualTo("citycode", it)
                        }
                        config.districtCode?.let {
                            andEqualTo("districtcode", it)
                        }
                    }
            }
            orderBy("planstarttime")
        }
 
        val subTasks = mutableMapOf<String, MutableList<Problemlist>>()
        subtaskMapper.selectByExample(subTaskExample).forEach {
            //查询该任务对应的场景
            val scene = scenseMapper.selectByPrimaryKey(it.scenseid)
 
            //根据场景条件筛选
            val need = if (config.sceneType != null) {
                scene.typeid == config.sceneType?.toByte()
            } else {
                true
            }
            if (need) {
                val problems = mutableListOf<Problemlist>()
                //查询子任务对应的问题,并且根据条件进行筛选
                val problemlistExample = Example(Problemlist::class.java).apply {
                    createCriteria().andEqualTo("stguid", it.stguid).apply {
                        config.problemName?.let { p ->
                            andEqualTo("problemname", p)
                        }
                        townName?.let { t ->
                            andLike("location", "%$t%")
                        }
                    }
                }
 
                problemlistMapper.selectByExample(problemlistExample).forEach problemType@{ p ->
                    val result = problemtypeMapper.selectByPrimaryKey(p.ptguid)
                    if (config.problemTypeName != null) {
                        if (result.typename != config.problemTypeName) {
                            return@problemType
                        }
                    }
                    problems.add(p)
                }
 
                if (problems.isNotEmpty()) {
                    subTasks[it.name ?: "未知任务"] = problems
                }
            }
        }
 
        //建立第一层目录,包含所有的任务
        val time = DateUtil.DateToString(Date(), "yyyy-MM-dd_HH-mm-ss")
        var basePath =
            imgPath + File.separator + "temp" + File.separator + time
        var file = File(basePath)
        var i = 1
        while (file.exists() && i <= 100) {
            basePath += "($i)"
            file = File(basePath)
            i++
        }
        if (file.exists()) {
            FileUtil.delAllFile(basePath)
        } else {
            file.mkdirs()
        }
        //循环建立第二层目录,每个任务单独建立一个文件夹
        subTasks.forEach {
 
            //建立一个子任务文件夹
            var subTaskFilePath = basePath + File.separator + it.key
            var sFile = File(subTaskFilePath)
            i = 1
            while (sFile.exists() && i <= 100) {
                subTaskFilePath += "($i)"
                sFile = File(subTaskFilePath)
                i++
            }
            if (sFile.exists()) {
                FileUtil.delAllFile(subTaskFilePath)
            } else {
                sFile.mkdirs()
            }
 
            //循环建立第三层目录,每个问题单独建立一个文件夹
            it.value.forEach { p ->
                var pPath = subTaskFilePath + File.separator + p.problemname
                var pFile = File(pPath)
                i = 1
                while (pFile.exists() && i <= 100) {
                    pPath += "($i)"
                    pFile = File(pPath)
                    i++
                }
                if (pFile.exists()) {
                    FileUtil.delAllFile(pPath)
                } else {
                    pFile.mkdirs()
                }
 
                var y = 1
                mediafileMapper.selectByExample(Example(Mediafile::class.java).apply {
                    createCriteria().andEqualTo("businessguid", p.guid)
                }).forEach { m ->
                    val picPath =
                        imgPath + File.separator + m.extension1 + m.guid + ".jpg"
                    val fromFile = File(picPath)
                    val picName = p.problemname + "_" + p.location + "($y).jpg"
                    val toFile = File(pPath + File.separator + picName)
                    FileUtil.copy(fromFile, toFile)
                    y++
                }
            }
        }
 
        response.apply {
            setHeader("Content-Disposition", "attachment;filename=$time.zip")
            contentType = "application/octet-stream"
            characterEncoding = StandardCharsets.UTF_8.name()
        }
 
        val zipFile = File("$basePath.zip")
        val fos1 = FileOutputStream(zipFile)
        ZipUtils.toZip(basePath, fos1, true)
 
        val out = response.outputStream
        val fis = FileInputStream(zipFile)
 
        val buf = ByteArray(2 * 1024)
        var len = fis.read(buf)
        while (len != -1) {
            out.write(buf, 0, len)
            len = fis.read(buf)
        }
        out.flush()
        out.close()
        fis.close()
 
        return response
    }
 
    override fun downloadPic2(sceneType: Int, topTaskId: String, response: HttpServletResponse): HttpServletResponse {
        //建立第一层目录,包含所有的任务
        val topTask = taskMapper.selectByPrimaryKey(topTaskId)
        val time = DateUtil.DateToString(Date(), "yyyy-MM-dd_HH-mm-ss")
        val basePath =
            imgPath + File.separator + "temp" + File.separator + topTask.name
        val file = File(basePath)
        if (!file.exists()) {
            file.mkdirs()
            //循环建立第二层目录,每个任务单独建立一个文件夹
            val subtaskList = subtaskMapper.selectByExample(Example(Subtask::class.java).apply {
                createCriteria().andEqualTo("tguid", topTaskId)
            })
            var i: Int
            subtaskList.forEach {
 
                scenseMapper.selectByPrimaryKey(it.scenseid).run {
                    if (typeid != sceneType.toByte()) {
                        return@forEach
                    }
                }
 
                //建立一个子任务文件夹
                var subTaskFilePath = "${basePath}${File.separator}(${
                    DateUtil.DateToString(
                        it.planstarttime,
                        DateUtil.DateStyle.YYYY_MM_DD_CN
                    )
                })(${it.deployerrealname})${it.scensename}"
                var sFile = File(subTaskFilePath)
                i = 1
                while (sFile.exists() && i <= 100) {
                    subTaskFilePath += "($i)"
                    sFile = File(subTaskFilePath)
                    i++
                }
                if (sFile.exists()) {
                    FileUtil.delAllFile(subTaskFilePath)
                } else {
                    sFile.mkdirs()
                }
 
                inspectionMapper.selectByExample(Example(Inspection::class.java).apply {
                    createCriteria().andEqualTo("stguid", it.stguid)
                }).forEach { ins ->
                    val fileMap = mutableMapOf<String, MutableList<Mediafile>>()
                    mediafileMapper.selectByExample(Example(Mediafile::class.java).apply {
                        createCriteria().andEqualTo("iguid", ins.guid)
                    }).forEach { m ->
                        val key = m.businesstype ?: "未分类"
                        if (!fileMap.containsKey(key)) {
                            fileMap[key] = mutableListOf()
                        }
                        fileMap[key]?.add(m)
                    }
 
                    //循环建立第三层目录,每种类型单独建立一个文件夹
                    fileMap.forEach { t, u ->
                        var pPath = subTaskFilePath + File.separator + t
                        var pFile = File(pPath)
                        i = 1
                        while (pFile.exists() && i <= 100) {
                            pPath += "($i)"
                            pFile = File(pPath)
                            i++
                        }
                        if (pFile.exists()) {
                            FileUtil.delAllFile(pPath)
                        } else {
                            pFile.mkdirs()
                        }
 
                        u.forEach { f ->
                            val picPath =
                                imgPath + File.separator + f.extension1 + f.guid + ".jpg"
                            val fromFile = File(picPath)
                            val picName = f.description
                            val toFile = File(pPath + File.separator + picName)
                            FileUtil.copy(fromFile, toFile)
                        }
                    }
                }
            }
        }
 
        response.apply {
            setHeader("Content-Disposition", "attachment;filename=${topTask.name}.zip")
            contentType = "application/octet-stream"
            characterEncoding = StandardCharsets.UTF_8.name()
        }
 
        val zipFile = File("$basePath.zip")
 
        if (!zipFile.exists()) {
            val fos1 = FileOutputStream(zipFile)
            ZipUtils.toZip(basePath, fos1, true)
        }
 
        val out = response.outputStream
        val fis = FileInputStream(zipFile)
 
        val buf = ByteArray(2 * 1024)
        var len = fis.read(buf)
        while (len != -1) {
            out.write(buf, 0, len)
            len = fis.read(buf)
        }
        out.flush()
        out.close()
        fis.close()
 
        return response
    }
 
    override fun searchScore4JingAn(
        token: String,
        year: Int,
        month: Int,
        page: Int?,
        perPage: Int?,
    ): BaseResponse<List<ScoreVo>> {
        if (token != "jingan") {
            return BaseResponse(false)
        }
 
        val pn = page ?: 1
        val ps = perPage ?: 100
        val p = PageHelper.startPage<Score>(pn, ps)
 
        val result = mutableListOf<ScoreVo>()
 
        scoreMapper.selectByExample(Example(Score::class.java).apply {
            createCriteria().andEqualTo("districtCode", "310106")
                .andEqualTo("year", year).andEqualTo("month", month)
        }).forEach {
            val vo = ScoreVo()
            BeanUtils.copyProperties(it, vo)
            result.add(vo)
        }
 
        return BaseResponse(true, head = DataHead(p.pageNum, p.pages), data = result)
    }
 
    override fun searchSubTaskByKeyword(
        userId: String,
        keyword: String,
        page: Int,
        perPage: Int,
    ): BaseResponse<List<SubtaskVo>> {
        val userInfo = userinfoMapper.selectByPrimaryKey(userId)
        if (userInfo.usertypeid?.toInt() == 3) return BaseResponse(false, "企业用户无查询权限")//企业用户无法查询
        val result = mutableListOf<SubtaskVo>()
        val pageInfo = PageHelper.startPage<Subtask>(page, perPage)
        subtaskMapper.selectByExample(Example(Subtask::class.java).apply {
            createCriteria().andLike("name", "%${keyword}%")
                .apply {
                    when (userInfo.usertypeid?.toInt()) {
                        0 -> {
                        } //管理员用户查询无其他限制
                        1 -> andLike("executorguids", "%${userId}%")//对于一般的巡查人员,只能查询到自己参与的子任务
                        2 -> andEqualTo("districtcode", userInfo.dGuid)//此处对于政府用户,dGuid存储的是区县编号
                    }
                }
            orderBy("planstarttime").desc()
        }).forEach {
            val vo = SubtaskVo()
            BeanUtils.copyProperties(it, vo)
            result.add(vo)
        }
 
        return BaseResponse(true, head = DataHead(pageInfo.pageNum, pageInfo.pages), data = result)
    }
 
    override fun getDailyReport(config: ExcelConfigVo): BaseTableVo {
        if (config.districtCode == null || config.startTime == null) return BaseTableVo(emptyList(), emptyList())
 
        val dbMapper = DbMapper(
            scenseMapper,
            problemlistMapper,
            problemtypeMapper,
            subtaskMapper,
            monitorobjectversionMapper,
            sceneConstructionSiteMapper,
            sceneMixingPlantMapper,
            sceneStorageYardMapper,
            sceneWharfMapper,
            taskMapper,
            evaluationruleMapper, evaluationsubruleMapper, evaluationMapper, itemevaluationMapper,
            ledgerSubTypeMapper, ledgerRecordMapper, userinfoMapper, userMapMapper, townMapper
        )
        val task =
            taskService.getByDistrictCode(config.districtCode, config.startTime).takeIf { it.isNotEmpty() }?.get(0)
        config.topTaskGuid = task?.tguid ?: ""
        config.allScene = false
        val dataSource = mutableListOf<DataSource>()
//        config.sceneType = Constant.SceneType.TYPE1.value.toInt()
        dataSource.add(DataSource(config, dbMapper))
 
//        val config2 = config.copy(sceneType = Constant.ScenseType.TYPE2.value.toInt())
//        dataSource.add(DataSource(config2, dbMapper))
//
//        val config3 = config.copy(sceneType = Constant.ScenseType.TYPE3.value.toInt())
//        dataSource.add(DataSource(config3, dbMapper))
//
//        val config4 = config.copy(sceneType = Constant.ScenseType.TYPE14.value.toInt())
//        dataSource.add(DataSource(config4, dbMapper))
 
        val t = DailyReportSummary(dataSource)
        t.execute()
        val result = t.toTableRows()
 
        return BaseTableVo(result.first, result.second)
    }
 
    override fun getScoreDetail(subTaskId: String): ScoreDetail {
        //场景信息
        val scene = sceneRep.findBySubTask(subTaskId)
        //总分
        val evaluation = evaluationRep.findBySubtask(subTaskId)
        //子规则逐条得分
        val subRuleScores = evaluationRep.findItemEvaluation(subTaskId)
        if (subRuleScores.isEmpty()) throw BizException("无评估记录")
        //评分总规则
        val rule = evaluationRuleRep.findAutoEvaluationRule(subTaskId) ?: throw BizException("未找到相关自动评估规则")
        //总规则对应的评分子规则
        val subRules = evaluationRuleRep.findSubRule(rule.guid)
        //查询结果
        val result = ScoreDetail()
        result.status = if (scene?.extension1.equals("1")) "在建" else "完工"
 
        result.updateTime = evaluation?.updatedate
        subRules.forEach {
            it.ertype ?: return@forEach
            result.addDetail(result.details, it, it.ertype!! - 1, subRuleScores, true)
        }
        result.calScore()
 
        return result
    }
}