日报2025313

今日继续学习AS组件使用,实现分页

package com.example.sanpaias.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.example.sanpaias.R
import com.example.sanpaias.activity.DeviceListActivity
import com.example.sanpaias.activity.InspectionListActivity
import com.example.sanpaias.activity.InspectionPlanListActivity
import com.example.sanpaias.activity.MaintenancePlanListActivity
import com.example.sanpaias.activity.OrderApprovalActivity
import com.example.sanpaias.activity.PendingTasksActivity
import com.example.sanpaias.activity.TestingPlanListActivity
import com.example.sanpaias.network.RetrofitClient
import com.google.gson.Gson
import com.google.gson.JsonObject
import kotlinx.coroutines.launch

class HomeFragment : Fragment() {

    private lateinit var tvTotalDevices: TextView
    private lateinit var tvNormalDevices: TextView
    private lateinit var tvFaultDevices: TextView
    private lateinit var cardDeviceStats: CardView
    private lateinit var cardTaskOverview: CardView
    private lateinit var tvPendingTasks: TextView
    private lateinit var tvProcessingTasks: TextView
    private lateinit var tvCompletedTasks: TextView
    
    // 添加工单审批相关的TextView
    private lateinit var tvRepairOrderCount: TextView
    private lateinit var tvInspectionOrderCount: TextView
    private lateinit var tvMaintenanceOrderCount: TextView
    private lateinit var tvTestingOrderCount: TextView

    // 添加巡检相关视图
    private lateinit var cardInspection: CardView
    private lateinit var tvPendingInspections: TextView
    private lateinit var tvCompletedInspections: TextView

    // 添加保养计划相关视图
    private lateinit var cardMaintenancePlan: CardView
    private lateinit var tvPendingMaintenances: TextView
    private lateinit var tvCompletedMaintenances: TextView

    // 添加检测计划相关视图
    private lateinit var cardTestingPlan: CardView
    private lateinit var tvPendingTestings: TextView
    private lateinit var tvCompletedTestings: TextView

    // 添加获取用户信息的私有方法
    private fun getUserInfo(): Pair<String, String> {
        val userJson = requireActivity().getSharedPreferences("user_prefs", 0).getString("user_info", null)
        return if (!userJson.isNullOrEmpty()) {
            try {
                val userObject = Gson().fromJson(userJson, JsonObject::class.java)
                val username = userObject.get("username")?.asString ?: "用户"
                val role = userObject.get("role")?.asString ?: ""
                Pair(username, role)
            } catch (e: Exception) {
                e.printStackTrace()
                Pair("用户", "")
            }
        } else {
            Pair("用户", "")
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home, container, false)
        
        // 初始化视图
        tvTotalDevices = view.findViewById(R.id.tvTotalDevices)
        tvNormalDevices = view.findViewById(R.id.tvNormalDevices)
        tvFaultDevices = view.findViewById(R.id.tvFaultDevices)
        cardDeviceStats = view.findViewById(R.id.cardDeviceStats)
        cardTaskOverview = view.findViewById(R.id.cardTaskOverview)
        tvPendingTasks = view.findViewById(R.id.tvPendingTasks)
        tvProcessingTasks = view.findViewById(R.id.tvProcessingTasks)
        tvCompletedTasks = view.findViewById(R.id.tvCompletedTasks)
        
        // 初始化工单审批相关视图
        val cardOrderApproval = view.findViewById<CardView>(R.id.cardOrderApproval)
        tvRepairOrderCount = view.findViewById(R.id.tvRepairOrderCount)
        tvInspectionOrderCount = view.findViewById(R.id.tvInspectionOrderCount)
        tvMaintenanceOrderCount = view.findViewById(R.id.tvMaintenanceOrderCount)
        tvTestingOrderCount = view.findViewById(R.id.tvTestingOrderCount)
        
        // 初始化巡检卡片
        cardInspection = view.findViewById(R.id.cardInspection)
        tvPendingInspections = view.findViewById(R.id.tvPendingInspections)
        tvCompletedInspections = view.findViewById(R.id.tvCompletedInspections)
        
        // 初始化保养计划卡片
        cardMaintenancePlan = view.findViewById(R.id.cardMaintenancePlan)
        tvPendingMaintenances = view.findViewById(R.id.tvPendingMaintenances)
        tvCompletedMaintenances = view.findViewById(R.id.tvCompletedMaintenances)

        cardTestingPlan = view.findViewById(R.id.cardTestingPlan)
        tvPendingTestings = view.findViewById(R.id.tvPendingTestings)
        tvCompletedTestings = view.findViewById(R.id.tvCompletedTestings)
        
        // 使用新的获取用户信息方法
        val (username, role) = getUserInfo()
        
        // 根据角色决定是否显示任务概览、工单审批和巡检卡片
        if (role == "admin") {
            cardTaskOverview.visibility = View.GONE
            cardOrderApproval.visibility = View.VISIBLE
            cardInspection.visibility = View.VISIBLE
            cardMaintenancePlan.visibility = View.VISIBLE
            cardTestingPlan.visibility = View.VISIBLE
        } else if (role == "engineer") {
            cardTaskOverview.visibility = View.VISIBLE
            cardOrderApproval.visibility = View.GONE
            cardInspection.visibility = View.GONE
            cardMaintenancePlan.visibility = View.GONE
            cardTestingPlan.visibility = View.GONE
        }
        
        val welcomeText = "欢迎您,$username"
        view.findViewById<TextView>(R.id.tvWelcome)?.text = welcomeText
        
        // 加载数据
        loadDashboardData()
        
        // 设置点击事件
        cardDeviceStats.setOnClickListener {
            val intent = Intent(requireContext(), DeviceListActivity::class.java)
            startActivity(intent)
        }
        
        cardTaskOverview.setOnClickListener {
            val intent = Intent(requireContext(), PendingTasksActivity::class.java)
            startActivity(intent)
        }
        
        // 添加工单审批卡片点击事件
        cardOrderApproval?.setOnClickListener {
            val intent = Intent(requireContext(), OrderApprovalActivity::class.java)
            startActivity(intent)
        }
        
        // 添加巡检卡片点击事件
        cardInspection.setOnClickListener {
            val intent = Intent(requireContext(), InspectionPlanListActivity::class.java)
            startActivity(intent)
        }
        
        // 在现有的巡检计划卡片点击事件后添加
        cardMaintenancePlan.setOnClickListener {
            val intent = Intent(requireContext(), MaintenancePlanListActivity::class.java)
            startActivity(intent)
        }

        cardTestingPlan.setOnClickListener {
            val intent = Intent(requireContext(), TestingPlanListActivity::class.java)
            startActivity(intent)
        }
        
        return view
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        // 加载巡检统计数据
        loadInspectionStats()
    }
    
    // 添加加载巡检统计数据的方法
    private fun loadInspectionStats() {
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getInspectionPlanList()
                if (response.isSuccessful && response.body()?.code == 200) {
                    val plans = response.body()?.data ?: emptyList()
                    
                    // 统计启用和停用的数量
                    val enabledCount = plans.count { it.status == "启用" }
                    val disabledCount = plans.count { it.status == "停用" }
                    
                    // 更新UI显示
                    tvPendingInspections.text = enabledCount.toString()
                    tvCompletedInspections.text = disabledCount.toString()
                } else {
                    Log.e("HomeFragment", "获取巡检计划失败: ${response.message()}")
                }
            } catch (e: Exception) {
                Log.e("HomeFragment", "加载巡检统计异常", e)
            }
        }
    }
    // 在loadInspectionPlanStats方法后添加
    private fun loadMaintenancePlanStats() {
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getMaintenancePlanList()
                if (response.isSuccessful && response.body()?.code == 200) {
                    val plans = response.body()?.data ?: emptyList()
                    val enabledCount = plans.count { it.status == "启用" }
                    val disabledCount = plans.count { it.status == "停用" || it.status == "待启用" }

                    tvPendingMaintenances.text = enabledCount.toString()
                    tvCompletedMaintenances.text = disabledCount.toString()
                }
            } catch (e: Exception) {
                Log.e("HomeFragment", "加载保养计划统计失败", e)
            }
        }
    }
    
    // 在loadDashboardData方法中添加巡检数据加载
    private fun loadDashboardData() {
        // 从API获取设备数据
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getAllDevices()
                if (response.isSuccessful) {
                    val apiResponse = response.body()
                    if (apiResponse?.code == 200) {
                        val devices = apiResponse.data ?: emptyList()
                        
                        // 更新UI
                        tvTotalDevices.text = devices.size.toString()
                        tvNormalDevices.text = devices.count { it.status == "正常" }.toString()
                        tvFaultDevices.text = devices.count { it.status == "故障" }.toString()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                // 使用默认数据
                tvTotalDevices.text = "0"
                tvNormalDevices.text = "0"
                tvFaultDevices.text = "0"
            }
        }
        
        // 使用getUserInfo方法获取用户角色
        val (username, role) = getUserInfo()
        
        // 只有工程师才加载任务数据
        if (role == "engineer") {
            loadEngineerTaskData()
        }
        
        // 管理员才加载工单审批数据
        if (role == "admin") {
            loadOrderApprovalData()
            // 加载巡检统计数据
            loadInspectionStats()
            // 加载保养计划统计数据
            loadMaintenancePlanStats()

            loadTestingPlanStats()
        }
        
        // 更新欢迎文本
        val welcomeText = "欢迎您,$username"
        view?.findViewById<TextView>(R.id.tvWelcome)?.text = welcomeText
    }

    private fun loadTestingPlanStats() {
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getTestingPlanList()
                if (response.isSuccessful && response.body()?.code == 200) {
                    val plans = response.body()?.data ?: emptyList()
                    val enabledCount = plans.count { it.status == "启用" }
                    val disabledCount = plans.count { it.status == "停用" || it.status == "待启用" }

                    tvPendingTestings.text = enabledCount.toString()
                    tvCompletedTestings.text = disabledCount.toString()
                }
            } catch (e: Exception) {
                Log.e("HomeFragment", "加载检测计划统计失败", e)
            }
        }
    }
    
    // 新增:专门为工程师加载任务数据的方法
    private fun loadEngineerTaskData() {
        lifecycleScope.launch {
            try {
                var pendingCount = 0
                var processingCount = 0
                var completedCount = 0
                
                // 获取维修工单
                val repairResponse = RetrofitClient.instance.getRepairOrderList()
                if (repairResponse.isSuccessful && repairResponse.body()?.code == 200) {
                    val repairOrders = repairResponse.body()?.data ?: emptyList()
                    pendingCount += repairOrders.count { it.status == "待处理" }
                    processingCount += repairOrders.count { it.status == "处理中" }
                    completedCount += repairOrders.count { it.status == "已完成" }
                }
                
                // 获取巡检工单
                val inspectionResponse = RetrofitClient.instance.getInspectionOrderList()
                if (inspectionResponse.isSuccessful && inspectionResponse.body()?.code == 200) {
                    val inspectionOrders = inspectionResponse.body()?.data ?: emptyList()
                    pendingCount += inspectionOrders.count { it.status == "待处理" }
                    processingCount += inspectionOrders.count { it.status == "处理中" }
                    completedCount += inspectionOrders.count { it.status == "已完成" }
                }
                
                // 获取保养工单
                val maintenanceResponse = RetrofitClient.instance.getMaintenanceOrderList()
                if (maintenanceResponse.isSuccessful && maintenanceResponse.body()?.code == 200) {
                    val maintenanceOrders = maintenanceResponse.body()?.data ?: emptyList()
                    pendingCount += maintenanceOrders.count { it.status == "待处理" }
                    processingCount += maintenanceOrders.count { it.status == "处理中" }
                    completedCount += maintenanceOrders.count { it.status == "已完成" }
                }
                
                // 获取检测工单
                val testingResponse = RetrofitClient.instance.getTestingOrderList()
                if (testingResponse.isSuccessful && testingResponse.body()?.code == 200) {
                    val testingOrders = testingResponse.body()?.data ?: emptyList()
                    pendingCount += testingOrders.count { it.status == "待处理" }
                    processingCount += testingOrders.count { it.status == "处理中" }
                    completedCount += testingOrders.count { it.status == "已完成" }
                }
                
                // 更新UI
                tvPendingTasks.text = pendingCount.toString()
                tvProcessingTasks.text = processingCount.toString()
                tvCompletedTasks.text = completedCount.toString()
                
            } catch (e: Exception) {
                e.printStackTrace()
                // 使用默认数据
                tvPendingTasks.text = "0"
                tvProcessingTasks.text = "0"
                tvCompletedTasks.text = "0"
            }
        }
    }
    
    // 添加加载工单审批数据的方法
    private fun loadOrderApprovalData() {
        // 加载维修工单数据
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getRepairOrderList()
                if (response.isSuccessful) {
                    val apiResponse = response.body()
                    if (apiResponse?.code == 200) {
                        val orders = apiResponse.data ?: emptyList()
                        // 只统计待审批的工单
                        val pendingApprovalCount = orders.count { it.status == "待审批" }
                        tvRepairOrderCount.text = pendingApprovalCount.toString()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                tvRepairOrderCount.text = "0"
            }
        }
        
        // 加载巡检工单数据
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getInspectionOrderList()
                if (response.isSuccessful) {
                    val apiResponse = response.body()
                    if (apiResponse?.code == 200) {
                        val orders = apiResponse.data ?: emptyList()
                        // 只统计待审批的工单
                        val pendingApprovalCount = orders.count { it.status == "待审批" }
                        tvInspectionOrderCount.text = pendingApprovalCount.toString()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                tvInspectionOrderCount.text = "0"
            }
        }
        
        // 加载保养工单数据
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getMaintenanceOrderList()
                if (response.isSuccessful) {
                    val apiResponse = response.body()
                    if (apiResponse?.code == 200) {
                        val orders = apiResponse.data ?: emptyList()
                        // 只统计待审批的工单
                        val pendingApprovalCount = orders.count { it.status == "待审批" }
                        tvMaintenanceOrderCount.text = pendingApprovalCount.toString()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                tvMaintenanceOrderCount.text = "0"
            }
        }
        
        // 加载检测工单数据
        lifecycleScope.launch {
            try {
                val response = RetrofitClient.instance.getTestingOrderList()
                if (response.isSuccessful) {
                    val apiResponse = response.body()
                    if (apiResponse?.code == 200) {
                        val orders = apiResponse.data ?: emptyList()
                        // 只统计待审批的工单
                        val pendingApprovalCount = orders.count { it.status == "待审批" }
                        tvTestingOrderCount.text = pendingApprovalCount.toString()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                tvTestingOrderCount.text = "0"
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次回到页面时刷新数据
        loadDashboardData()
    }
}


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.dashboard.DashboardActivity">

    <FrameLayout
        android:id="@+id/fragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/bottomNavigation"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNavigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

posted @ 2025-03-13 22:18  花落水无痕  阅读(18)  评论(0)    收藏  举报