cloudroam
2025-04-16 ca8bc638ba9cbca3f5f6a4d497d45f92e70064f3
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
package com.example.firstapp.ui.home
 
import android.content.Context
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.firstapp.core.Core
import com.example.firstapp.database.service.RetrofitClient
import com.example.firstapp.model.CategoryConfig
import com.example.firstapp.model.CategoryConfigSync
import com.example.firstapp.model.ExpressGroup
import com.example.firstapp.model.ExpressPackage
import com.example.firstapp.model.FinanceGroup
import com.example.firstapp.model.FinancePackage
import com.example.firstapp.model.IncomeGroup
import com.example.firstapp.model.IncomePackage
import com.example.firstapp.util.SecureStorage
import com.example.firstapp.utils.PreferencesManager
import kotlinx.coroutines.launch
import com.example.firstapp.database.repository.ReminderRecordRepository
import com.example.firstapp.database.entity.ReminderRecord
import com.example.firstapp.model.TrainGroup
import com.example.firstapp.model.TrainPackage
import com.example.firstapp.model.FlightGroup
import com.example.firstapp.model.FlightPackage
 
class HomeViewModel : ViewModel() {
 
    private val _expressItems = MutableLiveData<List<ExpressGroup>>()
    private val _financeItems = MutableLiveData<List<FinanceGroup>>()
    private val _incomeItems = MutableLiveData<List<IncomeGroup>>()
    private val _flightItems = MutableLiveData<List<FlightGroup>>()
    private val _trainItems = MutableLiveData<List<TrainGroup>>()
    
    val expressItems: LiveData<List<ExpressGroup>> = _expressItems
    val financeItems: LiveData<List<FinanceGroup>> = _financeItems
    val incomeItems: LiveData<List<IncomeGroup>> = _incomeItems
    val flightItems: LiveData<List<FlightGroup>> = _flightItems
    val trainItems: LiveData<List<TrainGroup>> = _trainItems
 
    private val _categories = MutableLiveData<List<CategoryConfig>>()
    val categories: LiveData<List<CategoryConfig>> = _categories
 
    private val _visibleCategories = MutableLiveData<List<CategoryConfig>>()
    val visibleCategories: LiveData<List<CategoryConfig>> = _visibleCategories
 
    private val _unreadReminderCount = MutableLiveData<Int>()
    val unreadReminderCount: LiveData<Int> = _unreadReminderCount
 
    private lateinit var secureStorage: SecureStorage
    private lateinit var currentUserId: String
    private lateinit var reminderRecordRepository: ReminderRecordRepository
 
    init {
        // 初始化时加载包裹列表数据
        loadExpressData()
        // 初始化时不加载财务列表数据 0317
        //  loadFinanceData()
    }
 
    fun initialize(context: Context, userId: String) {
        secureStorage = SecureStorage(context)
        currentUserId = userId
        reminderRecordRepository = ReminderRecordRepository(context)
        loadCategories()
        // 初始化时更新可见分类
        _categories.value?.let { updateVisibleCategories(it) }
        // 加载未读提醒数量
        checkUnreadReminders()
    }
 
    private fun loadDataByType(type: String) {
        viewModelScope.launch {
            try {
                // 获取该类型下的所有站点分组
                val stations = Core.code.getStationsByType(type)
                
                when (type) {
                    "快递" -> {
                        // 处理快递类型
                        val groups = stations.map { station ->
                            val packages = Core.code.getPackagesByTypeAndStation(type, station.stationName).map { code ->
                                ExpressPackage(
                                    id = code.id,
                                    company = code.secondLevel,
                                    trackingNumber = code.code,
                                    createTime = code.createTime
                                )
                            }
                            ExpressGroup(stationName = station.stationName, packages = packages)
                        }
                        _expressItems.postValue(groups)
                    }
                    "收入" -> {
                        // 特殊处理收入类型
                        val groups = stations.map { station ->
                            val packages = Core.code.getPackagesByTypeAndStation(type, station.stationName).map { code ->
                                IncomePackage(
                                    id = code.id,
                                    company = code.secondLevel,  // 交易对方
                                    trackingNumber = code.code,  // 金额
                                    createTime = code.createTime,
                                    balance = code.remarks.replace("余额", "") // 去掉"余额"前缀
                                )
                            }
                            IncomeGroup(stationName = station.stationName, packages = packages)
                        }
                        _incomeItems.postValue(groups)
                    }
                    "火车票" -> {
                        // 处理火车票类型
                        val groups = stations.map { station ->
                            val packages = Core.code.getPackagesByTypeAndStation(type, station.stationName).map { code ->
                                TrainPackage(
                                    id = code.id,
                                    company = code.secondLevel,
                                    trackingNumber = code.code,
                                    createTime = code.createTime
                                )
                            }
                            TrainGroup(stationName = station.stationName, packages = packages)
                        }
                        _trainItems.postValue(groups)
                    }
                    "航班" -> {
                        // 处理航班类型
                        val groups = stations.map { station ->
                            val packages = Core.code.getPackagesByTypeAndStation(type, station.stationName).map { code ->
                                FlightPackage(
                                    id = code.id,
                                    company = code.secondLevel,
                                    trackingNumber = code.code,
                                    createTime = code.createTime
                                )
                            }
                            FlightGroup(stationName = station.stationName, packages = packages)
                        }
                        _flightItems.postValue(groups)
                    }
                    else -> {
                        // 处理其他类型(还款)
                        val groups = stations.map { station ->
                            val packages = Core.code.getPackagesByTypeAndStation(type, station.stationName).map { code ->
                                FinancePackage(
                                    id = code.id,
                                    company = code.secondLevel,
                                    trackingNumber = code.code,
                                    createTime = code.createTime
                                )
                            }
                            FinanceGroup(stationName = station.stationName, packages = packages)
                        }
                        
                        // 根据类型更新对应的 LiveData
                        when (type) {
                            "还款" -> _financeItems.postValue(groups)
                        }
                    }
                }
            } catch (e: Exception) {
                Log.e("HomeViewModel", "Failed to load $type data: ${e.message}")
            }
        }
    }
 
    fun loadExpressData() {
        loadDataByType("快递")
    }
 
    fun loadFinanceData() {
        loadDataByType("还款")
    }
 
    fun loadIncomeData() {
        loadDataByType("收入")
    }
 
    fun loadFlightData() {
        loadDataByType("航班")
    }
 
    fun loadTrainData() {
        loadDataByType("火车票")
    }
 
    private fun loadCategories() {
        viewModelScope.launch {
            try {
                // 先尝试从本地获取配置
                val localCategories = secureStorage.getCategories(currentUserId)
                
                // 默认完整分类列表
                val fullCategories = listOf(
                    CategoryConfig(1, "快递", 0, true),
                    CategoryConfig(2, "还款", 1, true),
                    CategoryConfig(3, "收入", 2, true),
                    CategoryConfig(4, "航班", 3, true),
                    CategoryConfig(5, "火车票", 4, true)
                )
                
                // 基础分类(非会员可见)
                val basicCategories = listOf(
                    CategoryConfig(1, "快递", 0, true),
                    CategoryConfig(2, "还款", 1, true)
                )
 
                if (localCategories.isNotEmpty()) {
                    // 如果本地有配置,直接使用本地配置
                    _categories.value = localCategories
                } else {
                    try {
                        // 尝试从服务器获取用户信息判断是否是会员
                        val savedPhone = PreferencesManager.getPhone()
                        val response = RetrofitClient.apiService.getUserInfo(savedPhone ?: "")
                        val isMember = response.code == "0" && response.data?.isMember == true
 
                        // 根据会员状态设置默认分类
                        val defaultCategories = if (isMember) fullCategories else basicCategories
                        _categories.value = defaultCategories
                        secureStorage.saveCategories(currentUserId, defaultCategories)
                        
                        // 同步到服务器
                        try {
                            syncCategoriesToServer(defaultCategories)
                        } catch (e: Exception) {
                            Log.e("HomeViewModel", "Failed to sync categories: ${e.message}")
                        }
                    } catch (e: Exception) {
                        // 如果获取用户信息失败,使用基础分类
                        _categories.value = basicCategories
                        secureStorage.saveCategories(currentUserId, basicCategories)
                    }
                }
                
                // 更新可见分类
                _categories.value?.let { updateVisibleCategories(it) }
                
            } catch (e: Exception) {
                Log.e("HomeViewModel", "Failed to load categories: ${e.message}")
            }
        }
    }
 
    private fun syncCategoriesToServer(categories: List<CategoryConfig>) {
        viewModelScope.launch {
            try {
                RetrofitClient.apiService.saveUserCategories(
                    CategoryConfigSync(currentUserId, categories)
                )
            } catch (e: Exception) {
                // 同步失败,可以稍后重试或者显示提示
                Log.e("CategorySync", "Failed to sync categories: ${e.message}")
            }
        }
    }
 
    fun saveCategories(categories: List<CategoryConfig>) {
        _categories.value = categories
        // 保存到本地存储
        secureStorage.saveCategories(currentUserId, categories)
        // 同步到服务器
        syncCategoriesToServer(categories)
        // 更新可见分类
        updateVisibleCategories(categories)
    }
 
    private fun updateVisibleCategories(categories: List<CategoryConfig>) {
        val visibleNames = categories
            .filter { it.isEnabled }
            .sortedBy { it.order }
            .map { it.name }
        
        _visibleCategories.value = categories.filter { it.isEnabled }
    }
 
    // 添加检查未读提醒数量的方法
    fun checkUnreadReminders() {
        viewModelScope.launch {
            try {
                val unreadCount = reminderRecordRepository.getUnreadCount(ReminderRecord.STATUS_UNREAD)
                _unreadReminderCount.postValue(unreadCount)
            } catch (e: Exception) {
                Log.e("HomeViewModel", "Failed to get unread reminder count: ${e.message}")
            }
        }
    }
 
    // 登出时不再清除本地数据
    fun logout() {
        // 只清除内存中的数据
        _categories.value = emptyList()
    }
 
}