/* eslint-disable @typescript-eslint/prefer-for-of */
import type { BookVersion, Clean, TextBook } from './subject'

const _getBookColor = (bookName: string) => {
  let index = bookVersionNames.length - 1
  let stop = false
  // 看一下bookName包含bookVersionNames的哪一个
  for (let i = 0; i < bookVersionNames.length; i++) {
    for (let j = 0; j < bookVersionNames[i].length; j++) {
      if (bookName.indexOf(bookVersionNames[i][j]) !== -1) {
        index = i
        stop = true
        break
      }
    }
    if (stop) {
      break
    }
  }
  return bookColors[index]
}

const TAGS = ['五四', '六三', '课改']
const replaced_tags: any = {
  五四制: '五四',
  六三制: '六三',
  '-广州用': '(广州)',
  '(北京课改版)': '(课改版)',
  '-开心学英语': '(开心学英语)',
  一起: '(一年级起点)',
  三起: '(三年级起点)',
  新启航: '(新启航)',
  新视角: '(新视角)',
  新交际: '(新交际)',
}
// 处理名字,分割成标签、非标签
const _processName = (name: string) => {
  // 先统一括号为英文括号
  name = name.replace(/（/g, '(').replace(/）/g, ')')

  // 替换
  for (const key in replaced_tags) {
    name = name.replace(key, replaced_tags[key])
  }

  // 区分
  const data: {
    tags: string[]
    name: string
  } = {
    tags: [],
    name,
  }

  // 如果名字里面带有括号
  const bracket: any = Array.from(name.matchAll(/\(([^\）]*?)\)/g), match => match[1])
  if (bracket) {
    data.tags = bracket
    for (const b of bracket) {
      name = name.replace(`(${b})`, '')
    }
    data.name = name
  }

  // 先处理标签
  for (const tag of TAGS) {
    const idx = name.indexOf(tag)
    if (idx === -1) continue
    data.tags.push(tag)
    data.name = name.slice(0, idx) + name.slice(idx + tag.length)
    break
  }

  // 有些标签包含了/
  if (data.tags) {
    let newTags: any = []
    for (const tag of data.tags) {
      newTags = [...newTags, ...tag.split('/')]
    }
    newTags.sort()
    data.tags = newTags
  }

  // // 去掉括号
  // if (data.tag.startsWith('(')) {
  //     data.tag = data.tag.slice(1, -1)
  // }
  return data
}

const _processObj = (obj: any) => {
  const sourceName = obj?.clean?.name || ''
  const name = _processName(sourceName)
  obj.clean.tags = name.tags || []
  obj.clean.name = name.name || sourceName
}

const _longest = (...args: string[]) => {
  let size = 0
  let longest = ''
  for (const arg of args) {
    if (!arg) continue
    if (arg.length > size) {
      size = arg.length
      longest = arg
    }
  }
  return longest
}

// 清洗一下版本数据
export const cleanVersions = (versions: BookVersion[]) => {
  for (const version of versions) {
    version.clean = {} as Clean
    // 设置名字
    version.clean.name = version.shortName || version.name
    // 处理对象
    _processObj(version)
    // 处理书本
    for (const book of version.textBookVoList) {
      book.clean = {} as Clean
      // 设置名字
      if (version.clean.tags?.length) {
        book.clean.name = book.displayName || book.shortName || book.name
      } else {
        book.clean.name = _longest(book.name, book.displayName, book.shortName)
      }
      // 处理对象
      _processObj(book)
      // 全名
      book.clean.fullName = _getBookName(book, version)
      // 覆盖颜色
      book.clean.color = _getBookColor(book.clean.fullName!)
      version.clean.color = book.clean.color
      // 去除不必要的tag
      if (book.clean.tags?.length) {
        book.clean.tags = book.clean.tags.filter((tag: string) => {
          // 如果跟版本名字相同，直接去掉
          return tag !== version.clean.name
        })
      }

      // 合并tag
      book.clean.all_tags = [
        ...new Set([...(book.clean?.tags || []), ...(version.clean?.tags || [])]),
      ]
    }
  }
}

// 清洗一下教材数据
export const cleanBooks = (books: TextBook[]) => {
  for (const book of books) {
    book.clean = {} as Clean
    book.version = {
      clean: {} as Clean,
    } as BookVersion
    // 设置名字
    book.clean.name = book.textBookName
    book.version.clean.name = book.bookVersionName || book.versionName

    // 处理对象
    _processObj(book)
    _processObj(book.version)

    // 全名
    book.clean.fullName = _getBookName(book, book.version)
    book.clean.color = _getBookColor(book.clean.fullName!)
    book.version.clean.color = book.clean.color
    // 去除不必要的tag
    if (book.clean.tags?.length) {
      book.clean.tags = book.clean.tags.filter((tag: string) => {
        // 如果跟版本名字相同，直接去掉
        return tag !== book.version.clean.name
      })
    }
    // 合并tag
    book.clean.all_tags = [
      ...new Set([...(book.clean.tags || []), ...(book.version.clean.tags || [])]),
    ]
  }
}

const _escapeRegExp = (text: string) => {
  return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

const _trimRegex = (source: string, regex: string) => {
  const safeRegex = _escapeRegExp(regex || '')
  const reg = new RegExp(`\\s*${safeRegex}\\s*`, 'g')
  return source.replace(reg, '')
}

// 需要去掉的名字
const trim_names = ['人教版数学', '沪教版', '小学', '英语', '少儿']

// 获取书本名字
const _getBookName = (book: any, version: any) => {
  // 第1步：去掉书本名字中的教材版本名字
  for (const name of trim_names) {
    book.clean.name = _trimRegex(book.clean.name, name)
  }
  book.clean.name = _trimRegex(book.clean.name, version.clean.name)

  // 第2步
  let name = version.clean.name
  const tags = version.clean.tags || []
  const step = '·'
  if (tags.length) {
    name += step + tags.join(step)
  }
  name += '·' + book.clean.name
  return name
}

const bookVersionNames = [
  ['人', '编'],
  ['辽', '陕', '鲁', '青'],
  ['北', '冀', '清', '河'],
  ['苏', '浙', '沪', '杭', '上海'],
  ['鄂', '湘', '闽', '湖', '福'],
  ['重', '渝', '川'],
  ['粤', '桂', '琼', '广'],
  ['五四', '六三'],
  ['大象', '接力', '仁', '译'],
  ['外', 'W', '牛津', '剑桥', '朗文'],
  ['新', '起点'],
  ['大学', '科', '师'],
]

const bookColors = [
  {
    // 深绿
    color: '#21CC18',
    bgColor: '#93F28D',
  },
  {
    // 卡其
    color: '#C7B767',
    bgColor: '#DBD5B8',
  },
  {
    // 深蓝
    color: '#04A6FF',
    bgColor: '#20CDFF',
  },
  {
    // 浅紫
    color: '#967ACC',
    bgColor: '#C4B8DB',
  },
  {
    // 米黄色
    color: '#FF7438',
    bgColor: '#FFC49F',
  },
  {
    // 红褐色
    color: '#FF6363',
    bgColor: '#FF9F9F',
  },
  {
    // 蓝紫色
    color: '#5B5DFF',
    bgColor: '#989AFF',
  },
  {
    // 深紫色
    color: '#AB5CFF',
    bgColor: '#D199FF',
  },
  {
    // 蓝色
    color: '#5C89FF',
    bgColor: '#99BBFF',
  },
  {
    // 黄色
    color: '#E5B000',
    bgColor: '#FCEB5B',
  },
  {
    // 粉灰色
    color: '#CC7A8D',
    bgColor: '#DBC1C7',
  },
  {
    // 粉紫
    color: '#FC5EC9',
    bgColor: '#FF99E1',
  },
  {
    // 紫色
    color: '#FF5CFF',
    bgColor: '#FF99FF',
  },
  {
    // 浅绿
    color: '#6BD600',
    bgColor: '#CCF37C',
  },
  {
    // 天蓝
    color: '#00C7D6',
    bgColor: '#45ECF5',
  },
]

// 年级
const grade_1 = 1
const grade_2 = 2
const grade_3 = 3
const grade_4 = 4
const grade_5 = 5
const grade_6 = 6
const grade_7 = 7
const grade_8 = 8
const grade_9 = 9
const grade_high_1 = 10
const grade_high_2 = 11
const grade_high_3 = 12
const xiaoxue = [grade_1, grade_2, grade_3, grade_4, grade_5, grade_6]
const chuzhong = [grade_7, grade_8, grade_9]
const gaozhong = [grade_high_1, grade_high_2, grade_high_3]
const grade_map: any = {
  [grade_1]: '一年级',
  [grade_2]: '二年级',
  [grade_3]: '三年级',
  [grade_4]: '四年级',
  [grade_5]: '五年级',
  [grade_6]: '六年级',
  [grade_7]: '七年级',
  [grade_8]: '八年级',
  [grade_9]: '九年级',
  [grade_high_1]: '高一',
  [grade_high_2]: '高二',
  [grade_high_3]: '高三',
}

const base_grade_1 = 1
const base_grade_2 = 2
const base_grade_3 = 3
const base_grade_4 = 4
const base_grade_5 = 5
const base_grade_6 = 6
const base_grade_7 = 7
const base_grade_8 = 8
const base_grade_9 = 9
const base_grade_high_1 = 10
const base_grade_high_2 = 11
const base_grade_high_3 = 12
const base_grade_map: any = {
  [base_grade_1]: grade_1,
  [base_grade_2]: grade_2,
  [base_grade_3]: grade_3,
  [base_grade_4]: grade_4,
  [base_grade_5]: grade_5,
  [base_grade_6]: grade_6,
  [base_grade_7]: grade_7,
  [base_grade_8]: grade_8,
  [base_grade_9]: grade_9,
  [base_grade_high_1]: grade_high_1,
  [base_grade_high_2]: grade_high_2,
  [base_grade_high_3]: grade_high_3,
}

export const grades = [
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '1',
    baseId: '1',
    name: '一年级',
    sort: 0,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '2',
    baseId: '2',
    name: '二年级',
    sort: 1,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '3',
    baseId: '3',
    name: '三年级',
    sort: 2,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '4',
    baseId: '4',
    name: '四年级',
    sort: 3,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '5',
    baseId: '5',
    name: '五年级',
    sort: 4,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '6',
    baseId: '6',
    name: '六年级',
    sort: 5,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '7',
    baseId: '7',
    name: '七年级',
    sort: 7,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '8',
    baseId: '8',
    name: '八年级',
    sort: 8,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '9',
    baseId: '9',
    name: '九年级',
    sort: 9,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '10',
    baseId: '10',
    name: '高一',
    sort: 10,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '11',
    baseId: '11',
    name: '高二',
    sort: 11,
    delFlag: 0,
  },
  {
    createTime: '2024-08-28 14:57:45',
    createUser: '-1',
    updateTime: '2024-08-28 14:57:45',
    updateUser: '-1',
    id: '12',
    baseId: '12',
    name: '高三',
    sort: 12,
    delFlag: 0,
  },
]

// 阶段
export const stage_xiaoxue = 1
export const stage_chuzhong = 2
export const stage_gaozhong = 3
export const stage_options = [
  {
    label: '小学',
    value: stage_xiaoxue,
  },
  {
    label: '初中',
    value: stage_chuzhong,
  },
  {
    label: '高中',
    value: stage_gaozhong,
  },
]

// 类型
export type SubjectItem = {
  subjectId: any
  name: string
  subject: string
  pictureUrl: string
  sort: any
}

// 学科
const chinese_subject_id = 1
const math_subject_id = 2
const english_subject_id = 3
export const subject_english = {
  subjectId: english_subject_id,
  name: '英语',
  subject: '英语',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_yingyu.png',
  sort: null,
} as SubjectItem
export const subject_chinese = {
  subjectId: chinese_subject_id,
  name: '语文',
  subject: '语文',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_yuwen.png',
  sort: null,
} as SubjectItem
export const subject_math = {
  subjectId: math_subject_id,
  name: '数学',
  subject: '数学',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_shuxue.png',
  sort: null,
} as SubjectItem
const subject_physics = {
  subjectId: 4,
  name: '物理',
  subject: '物理',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_wuli.png',
  sort: null,
} as SubjectItem
const subject_chemistry = {
  subjectId: 5,
  name: '化学',
  subject: '化学',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_huaxue.png',
  sort: null,
} as SubjectItem
const subject_bio = {
  subjectId: 6,
  name: '生物学',
  subject: '生物学',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_shengwu.png',
  sort: null,
} as SubjectItem
const subject_law = {
  subjectId: 7,
  name: '政治（道法）',
  subject: '政治（道法）',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_fazhi.png',
  sort: null,
} as SubjectItem
const subject_history = {
  subjectId: 8,
  name: '历史',
  subject: '历史',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_lishi.png',
  sort: null,
} as SubjectItem
const subject_geo = {
  subjectId: 9,
  name: '地理',
  subject: '地理',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_dili.png',
  sort: null,
} as SubjectItem
const subject_science = {
  subjectId: 10,
  name: '科学',
  subject: '科学',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_kexue.png',
  sort: null,
} as SubjectItem
const subject_history_society = {
  subjectId: 11,
  name: '历史与社会',
  subject: '历史与社会',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_lishiyushehui.png',
  sort: null,
} as SubjectItem
const subject_it = {
  subjectId: 12,
  name: '信息技术',
  subject: '信息技术',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_xinxi.png',
  sort: null,
} as SubjectItem
const subject_music = {
  subjectId: 13,
  name: '音乐',
  subject: '音乐',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_yinyue.png',
  sort: null,
} as SubjectItem
const subject_art = {
  subjectId: 14,
  name: '美术',
  subject: '美术',
  pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_meishu.png',
  sort: null,
} as SubjectItem
const xiaoxue_subjects = [
  subject_english,
  subject_chinese,
  subject_math,
  subject_science,
  subject_law,
]
const chuzhong_subjects = [
  subject_english,
  subject_chinese,
  subject_math,
  subject_physics,
  subject_chemistry,
  subject_history,
  subject_geo,
  subject_bio,
  subject_science,
  subject_law,
]
const gaozhong_subjects = [
  subject_english,
  subject_chinese,
  subject_math,
  subject_physics,
  subject_chemistry,
  subject_history,
  subject_geo,
  subject_bio,
  subject_law,
  subject_it,
  // {
  //   subjectId: 14,
  //   name: '通用',
  //   subject: '通用',
  //   pictureUrl: 'https://xxl-1313840333.cos.ap-guangzhou.myqcloud.com/urm/subject_tongyong.png',
  //   sort: null,
  // },
]
export const subjects = [
  {
    id: chinese_subject_id,
    name: '语文',
    subject: '语文',
    pictureUrl: null,
    tableMark: '1',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: math_subject_id,
    name: '数学',
    subject: '数学',
    pictureUrl: null,
    tableMark: '2',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: english_subject_id,
    name: '英语',
    subject: '英语',
    pictureUrl: null,
    tableMark: '3',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 4,
    name: '物理',
    subject: '物理',
    pictureUrl: null,
    tableMark: '4',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 5,
    name: '化学',
    subject: '化学',
    pictureUrl: null,
    tableMark: '5',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 6,
    name: '生物学',
    subject: '生物学',
    pictureUrl: null,
    tableMark: '6',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 7,
    name: '政治（道法）',
    subject: '政治（道法）',
    pictureUrl: null,
    tableMark: '7',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 8,
    name: '历史',
    subject: '历史',
    pictureUrl: null,
    tableMark: '8',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 9,
    name: '地理',
    subject: '地理',
    pictureUrl: null,
    tableMark: '9',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 10,
    name: '科学',
    subject: '科学',
    pictureUrl: null,
    tableMark: '10',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 11,
    name: '历史与社会',
    subject: '历史与社会',
    pictureUrl: null,
    tableMark: '11',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 12,
    name: '信息技术',
    subject: '信息技术',
    pictureUrl: null,
    tableMark: '12',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 13,
    name: '音乐',
    subject: '音乐',
    pictureUrl: null,
    tableMark: '13',
    status: 0,
    createUser: null,
    updateUser: null,
  },
  {
    id: 14,
    name: '美术',
    subject: '美术',
    pictureUrl: null,
    tableMark: '14',
    status: 0,
    createUser: null,
    updateUser: null,
  },
]

export type Subject = {
  id?: number
  subjectId: number
  name: string
  subject: string
  pictureUrl: string
}

// 获得真正的年级
export const getRealGrade = (grade: any) => {
  grade = Number(grade)
  if (grade <= base_grade_high_3) {
    return base_grade_map[grade]
  }
  return grade
}

export const getStageByGrade = (grade: any) => {
  grade = getRealGrade(grade)
  if (gaozhong.includes(grade)) {
    return stage_gaozhong
  }
  if (chuzhong.includes(grade)) {
    return stage_chuzhong
  }
  return stage_xiaoxue
}

export const getSubjectById = (subjectId: any): Subject => {
  subjectId = Number(subjectId)
  for (const subject of subjects) {
    if (subject.id === subjectId) {
      return subject as any
    }
  }
  return undefined as any
}

export const getSubjectsByStage = (stage: any): Subject[] => {
  if (!stage) return []
  stage = Number(stage)
  if (stage === stage_xiaoxue) return xiaoxue_subjects
  if (stage === stage_chuzhong) return chuzhong_subjects
  return gaozhong_subjects
}

export const getSubjectsByGrade = (grade: any): Subject[] => {
  if (!grade) return []
  grade = getRealGrade(grade)
  if (xiaoxue.includes(grade)) return xiaoxue_subjects
  if (chuzhong.includes(grade)) return chuzhong_subjects
  return gaozhong_subjects
}

// 根据班级名称获得年级
export const getGradeByClassName = (className: string) => {
  for (const grade in grade_map) {
    const gradeName = grade_map[grade]
    if (className.includes(gradeName)) return grade
  }
  return undefined
}

// 根据班级名称获得学科
export const getSubjectsByClassName = (className: string) => {
  return getSubjectsByGrade(getGradeByClassName(className))
}
