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
package cn.flightfeather.supervision.business.autooutput.datasource
 
import cn.flightfeather.supervision.common.exception.ResponseErrorException
import cn.flightfeather.supervision.common.utils.Constant
import cn.flightfeather.supervision.domain.ds1.entity.*
import cn.flightfeather.supervision.domain.ds2.entity.LedgerRecord
import cn.flightfeather.supervision.domain.ds2.entity.LedgerSubType
import cn.flightfeather.supervision.domain.ds2.entity.UserMap
import cn.flightfeather.supervision.domain.ds2.entity.UserinfoTZ
import tk.mybatis.mapper.entity.Example
import java.time.LocalDateTime
import java.time.ZoneId
 
/**
 * 自动输出数据源
 */
class AopDataSource(private val aopDbMapper: AopDbMapper, private val aopSceneTypeCheck: AopSceneTypeCheck) {
 
    private val sceneSourceList = mutableListOf<Scense?>()
    private val userSourceList = mutableListOf<UserinfoTZ?>()
    var config: AopDataConfig? = null
    private var mode = 0
    private val evaluationScene = EvaluationScene()
 
    /**
     * 设置数据源
     */
    fun setResource(topTaskGuid: String?, sceneType: Int, districtName: String?, townCode: String?) {
        val config = AopDataConfig(topTaskGuid = topTaskGuid, sceneType = sceneType, districtName = districtName,
            townCode = townCode)
        evaluationScene.config = config
        val check = aopSceneTypeCheck.checkSceneType(sceneType)
        if (check.first) {
            initSceneSource(config)
        } else {
            initUserSource(config)
        }
    }
 
    fun setResource(config: AopDataConfig) {
        config.sceneType ?: return
        evaluationScene.config = config
        val check = aopSceneTypeCheck.checkSceneType(config.sceneType!!)
        if (check.first) {
            initSceneSource(config)
        } else {
            initUserSource(config)
        }
    }
 
    fun setResource(subtask: Subtask) {
        val scene = aopDbMapper.scenseMapper.selectByPrimaryKey(subtask.scenseid)
        val sceneType = scene.typeid?.toInt()
        val config = AopDataConfig(topTaskGuid = subtask.tguid, sceneType = sceneType,
            districtName = subtask.districtname, townCode = subtask.towncode)
        evaluationScene.config = config
//        val check = aopSceneTypeCheck.checkSceneType(sceneType)
        this.mode = 0
        sceneSourceList.clear()
        sceneSourceList.add(scene)
    }
 
    /**
     * 轮询数据源
     */
    fun loop(callback: (index:Int, evaluationScene: EvaluationScene) -> Unit) {
        when (mode) {
            0 -> {
                sceneSourceList.forEachIndexed { i, scene ->
                    evaluationScene.clear()
                    evaluationScene.index = i
                    evaluationScene.setDefaultScene(scene)
                    callback(i, evaluationScene)
                }
            }
            1 -> {
                userSourceList.forEachIndexed { i, user ->
                    evaluationScene.clear()
                    evaluationScene.index = i
                    evaluationScene.setDefaultUserTZ(user)
                    callback(i, evaluationScene)
                }
            }
        }
    }
 
    // 从监管系统获取场景
    private fun initSceneSource(config: AopDataConfig) {
        config.topTaskGuid ?: throw ResponseErrorException("顶层任务id不能为null")
        this.config = config
        this.mode = 0
        sceneSourceList.clear()
        val taskSceneIdList =
            aopDbMapper.scenseMapper.getSceneByType(config.topTaskGuid, config.sceneType, config.townCode)
        sceneSourceList.addAll(taskSceneIdList)
    }
 
    // 从台账系统获取场景
    private fun initUserSource(config: AopDataConfig) {
        this.config = config
        this.mode = 1
        userSourceList.clear()
        aopDbMapper.userinfoTZMapper.selectByExample(Example(UserinfoTZ::class.java).apply {
            createCriteria().andEqualTo("extension1", config.districtName)
                .andEqualTo("extension2", config.sceneType)
                .andEqualTo("isenable", true)
                .andEqualTo("usertypeid", "3")
            and(createCriteria().orNotEqualTo("workno", "test").orIsNull("workno"))
        }).let { userSourceList.addAll(it) }
    }
 
    // 单个评估对象
    inner class EvaluationScene(){
        var index = 0
 
        var config: AopDataConfig? = null
 
        val scene = InfoProxy<Scense>()
 
        val userInfoTZ = InfoProxy<UserinfoTZ>()
 
        fun setDefaultScene(s: Scense?) {
            scene.value = s
            userInfoTZ.fetch = {_,_ ->
                val svUserId = aopDbMapper.userinfoMapper.selectByExample(Example(Userinfo::class.java).apply {
                    createCriteria().andEqualTo("dGuid", scene.value?.guid)
                })?.takeIf { m -> m.isNotEmpty() }?.get(0)?.guid
                val tzUserId = aopDbMapper.userMapMapper.selectByExample(Example(UserMap::class.java).apply {
                    createCriteria().andEqualTo("svUserId", svUserId)
                })?.takeIf { m -> m.isNotEmpty() }?.get(0)?.tzUserId
                aopDbMapper.userinfoTZMapper.selectByPrimaryKey(tzUserId)
            }
        }
 
        fun setDefaultUserTZ(u: UserinfoTZ?) {
            userInfoTZ.value = u
            scene.fetch = {_,_ ->
                val svUserId = aopDbMapper.userMapMapper.selectByExample(Example(UserMap::class.java).apply {
                    createCriteria().andEqualTo("tzUserId", userInfoTZ.value?.guid)
                })?.takeIf { m -> m.isNotEmpty() }?.get(0)?.svUserId
                val sId = aopDbMapper.userinfoMapper.selectByPrimaryKey(svUserId)?.dGuid
                aopDbMapper.scenseMapper.selectByPrimaryKey(sId)
            }
        }
 
        val userInfo = InfoProxy<Userinfo>{_,_ ->
            scene.value?.guid ?: return@InfoProxy null
            return@InfoProxy aopDbMapper.userinfoMapper.selectOne(Userinfo().apply {
                dGuid = scene.value?.guid
            })
        }
        //巡查任务信息
        val subTask = InfoProxy<Subtask> {_,_ ->
            return@InfoProxy aopDbMapper.subtaskMapper.selectByExample(Example(Subtask::class.java).apply {
                createCriteria().andEqualTo("scenseid", scene.value?.guid)
//                    .andBetween("planstarttime", config?.startTime, config?.endTime)
                    .andEqualTo("tguid", config?.topTaskGuid)
            })?.takeIf { it.isNotEmpty() }?.get(0)
        }
 
        //现场巡查信息
        val inspection = InfoProxy<Inspection>{_,_ ->
            val inspection = Inspection()
            inspection.stguid = subTask.value?.stguid
            return@InfoProxy aopDbMapper.inspectionMapper.selectOne(inspection)
        }
 
        //各场景特有的基本信息
        val baseScene = InfoProxy<BaseScene> {_,_ ->
            return@InfoProxy when (config?.sceneType.toString()) {
                // 监管系统
                Constant.SceneType.TYPE1.value -> {
                    aopDbMapper.sceneConstructionSiteMapper.selectByPrimaryKey(scene.value?.guid)
                }
                Constant.SceneType.TYPE2.value -> {
                    aopDbMapper.sceneWharfMapper.selectByPrimaryKey(scene.value?.guid)
                }
                Constant.SceneType.TYPE3.value -> {
                    aopDbMapper.sceneMixingPlantMapper.selectByPrimaryKey(scene.value?.guid)
                }
                Constant.SceneType.TYPE14.value -> {
                    aopDbMapper.sceneStorageYardMapper.selectByPrimaryKey(scene.value?.guid)
                }
                // 台账系统
                Constant.SceneType.TYPE5.value -> {
                    aopDbMapper.restaurantBaseInfoMapper.selectByPrimaryKey(userInfoTZ.value?.guid)
                }
                Constant.SceneType.TYPE6.value -> {
                    aopDbMapper.vehicleBaseInfoMapper.selectByPrimaryKey(userInfoTZ.value?.guid)
                }
                else -> null
            }
        }
 
        //具体的问题
        val problems = InfoProxy<MutableList<Problemlist>> {_,_ ->
            if (noRecord()) return@InfoProxy mutableListOf()
            return@InfoProxy aopDbMapper.problemlistMapper.selectByExample(Example(Problemlist::class.java).apply {
                createCriteria().andEqualTo("stguid", subTask.value?.stguid)
            })
        }
 
        //评估总分
        val evaluation = InfoProxy<Evaluation> {_,_ ->
            if (noRecord()) return@InfoProxy null
 
            return@InfoProxy aopDbMapper.evaluationMapper.selectByExample(Example(Evaluation::class.java).apply {
                createCriteria().andEqualTo("stguid", subTask.value?.stguid)
            })?.takeIf { it.isNotEmpty() }?.get(0)
        }
 
        //评估细则得分
        val itemevaluationList = InfoProxy<MutableList<Itemevaluation>> {_,_ ->
            return@InfoProxy aopDbMapper.itemevaluationMapper.selectByExample(Example(Itemevaluation::class.java).apply {
                createCriteria().andEqualTo("stguid", subTask.value?.stguid)
            })
        }
 
        //问题类型
        val problemTypes = InfoProxy<MutableList<Problemtype>>(config?.sceneType.toString()) { _, cacheMap ->
            val list = aopDbMapper.problemtypeMapper.selectByExample(Example(Problemtype::class.java).apply {
                createCriteria().andEqualTo("scensetypeid", scene.value?.typeid)
                    .andEqualTo("districtcode", scene.value?.districtcode)
                orderBy("extension1")
            })
            cacheMap[config?.sceneType.toString()] = list
            return@InfoProxy list
        }
 
        // FIXME: 2023/8/9 总规则的获取必须在[topItems]调用之后,否则为空
        val baseRule = InfoProxy<Evaluationrule>()
 
        // FIXME: 2023/8/9 总分的获取必须在[topItems]调用之后,否则为空
        val totalScore = InfoProxy<Int>()
 
        //自动评分规则一级分类
        val topItems = InfoProxy<MutableList<Evaluationsubrule2>>(config?.sceneType.toString()) { _, cacheMap ->
            val _topItems = mutableListOf<Evaluationsubrule2>()
            val _rules = mutableListOf<Pair<Evaluationsubrule2, MutableList<Evaluationsubrule2>>>()
            val rule = aopDbMapper.evaluationruleMapper.selectByExample(Example(Evaluationrule::class.java).apply {
                createCriteria()
                    .andEqualTo("tasktypeid", 99)
                    .andEqualTo("scensetypeid", scene.value?.typeid)
            })
            if (rule.isNotEmpty()) {
                this@EvaluationScene.baseRule.value = rule[0]
                this@EvaluationScene.baseRule.cacheMap[config?.sceneType.toString()] = rule[0]
 
                val ruleId = rule[0].guid
                val rules =
                    aopDbMapper.evaluationsubruleMapper.selectByExample(Example(Evaluationsubrule2::class.java).apply {
                        createCriteria().andEqualTo("erguid", ruleId)
                    })
                rules.forEach {
                    if (it.ertype == 2) {
                        _topItems.add(it)
                    }
                }
                _topItems.sortBy { it.displayid }
 
                var t = 0
                _topItems.forEach {
                    t += it.maxscore ?: 0
                    val tempRules = mutableListOf<Evaluationsubrule2>()
                    for (i in rules) {
                        if (i.fatherid == it.guid && i.ertype == 3) {
                            tempRules.add(i)
                        }
                    }
                    //评分大项如果没有找到评分小项,则说明其直接对应最小评分项,其本身变成评分项
                    if (tempRules.isEmpty()) {
                        tempRules.add(it)
                    }
                    tempRules.sortBy { t -> t.displayid }
                    tempRules.forEach { temp ->
                        val tempSubRules = mutableListOf<Evaluationsubrule2>()
                        for (i in rules) {
                            if (i.fatherid == temp.guid && i.ertype == 4) {
                                tempSubRules.add(i)
                            }
                        }
                        tempSubRules.sortBy { ts -> ts.displayid }
                        _rules.add(Pair(temp, tempSubRules))
                    }
                }
                this@EvaluationScene.totalScore.value = t
                this@EvaluationScene.totalScore.cacheMap[config?.sceneType.toString()] = t
                this@EvaluationScene.rules.value = _rules
                this@EvaluationScene.rules.cacheMap[config?.sceneType.toString()] = _rules
            }
            cacheMap[config?.sceneType.toString()] = _topItems
            return@InfoProxy _topItems
        }
 
        // FIXME: 2023/8/9 子规则的获取必须在[topItems]调用之后,否则为空
        //自动评分规则二级和三级分类
        val rules = InfoProxy<MutableList<Pair<Evaluationsubrule2, MutableList<Evaluationsubrule2>>>>()
 
        //必填台账数量
        val ledgerCount = InfoProxy<Int>(config?.sceneType.toString()) {_, cacheMap ->
            val tzSceneType = Constant.SceneType.typeMap(scene.value?.typeid)
            val list = aopDbMapper.ledgerSubTypeMapper.selectCountByExample(Example(LedgerSubType::class.java).apply {
                createCriteria().andEqualTo("lScenetype", tzSceneType).andEqualTo("lNeedupdate", true)
            })
            cacheMap[config?.sceneType.toString()] = list
            return@InfoProxy list
        }
 
        //用户实际提交台账数量
        val ledgerRecords = InfoProxy<List<LedgerRecord>> {_,_ ->
            return@InfoProxy aopDbMapper.ledgerRecordMapper.selectByExample(Example(LedgerRecord::class.java).apply {
                createCriteria().andEqualTo("lrYear", config?.year)
                    .andEqualTo("lrMonth", config?.month)
                    .andEqualTo("lrSubmitid", userInfoTZ.value?.guid)
            })
        }
 
        /**
         * 获取当前巡查任务的上期巡查记录
         */
        fun lastSubTask(): EvaluationScene {
            val last = EvaluationScene()
            val r = aopDbMapper.subtaskMapper.selectByExample(Example(Subtask::class.java).apply {
                createCriteria().andEqualTo("scenseid", subTask.value?.scenseid)
                    .andLessThan("planstarttime", subTask.value?.planstarttime)
                orderBy("planstarttime").desc()
            })
            if (r.isNotEmpty()) {
                val thisMonth = LocalDateTime.ofInstant(subTask.value?.planstarttime?.toInstant(), ZoneId.systemDefault())
                    .withDayOfMonth(1).toLocalDate()
                val lastMonth = LocalDateTime.ofInstant(r[0]?.planstarttime?.toInstant(), ZoneId.systemDefault()).withDayOfMonth(1).toLocalDate()
                if (lastMonth.plusMonths(1).isEqual(thisMonth)) {
                    last.subTask.value = r[0]
                }
            }
            return last
        }
 
        /**
         * 清空当前处理的对象的相关数据源
         */
        fun clear() {
            scene.clear()
            userInfo.clear()
            userInfoTZ.clear()
            subTask.clear()
            inspection.clear()
            baseScene.clear()
            problems.clear()
            evaluation.clear()
            itemevaluationList.clear()
            problemTypes.clear()
            baseRule.clear()
            totalScore.clear()
            topItems.clear()
            rules.clear()
            ledgerCount.clear()
            ledgerRecords.clear()
        }
 
        /**
         * 判断场景是否巡查监管,有无巡查记录
         */
        fun noRecord() = subTask.value?.stguid == null
    }
 
    // 评估对象相关信息获取代理
    inner class InfoProxy<T>(
        val key: String? = null,
        var fetch: (defaultValue: T?, cacheMap: MutableMap<String, T?>) -> T? =
            { _, _ ->
                null
            },
    ) {
 
        private var _value: T? = null
        private var fetched: Boolean = false
        private var defaultValue: T? = null
        private var cacheTimeStamp = LocalDateTime.now()
        val cacheMap = mutableMapOf<String, T?>()
 
        var value: T?
            get() {
                if (defaultValue != null) {
                    return defaultValue
                } else if (!fetched && _value == null) {
                    _value = if (cacheMap.containsKey(key) && LocalDateTime.now().minusDays(1).isBefore(cacheTimeStamp)) {
                        cacheMap[key]
                    } else {
                        cacheTimeStamp = LocalDateTime.now()
                        fetch(defaultValue, cacheMap)
                    }
                    fetched = true
                }
                return _value
            }
            set(value) {
                defaultValue = value
            }
 
        fun clear() {
            defaultValue = null
            _value = null
            fetched = false
        }
    }
}