export interface Color {
  bgColor: string
  color: string
}

export interface Clean {
  color: Color
  fullName?: string
  name: string
  tags: string[]
}

export interface BookVersion {
  baseId: string
  clean: Clean
  delFlag: number
  id: string
  name: string
  shortName: string
  // eslint-disable-next-line no-use-before-define
  textBookVoList: TextBook[]
}

export interface TextBook {
  addFlag: number
  baseId: string
  bookVersionId: string
  bookVersionName: any
  businessFlag: string
  chapterBaseId: any
  chapterTreeNodeList: any
  clean: Clean
  currentChapterId: any
  displayName: string
  gradeId: string
  id: string
  locked: boolean
  name: string
  progress: any
  shortName: string
  subjectId: string
  syncFlag: number
  textBookId: string
  textBookName: string
  version: BookVersion
  versionName: any
}

export const book_sync_locked = 1
export const book_sync_unlocked = 0

function _getBookColor(bookName: string) {
  let index = bookVersionNames.length - 1
  let stop = false
  // 看一下bookName包含bookVersionNames的哪一个
  for (const [i, bookVersionName] of bookVersionNames.entries()) {
    for (const element of bookVersionName) {
      if (bookName.includes(element)) {
        index = i
        stop = true
        break
      }
    }
    if (stop) {
      break
    }
  }
  return bookColors[index] as any
}

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

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

  // 区分
  const data: {
    name: string
    tags: 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
}

function _processObj(obj: any) {
  const name = _processName(obj.clean.name)
  if (name.tags) {
    obj.clean.tags = name.tags
    obj.clean.name = name.name
  }
}

function _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 function 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
      // 设置名字
      book.clean.name = version.clean.tags?.length
        ? book.displayName || book.shortName || book.name
        : _longest(book.name, book.displayName, book.shortName)
      // 处理对象
      _processObj(book)
      // 全名
      book.clean.fullName = _getBookName(book, version)
      // 覆盖颜色
      book.clean.color = _getBookColor(book.clean.fullName as any)
      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
        })
      }
    }
  }
}

// 清洗一下教材数据
export function 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 as any)
    book.version.clean.color = book.clean.color
  }
}

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

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

// 获取书本名字
function _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 > 0) {
    name += step + tags.join(step)
  }
  version.clean.fullName = name
  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',
  },
]
