import { getCountryRules } from '@/service/index/api'

import { useUserStore } from '@/store/user'
import { RuleResult } from '@/types/app-type'

const userStore = useUserStore()

export const requireSubjectList = ref<any[]>([])
export const optionalSubjectList = ref<any[]>([])
// 单选 必选学科
export const requireSubject = ref('')
// 任意选择科目
export const optionalSubject = ref<any[]>([])

export const useRules = (callback?: any) => {
  getCountryRules().then((res) => {
    if (res.code === 200) {
      const results = res.result as RuleResult[]

      const matchRule = results.filter((item) => item.p === userStore.userInfo.city.policy)
      const matchRules = matchRule.length > 0 ? matchRule[0].rule : []
      requireSubjectList.value = matchRules.filter((item) => item?.isfirst === 'true')
      optionalSubjectList.value = matchRules.filter((item) => !(item?.isfirst === 'true'))

      if (userStore.userInfo.city.code !== userStore.userInfo.estimatedAchievement.provinceCode) {
        return
      }
      splitSubject(requireSubjectList.value, optionalSubjectList.value)
      callback ? callback() : false
    }
  })
}

// 分离学科，然后将学科分类存储到用户的期望数据上
const splitSubject = (requireSubjectList: any[], optionalSubjectList: any[]) => {
  const subjectGroup = userStore.userInfo.estimatedAchievement.subjectGroup
  const splitRule = subjectGroup.split(',')

  const requireSubject = requireSubjectList.filter((item) => splitRule.includes(item.simplename))
  const optionalSubject = optionalSubjectList.filter((item) => splitRule.includes(item.simplename))

  userStore.setEstimatedAchievement({
    requireSubject,
    optionalSubject,
  })
}
