cloudroam
2025-03-06 cf9bc941487df8dfb0780d3e8f1281f4e397b5fa
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
package com.example.firstapp.ui.dashboard
 
import com.example.firstapp.R
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.firstapp.databinding.FragmentDashboardBinding
import com.google.android.material.tabs.TabLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.firstapp.adapter.PackageAdapter
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.charts.PieChart
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.*
import com.github.mikephil.charting.formatter.ValueFormatter
import java.util.*
import java.text.SimpleDateFormat
import android.graphics.Color
import android.widget.GridLayout
import com.example.firstapp.model.DailyStat
 
class DashboardFragment : Fragment() {
 
    private var _binding: FragmentDashboardBinding? = null
    private val binding get() = _binding!!
    private val packageAdapter = PackageAdapter()
    private var currentDate = Calendar.getInstance()
    private var currentDateType = DateType.DAY
    private lateinit var barChart: BarChart
    private lateinit var pieChart: PieChart
    private lateinit var heatmapView: View
    enum class DateType {
        DAY, WEEK, MONTH, YEAR
    }
    private val viewModel: DashboardViewModel by viewModels()
 
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentDashboardBinding.inflate(inflater, container, false)
        return binding.root
    }
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
 
        //渲染包裹列表
        setupRecyclerView()
        //初始化tab内容和数据
        setupTabLayout()
        //日期调整
        setupDatePicker()
        setupView(view)
        updateDateDisplay()
        loadPackages()
    }
 
    private fun setupRecyclerView() {
        binding.recyclerPackages.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = packageAdapter
        }
    }
 
    private fun setupTabLayout() {
        binding.tabDateRange.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                currentDateType = when(tab?.position) {
                    0 -> DateType.DAY
                    1 -> DateType.WEEK
                    2 -> DateType.MONTH
                    3 -> DateType.YEAR
                    else -> DateType.DAY
                }
                updateDateDisplay()
                updateCharts()
                loadPackages()
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {}
            override fun onTabReselected(tab: TabLayout.Tab?) {}
        })
    }
 
    private fun setupDatePicker() {
        binding.btnPreviousDate.setOnClickListener {
            adjustDate(-1)
        }
        binding.btnNextDate.setOnClickListener {
            adjustDate(1)
        }
    }
 
    private fun adjustDate(amount: Int) {
        when (currentDateType) {
            DateType.DAY -> currentDate.add(Calendar.DAY_OF_MONTH, amount)
            DateType.WEEK -> currentDate.add(Calendar.WEEK_OF_YEAR, amount)
            DateType.MONTH -> currentDate.add(Calendar.MONTH, amount)
            DateType.YEAR -> currentDate.add(Calendar.YEAR, amount)
        }
        updateDateDisplay()
        updateCharts()
        loadPackages()
    }
 
    private fun updateDateDisplay() {
        val dateFormat = when (currentDateType) {
            DateType.DAY -> "yyyy年MM月dd日"
            DateType.WEEK -> {
                // 获取本周的起始和结束日期
                val calendar = currentDate.clone() as Calendar
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
                val startDate = SimpleDateFormat("MM月dd日", Locale.getDefault()).format(calendar.time)
                
                calendar.add(Calendar.DAY_OF_WEEK, 6)
                val endDate = SimpleDateFormat("MM月dd日", Locale.getDefault()).format(calendar.time)
                
                "$startDate-$endDate"
            }
            DateType.MONTH -> "yyyy年MM月"
            DateType.YEAR -> "yyyy年"
        }
        
        if (currentDateType == DateType.WEEK) {
            binding.textCurrentDate.text = dateFormat
        } else {
            binding.textCurrentDate.text = SimpleDateFormat(dateFormat, Locale.getDefault())
                .format(currentDate.time)
        }
    }
    private fun setupView(view: View) {
        val weekStatsView = binding.layoutWeekStats.root
        barChart = weekStatsView.findViewById(R.id.chart_daily_packages)
        pieChart = weekStatsView.findViewById(R.id.chart_courier_distribution)
        heatmapView = weekStatsView.findViewById(R.id.heatmap_yearly)
        
        // 初始化时隐藏统计视图
        weekStatsView.visibility = View.GONE
        
        setupBarChart()
        setupPieChart()
        setupHeatmap()
        updateCharts()
    }
    private fun setupBarChart() {
        barChart.apply {
            description.isEnabled = false
            setDrawGridBackground(false)
            legend.isEnabled = false
            
            // 增大图表高度
            minimumHeight = (resources.displayMetrics.density * 300).toInt()
 
            // X轴设置
            xAxis.apply {
                position = XAxis.XAxisPosition.BOTTOM
                setDrawGridLines(false)
                granularity = 1f
                labelRotationAngle = -45f
                textSize = 10f
            }
 
            // Y轴设置
            axisLeft.apply {
                setDrawGridLines(true)
                axisMinimum = 0f
                granularity = 0.5f  // 将刻度间隔设为0.5
                valueFormatter = object : ValueFormatter() {
                    override fun getFormattedValue(value: Float): String {
                        // 只有整数时才显示标签
                        return if (value % 1 == 0f) {
                            value.toInt().toString()
                        } else {
                            ""
                        }
                    }
                }
            }
            axisRight.isEnabled = false
            
            // 设置图表交互
            setTouchEnabled(true)
            isDragEnabled = true
            setScaleEnabled(true)
        }
 
        updateBarChartData()
    }
    private fun updateBarChartData() {
        val statsFlow = when (currentDateType) {
            DateType.WEEK -> {
                viewModel.getWeeklyStats(currentDate.timeInMillis, 6)
            }
            DateType.MONTH -> {
                viewModel.getYearMonthlyStats(currentDate.timeInMillis)
            }
            else -> return
        }
 
        statsFlow.observe(viewLifecycleOwner) { stats ->
            if (stats.isEmpty()) return@observe
            
            val entries = stats.mapIndexed { index, stat ->
                BarEntry(index.toFloat(), stat.count.toFloat())
            }
 
            val dataSet = BarDataSet(entries, "包裹数量")
            dataSet.apply {
                color = resources.getColor(R.color.purple_500)
                valueTextSize = 12f
                valueFormatter = object : ValueFormatter() {
                    override fun getFormattedValue(value: Float): String {
                        return value.toInt().toString()
                    }
                }
            }
 
            val barData = BarData(dataSet)
            barChart.data = barData
            
            // 修改X轴标签显示
            barChart.xAxis.apply {
                valueFormatter = object : ValueFormatter() {
                    override fun getFormattedValue(value: Float): String {
                        val position = value.toInt()
                        if (position >= 0 && position < stats.size) {
                            return when(currentDateType) {
                                DateType.WEEK -> {
                                    val weekStat = stats[position]
                                    val calendar = Calendar.getInstance()
                                    calendar.timeInMillis = weekStat.weekStart!!
                                    SimpleDateFormat("MM/dd", Locale.getDefault()).format(calendar.time)
                                }
                                DateType.MONTH -> {
                                    // 显示月份标签(1-12月)
                                    "${position + 1}月"
                                }
                                else -> ""
                            }
                        }
                        return ""
                    }
                }
                position = XAxis.XAxisPosition.BOTTOM
                setDrawGridLines(false)
                labelCount = stats.size
                granularity = 1f
                labelRotationAngle = -45f
                textSize = 10f
            }
            
            // 高亮当前月份
            if (currentDateType == DateType.MONTH) {
                val currentMonth = currentDate.get(Calendar.MONTH)
                dataSet.setColors(List(stats.size) { index ->
                    if (index == currentMonth) resources.getColor(R.color.purple_500)
                    else resources.getColor(R.color.purple_200)
                })
            } else if (currentDateType == DateType.WEEK) {
                // 保持周视图的高亮逻辑
                val highlightIndex = 3f
                dataSet.setColors(List(stats.size) { index ->
                    if (index == 3) resources.getColor(R.color.purple_500)
                    else resources.getColor(R.color.purple_200)
                })
            }
            
            barChart.invalidate()
        }
    }
    private fun setupPieChart() {
        pieChart.apply {
            description.isEnabled = false
            setUsePercentValues(false)
            setDrawEntryLabels(false)
            
            // 调整饼图边距
            setExtraOffsets(20f, 10f, 60f, 10f)
            
            // 配置图例
            legend.apply {
                isEnabled = true
                verticalAlignment = Legend.LegendVerticalAlignment.CENTER
                horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
                orientation = Legend.LegendOrientation.VERTICAL
                setDrawInside(false)
                xEntrySpace = 10f
                yEntrySpace = 5f
                yOffset = 0f
                textSize = 14f
            }
 
            // 设置中心空白
            holeRadius = 45f
            transparentCircleRadius = 50f
        }
 
        updatePieChartData()
    }
    private fun updatePieChartData() {
        viewModel.getCourierStats(
            currentDate.timeInMillis,
            currentDateType.name
        ).observe(viewLifecycleOwner) { stats ->
            val entries = stats.map { stat ->
                PieEntry(stat.count.toFloat(), "${stat.courierName}(${stat.count})")
            }
 
            val dataSet = PieDataSet(entries, "快递公司分布")
            dataSet.colors = listOf(
                resources.getColor(R.color.purple_500),
                resources.getColor(R.color.teal_200),
                resources.getColor(R.color.purple_200),
                resources.getColor(R.color.teal_700)
            )
            dataSet.valueTextSize = 14f // 增大数值文字大小
 
            val pieData = PieData(dataSet)
            pieData.setValueFormatter(object : ValueFormatter() {
                override fun getFormattedValue(value: Float): String {
                    return value.toInt().toString()
                }
            })
 
            pieChart.data = pieData
            pieChart.invalidate()
        }
    }
    private fun getDayLabels(): Array<String> {
        return arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
    }
 
    private fun loadPackages() {
        viewModel.getPackages(
            currentDate.timeInMillis,
            currentDateType.name
        ).observe(viewLifecycleOwner) { packages ->
            packageAdapter.updatePackages(packages)
            binding.textPackageCount.text = "${packages.size}个"
        }
    }
    private fun setupHeatmap() {
        heatmapView.visibility = View.GONE
    }
 
    private fun updateHeatmapData() {
        viewModel.getYearlyHeatmap(currentDate.timeInMillis).observe(viewLifecycleOwner) { stats ->
            if (stats.isEmpty()) return@observe
 
            // 创建52周x7天的数据矩阵
            val heatmapMatrix = Array(7) { IntArray(52) }
            
            // 填充数据
            stats.forEach { stat ->
                val week = stat.weekOfYear - 1 // 0-51
                val dayOfWeek = stat.dayOfWeek - 1 // 0-6
                if (week in 0..51 && dayOfWeek in 0..6) {
                    heatmapMatrix[dayOfWeek][week] = stat.count
                }
            }
 
            // 更新UI
            binding.layoutWeekStats.heatmapYearly.apply {
                // 清除现有的子视图
                removeAllViews()
                
                // 创建网格布局
                val gridLayout = GridLayout(context).apply {
                    rowCount = 7
                    columnCount = 52
                }
 
                // 添加日期标签
                val dayLabels = arrayOf("周日", "周一", "周二", "周三", "周四", "周五", "周六")
                for (i in 0..6) {
                    val label = TextView(context).apply {
                        text = dayLabels[i]
                        textSize = 10f
                        setPadding(0, 0, 8, 0)
                    }
                    gridLayout.addView(label)
                }
 
                // 添加热力图单元格
                for (day in 0..6) {
                    for (week in 0..51) {
                        val count = heatmapMatrix[day][week]
                        val cell = View(context).apply {
                            layoutParams = ViewGroup.LayoutParams(
                                resources.getDimensionPixelSize(R.dimen.heatmap_cell_size),
                                resources.getDimensionPixelSize(R.dimen.heatmap_cell_size)
                            )
                            setBackgroundColor(getHeatmapColor(count))
                            setPadding(1, 1, 1, 1)
                        }
                        gridLayout.addView(cell)
                    }
                }
 
                addView(gridLayout)
            }
        }
    }
 
    private fun getHeatmapColor(count: Int): Int {
        // 根据数量返回不同深浅的颜色
        return when {
            count == 0 -> Color.parseColor("#EBEDF0")
            count <= 2 -> Color.parseColor("#9BE9A8")
            count <= 4 -> Color.parseColor("#40C463")
            count <= 6 -> Color.parseColor("#30A14E")
            else -> Color.parseColor("#216E39")
        }
    }
 
    private fun updateCharts() {
        when (currentDateType) {
            DateType.DAY -> {
                // 日视图显示包裹列表,隐藏统计图表
                binding.recyclerPackages.visibility = View.VISIBLE
                binding.layoutWeekStats.root.visibility = View.GONE
                binding.layoutYearStats.root.visibility = View.GONE
            }
            DateType.WEEK, DateType.MONTH -> {
                // 周和月视图显示柱状图和饼图,隐藏包裹列表
                binding.recyclerPackages.visibility = View.GONE
                binding.layoutWeekStats.root.visibility = View.VISIBLE
                binding.layoutYearStats.root.visibility = View.GONE
                binding.layoutWeekStats.chartDailyPackages.visibility = View.VISIBLE
                binding.layoutWeekStats.heatmapYearly.visibility = View.GONE
                updateBarChartData()
                updatePieChartData()
            }
            DateType.YEAR -> {
                // 年视图显示热力图和饼图,隐藏包裹列表和柱状图
                binding.recyclerPackages.visibility = View.GONE
                binding.layoutWeekStats.root.visibility = View.VISIBLE
                binding.layoutYearStats.root.visibility = View.VISIBLE
                binding.layoutWeekStats.chartDailyPackages.visibility = View.GONE
                binding.layoutWeekStats.heatmapYearly.visibility = View.VISIBLE
                updateHeatmapData()
                updatePieChartData()
            }
        }
    }
 
    private fun updateYearlyStats() {
        viewModel.getYearlyStats(currentDate.timeInMillis).observe(viewLifecycleOwner) { stats: List<DailyStat> ->
            if (stats.isEmpty()) return@observe
            
            // 更新年度包裹总数
            binding.layoutYearStats.textTotalPackages.text = "${stats.sumOf { it.count }}个"
            
            // 更新平均每天包裹数
            val avgDaily = stats.sumOf { it.count }.toFloat() / 365
            binding.layoutYearStats.textDailyAverage.text = String.format("%.2f", avgDaily)
        }
    }
 
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}