个人作业Android学习系统开发日志七

最后逻辑实现:
MainActivity:

package com.example.learningmanagement.ui

import android.os.Bundle
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.example.learningmanagement.R
import com.example.learningmanagement.entity.WeekGoals
import com.example.learningmanagement.entity.DailySummary
import com.example.learningmanagement.entity.CodeLog
import com.example.learningmanagement.network.ServiceCreater
import com.example.learningmanagement.service.WeekGoalsService
import com.example.learningmanagement.service.DailySummaryService
import com.example.learningmanagement.service.CodeLogService
import com.example.learningmanagement.ui.fragment.WeekGoalsFragment
import com.example.learningmanagement.ui.fragment.DailySummaryFragment
import com.example.learningmanagement.utils.PrefsHelper
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.lifecycle.lifecycleScope
import com.example.learningmanagement.ui.fragment.CodeLogFragment
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone

class MainActivity : AppCompatActivity() {

    private lateinit var bottomNav: BottomNavigationView
    private lateinit var btnAdd: ImageButton
    private lateinit var btnDelete: ImageButton
    private val prefs by lazy { PrefsHelper(this) }
    private val weekGoalsService = ServiceCreater.create<WeekGoalsService>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        bottomNav = findViewById(R.id.bottom_nav)
        btnAdd = findViewById(R.id.btnAdd)
        btnDelete = findViewById(R.id.btnDelete)

        // 设置添加按钮点击事件
        // 设置添加按钮点击事件
        btnAdd.setOnClickListener {
            // 获取当前显示的Fragment
            val currentFragment = supportFragmentManager.findFragmentById(R.id.content_frame)

            // 根据当前Fragment类型执行不同的添加操作
            when (currentFragment) {
                is WeekGoalsFragment -> showAddWeekGoalDialog()
                is DailySummaryFragment -> showAddDailySummaryDialog()
                is CodeLogFragment -> showAddCodeLogDialog()
                else -> Toast.makeText(this, "当前页面不支持添加操作", Toast.LENGTH_SHORT).show()
            }
        }

        // 在 MainActivity 的 onCreate 方法中添加
        btnDelete.setOnClickListener {
            // 获取当前显示的 Fragment
            val currentFragment = supportFragmentManager.findFragmentById(R.id.content_frame)

            // 如果当前 Fragment 是 WeekGoalsFragment,则调用其删除方法
            if (currentFragment is WeekGoalsFragment) {
                currentFragment.deleteCurrentGoal()
            }
        }

        // 修改底部导航栏点击事件处理
        bottomNav.setOnItemSelectedListener { menuItem ->
            when (menuItem.itemId) {
                R.id.nav_weekly -> {
                    loadFragment(WeekGoalsFragment())
                    true
                }

                R.id.nav_daily -> {
                    // 加载日总结Fragment
                    loadFragment(DailySummaryFragment())
                    true
                }

                R.id.nav_code -> {
                    // 加载编程记录Fragment
                    loadFragment(CodeLogFragment())
                    true
                }

                R.id.nav_profile -> {
                    // 暂时显示占位信息
                    Toast.makeText(this, "个人中心功能开发中...", Toast.LENGTH_SHORT).show()
                    true
                }

                else -> false
            }
        }

        // 默认选中周目标页面并加载
        if (savedInstanceState == null) {
            loadFragment(WeekGoalsFragment())
            bottomNav.selectedItemId = R.id.nav_weekly
        }

    }

    // 添加周目标对话框
    private fun showAddWeekGoalDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_week_goal, null)
        val etWeekNumber = dialogView.findViewById<EditText>(R.id.etWeekNumber)
        val etTitle = dialogView.findViewById<EditText>(R.id.etTitle)
        val etContent = dialogView.findViewById<EditText>(R.id.etContent)

        AlertDialog.Builder(this)
            .setTitle("添加周目标")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                val weekNumber = etWeekNumber.text.toString().trim()
                val title = etTitle.text.toString().trim()
                val content = etContent.text.toString().trim()

                if (weekNumber.isEmpty() || title.isEmpty() || content.isEmpty()) {
                    Toast.makeText(this, "所有字段都必须填写", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }

                // 保存周目标
                saveWeekGoal(weekNumber.toInt(), title, content)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    // 保存周目标到服务器
    private fun saveWeekGoal(weekNumber: Int, title: String, content: String) {
        lifecycleScope.launch {
            try {
                val userId = prefs.getUserId()
                if (userId != null) {
                    val weekGoal = WeekGoals(
                        id = 0, // 后端会自动生成ID
                        weekNumber = weekNumber,
                        title = title,
                        content = content,
                        userId = userId.toInt()
                    )

                    val response = weekGoalsService.addWeekGoal(weekGoal)
                    if (response.code == "200") {
                        Toast.makeText(this@MainActivity, "添加成功", Toast.LENGTH_SHORT).show()
                        // 刷新周目标列表
                        refreshWeekGoalsFragment()
                    } else {
                        Toast.makeText(
                            this@MainActivity,
                            "添加失败: ${response.msg}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    Toast.makeText(this@MainActivity, "用户未登录", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@MainActivity, "网络错误: ${e.message}", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    // 刷新周目标Fragment
    private fun refreshWeekGoalsFragment() {
        val fragment = supportFragmentManager.findFragmentById(R.id.content_frame)
        if (fragment is WeekGoalsFragment) {
            fragment.refreshData()
        }
    }

    // 加载Fragment
    private fun loadFragment(fragment: Fragment) {
        supportFragmentManager.beginTransaction()
            .replace(R.id.content_frame, fragment)
            .commit()
    }

    // 更新周数标题
    fun updateWeekTitle(title: String) {
        findViewById<TextView>(R.id.tvWeekTitle).text = title
    }

    // 添加日总结对话框
    private fun showAddDailySummaryDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_daily_summary, null)
        val etUrl = dialogView.findViewById<EditText>(R.id.etUrl)

        AlertDialog.Builder(this)
            .setTitle("添加日总结")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                val url = etUrl.text.toString().trim()

                if (url.isEmpty()) {
                    Toast.makeText(this, "URL不能为空", Toast.LENGTH_SHORT).show()
                    return@setPositiveButton
                }

                // 保存日总结
                saveDailySummary(url)
            }
            .setNegativeButton("取消", null)
            .show()
    }

    // 保存日总结到服务器
    private fun saveDailySummary(url: String) {
        lifecycleScope.launch {
            try {
                val userId = prefs.getUserId()
                if (userId != null) {
                    val dailySummaryService = ServiceCreater.create<DailySummaryService>()
                    val dailySummary = DailySummary(
                        id = 0, // 后端会自动生成ID
                        userId = userId.toInt(),
                        url = url
                    )

                    val response = dailySummaryService.addDailySummary(dailySummary)
                    if (response.code == "200") {
                        Toast.makeText(this@MainActivity, "添加成功", Toast.LENGTH_SHORT).show()
                        // 刷新日总结列表
                        refreshDailySummaryFragment()
                    } else {
                        Toast.makeText(
                            this@MainActivity,
                            "添加失败: ${response.msg}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    Toast.makeText(this@MainActivity, "用户未登录", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@MainActivity, "网络错误: ${e.message}", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    // 刷新日总结Fragment
    private fun refreshDailySummaryFragment() {
        val fragment = supportFragmentManager.findFragmentById(R.id.content_frame)
        if (fragment is DailySummaryFragment) {
            fragment.refreshData()
        }
    }

    // 在MainActivity类中添加以下方法(放在类的适当位置)

    // 添加显示编程记录添加对话框的方法
    fun showAddCodeLogDialog() {
        val dialogView = layoutInflater.inflate(R.layout.dialog_add_code_log, null)

        // 设置当前日期
        val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val currentDate = Date()
        val formattedDate = dateFormat.format(currentDate)
        dialogView.findViewById<TextView>(R.id.tvCurrentDate).text = "当前日期: $formattedDate"

        // 获取输入框引用
        val etEstimate = dialogView.findViewById<EditText>(R.id.etEstimate)
        val etAnalysis = dialogView.findViewById<EditText>(R.id.etAnalysis)
        val etCodingStandard = dialogView.findViewById<EditText>(R.id.etCodingStandard)
        val etDesignDetails = dialogView.findViewById<EditText>(R.id.etDesignDetails)
        val etCode = dialogView.findViewById<EditText>(R.id.etCode)
        val etWorkloadMeasurement = dialogView.findViewById<EditText>(R.id.etWorkloadMeasurement)
        val etPostmortemAnalysis = dialogView.findViewById<EditText>(R.id.etPostmortemAnalysis)
        val etImprovementPlan = dialogView.findViewById<EditText>(R.id.etImprovementPlan)
        val etTotalHours = dialogView.findViewById<EditText>(R.id.etTotalHours)

        AlertDialog.Builder(this)
            .setTitle("添加编程记录")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                try {
                    val estimate = etEstimate.text.toString().toDoubleOrNull() ?: 0.0
                    val analysis = etAnalysis.text.toString().trim()
                    val codingStandard = etCodingStandard.text.toString().trim()
                    val designDetails = etDesignDetails.text.toString().trim()
                    val code = etCode.text.toString().trim()
                    val workloadMeasurement = etWorkloadMeasurement.text.toString().trim()
                    val postmortemAnalysis = etPostmortemAnalysis.text.toString().trim()
                    val improvementPlan = etImprovementPlan.text.toString().trim()
                    val totalHours = etTotalHours.text.toString().toDoubleOrNull() ?: 0.0

                    // 保存编程记录
                    saveCodeLog(
                        currentDate, estimate, analysis, codingStandard,
                        designDetails, code, workloadMeasurement,
                        postmortemAnalysis, improvementPlan, totalHours
                    )
                } catch (e: Exception) {
                    Toast.makeText(this, "输入有误: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    // 添加保存编程记录的方法
    private fun saveCodeLog(
        date: Date,
        estimate: Double,
        analysis: String,
        codingStandard: String,
        designDetails: String,
        code: String,
        workloadMeasurement: String,
        postmortemAnalysis: String,
        improvementPlan: String,
        totalHours: Double
    ) {
        lifecycleScope.launch {
            try {
                val userId = prefs.getUserId()
                if (userId != null) {
                    val codeLogService = ServiceCreater.create<CodeLogService>()
                    
                    // 使用GMT+8时区格式化日期
                    val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
                    dateFormat.timeZone = TimeZone.getTimeZone("GMT+8")
                    val formattedDateStr = dateFormat.format(date)
                    val formattedDate = dateFormat.parse(formattedDateStr)
                    
                    val codeLog = CodeLog(
                        id = "", // 后端会自动生成ID
                        date = formattedDate, // 使用格式化后的日期
                        estimate = estimate,
                        analysis = analysis,
                        codingStandard = codingStandard,
                        designDetails = designDetails,
                        code = code,
                        workloadMeasurement = workloadMeasurement,
                        postmortemAnalysis = postmortemAnalysis,
                        improvementPlan = improvementPlan,
                        totalHours = totalHours,
                        userId = userId.toInt()
                    )

                    val response = codeLogService.addCodeLog(codeLog)
                    if (response.code == "200") {
                        Toast.makeText(this@MainActivity, "添加成功", Toast.LENGTH_SHORT).show()
                        // 刷新编程记录列表
                        refreshCodeLogFragment()
                    } else {
                        Toast.makeText(
                            this@MainActivity,
                            "添加失败: ${response.msg}",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                } else {
                    Toast.makeText(this@MainActivity, "用户未登录", Toast.LENGTH_SHORT).show()
                }
            } catch (e: Exception) {
                Toast.makeText(this@MainActivity, "网络错误: ${e.message}", Toast.LENGTH_SHORT)
                    .show()
            }
        }
    }

    // 添加刷新编程记录Fragment的方法
    private fun refreshCodeLogFragment() {
        val fragment = supportFragmentManager.findFragmentById(R.id.content_frame)
        if (fragment is CodeLogFragment) {
            fragment.loadCodeLogs()
        }
    }
}
posted @ 2025-04-07 19:36  vivi_vimi  阅读(13)  评论(0)    收藏  举报