cloudroam
2025-03-04 2a117297daf83b2e1a104603e9641226d5beeba3
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
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.lifecycle.ViewModelProvider
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.example.firstapp.core.Core
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.IndexAxisValueFormatter
import java.util.*
import java.text.SimpleDateFormat
 
class DashboardFragment : Fragment() {
 
    private var _binding: FragmentDashboardBinding? = null
 
    // This property is only valid between onCreateView and
    // onDestroyView.
    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
    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()
        setupTabLayout()
        setupDatePicker()
        updateDateDisplay()
        setupWeekView(view)
        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
                }
                // 切换视图
                binding.viewFlipperStats.displayedChild = when(currentDateType) {
                    DateType.DAY -> 0
                    DateType.WEEK -> 1
                    else -> 0
                }
                updateDateDisplay()
//                loadPackages()
                observePackages()
            }
            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()
        loadPackages()
    }
 
    private fun updateDateDisplay() {
        val dateFormat = when (currentDateType) {
            DateType.DAY -> "yyyy年MM月dd日"
            DateType.WEEK -> "yyyy年第ww周"
            DateType.MONTH -> "yyyy年MM月"
            DateType.YEAR -> "yyyy年"
        }
        binding.textCurrentDate.text = SimpleDateFormat(dateFormat, Locale.getDefault())
            .format(currentDate.time)
    }
    private fun setupWeekView(view: View) {
        val weekStatsView = binding.layoutWeekStats.root
        barChart = weekStatsView.findViewById(R.id.chart_daily_packages)
        pieChart = weekStatsView.findViewById(R.id.chart_courier_distribution)
        setupBarChart()
        setupPieChart()
    }
    private fun setupBarChart() {
        // 配置柱状图
        barChart.apply {
            description.isEnabled = false
            setDrawGridBackground(false)
            legend.isEnabled = false
 
            // X轴设置
            xAxis.apply {
                position = XAxis.XAxisPosition.BOTTOM
                setDrawGridLines(false)
                valueFormatter = IndexAxisValueFormatter(getDayLabels())
            }
 
            // Y轴设置
            axisLeft.apply {
                setDrawGridLines(true)
                axisMinimum = 0f
            }
            axisRight.isEnabled = false
        }
 
        updateBarChartData()
    }
    private fun updateBarChartData() {
        viewModel.getDailyStats(currentDate.timeInMillis).observe(viewLifecycleOwner) { stats ->
            val entries = stats.mapIndexed { index, stat ->
                BarEntry(index.toFloat(), stat.count.toFloat())
            }
 
            val dataSet = BarDataSet(entries, "包裹数量")
            dataSet.color = resources.getColor(R.color.purple_500)
 
            barChart.data = BarData(dataSet)
            barChart.invalidate()
        }
    }
    private fun setupPieChart() {
        // 配置饼图
        pieChart.apply {
            description.isEnabled = false
            setUsePercentValues(true)
            setDrawEntryLabels(false)
 
            legend.isEnabled = true
            legend.verticalAlignment = Legend.LegendVerticalAlignment.CENTER
            legend.horizontalAlignment = Legend.LegendHorizontalAlignment.RIGHT
            legend.orientation = Legend.LegendOrientation.VERTICAL
        }
 
        updatePieChartData()
    }
    private fun updatePieChartData() {
        viewModel.getCourierStats(currentDate.timeInMillis).observe(viewLifecycleOwner) { stats ->
            val entries = stats.map { stat ->
                PieEntry(stat.count.toFloat(), stat.category)
            }
 
            val dataSet = PieDataSet(entries, "快递公司分布")
            dataSet.colors = listOf(
                resources.getColor(R.color.purple_500),
                resources.getColor(R.color.teal_200)
            )
 
            pieChart.data = PieData(dataSet)
            pieChart.invalidate()
        }
    }
    private fun getDayLabels(): Array<String> {
        return arrayOf("周一", "周二", "周三", "周四", "周五", "周六", "周日")
    }
 
    private fun loadPackages() {
        // 这里应该从数据库或网络加载数据
        // 根据当前选择的日期类型传入对应参数
        val packages = when (currentDateType) {
            DateType.DAY -> Core.code.getPackagesByDay(currentDate.timeInMillis)
//            DateType.WEEK -> Core.code.getPackagesByWeek(currentDate.timeInMillis)
//            DateType.MONTH -> Core.code.getPackagesByMonth(currentDate.timeInMillis)
//            DateType.YEAR -> Core.code.getPackagesByYear(currentDate.timeInMillis)
            DateType.WEEK -> TODO()
            DateType.MONTH -> TODO()
            DateType.YEAR -> TODO()
        }
        packageAdapter.updatePackages(packages)
        binding.textPackageCount.text = "${packageAdapter.itemCount}个"
    }
    private fun observePackages() {
        viewModel.getPackages(
            currentDate.timeInMillis,
            currentDateType.name
        ).observe(viewLifecycleOwner) { packages ->
            when (currentDateType) {
                DateType.WEEK -> {
                    // 更新图表数据
                    updateBarChartData()
                    updatePieChartData()
                }
                else -> {
                packageAdapter.updatePackages(packages)
            }
            }
            binding.textPackageCount.text = "${packages.size}个"
        }
    }
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}