/*
 *
 * Copyright (c) 2025. Jeffery Hsu - Achievement Report Generator
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 *
 */

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { ICourse, IGoal, IStudent } from '@renderer/types'
import { ElMessage } from 'element-plus'

export const useGlobalStore = defineStore('global', () => {
  const courseInfo = ref<ICourse | null>(null)
  const studentList = ref<IStudent[]>([])
  const goals = ref<IGoal[]>([])

  function saveCourseInfo(new_course: ICourse) {
    courseInfo.value = new_course
  }

  function clearCourseInfo() {
    courseInfo.value = null
  }

  async function createCourseFromXlsx(): Promise<boolean> {
    const wb = await window.electron.readXLSX()
    if (wb === null) {
      ElMessage({
        type: 'error',
        message: '无法打开文件'
      })
      return false
    }

    const sheet = wb.Sheets['Sheet1']
    if (!sheet) {
      ElMessage({
        type: 'error',
        message: '没有名为 Sheet1 的工作簿，请检查文件是否正确'
      })
      return false
    }

    studentList.value = []
    const classList: string[] = []

    for (let i = 6; ; i++) {
      if (sheet[`A${i}`] === undefined) {
        break
      }

      const stu = {
        className: sheet[`E${i}`]['v'],
        major: sheet[`D${i}`]['v'],
        name: sheet[`C${i}`]['v'],
        resitTag: false,
        serialNumber: sheet[`B${i}`]['v']
      }

      if (!classList.includes(stu.className)) {
        classList.push(stu.className)
      }

      studentList.value.push(stu)
    }

    let classStr = ''
    if (classList.length > 0) {
      // 假设字符串格式为：两位数字 + 非空白字符（基础部分），后面紧跟中文括号括起的数字部分
      const reg = /^([0-9]{2}\S+?)（(\d+)）$/
      const firstMatch = classList[0].match(reg)
      if (!firstMatch) {
        classStr = ''
        for (let i = 0; i < classList.length; i++) {
          classStr += classList[i]
          if (i !== classList.length - 1) {
            classStr += '、'
          }
        }
      } else {
        const base = firstMatch[1]
        const startNum = parseInt(firstMatch[2], 10)

        // 合并后保留一个基础部分，并按数组长度顺序拼接递增的括号数字
        classStr = base
        for (let i = 0; i < classList.length; i++) {
          classStr += `（${startNum + i}）`
        }
      }
    }

    courseInfo.value = {
      campus: sheet['A4']['v'].split('：')[1],
      className: classStr,
      credit: parseFloat(sheet['E4']['v'].split('：')[1]),
      id: sheet['A3']['v'].split('：')[1],
      master: '',
      name: sheet['E3']['v'].split('：')[1],
      teacher: sheet['D4']['v'].split('：')[1]
    }
    return true
  }

  return { courseInfo, saveCourseInfo, clearCourseInfo, createCourseFromXlsx, studentList, goals }
})
