import { getMemberAttrList, getEventAttrList, getMemberAttrRange, getRfmRes, getRfmStatistics } from '@/api/rfm'

// 用户属性类型
export interface AttrType {
  id: string
  name: string
  type: string
  format: string
  english_name: string
}

// 事件类型
interface MetaEventType {
  event_id: string
  event_name: string
  event_english_name: string
  attrs: AttrType[]
}

// 所有用户属性
export function useUserAttr() {
  const userAttrList = ref<AttrType[]>([])
  async function fetchUserAttrList(type: number) {
    await getMemberAttrList({ type }).then((res: any) => {
      userAttrList.value = res.data.items
    })
  }
  return { fetchUserAttrList, userAttrList }
}

// 所有事件
export function useMetaEvent() {
  const metaEventList = ref<MetaEventType[]>([])
  async function fetchMetaEventList(type: number) {
    await getEventAttrList({ type }).then((res: any) => {
      metaEventList.value = res.data.items
    })
  }
  return { fetchMetaEventList, metaEventList }
}

// 最大值最小值
export function useUserAttrRange() {
  const userAttrRange = ref<{ min: string; max: string; avg: string; median: string; zero_count: string; no_zero_median: string }>({
    min: '',
    max: '',
    avg: '',
    median: '',
    zero_count: '',
    no_zero_median: ''
  })
  async function fetchUserAttrRange(member_meta_id: string) {
    await getMemberAttrRange({ member_meta_id }).then((res: any) => {
      userAttrRange.value = res.data.detail
    })
  }
  return { fetchUserAttrRange, userAttrRange }
}

// RFM标签的结果集
interface RfmRes {
  frm_key: string
  frm_value: number
  frm_extend_info: any
}
const rfmResList = ref<RfmRes[]>([])
export function useRfmRes() {
  async function fetchRfmResList() {
    await getRfmRes().then((res: any) => {
      rfmResList.value = res.data.items
    })
  }
  onMounted(() => {
    fetchRfmResList()
  })
  return { fetchRfmResList, rfmResList }
}

interface RfmStatistics {
  is_complete: boolean
  rfm_tag_res: {
    r: number
    f: number
    m: number
  }
}
const rfmStatistics = ref<RfmStatistics>({ is_complete: false, rfm_tag_res: { r: 0, f: 0, m: 0 } })
export function useRfmStatistics(tagId: string) {
  async function fetchRfmStatistics() {
    if (!tagId) return
    await getRfmStatistics({ tag_id: tagId }).then((res: any) => {
      rfmStatistics.value = res.data
    })
  }
  onMounted(() => {
    fetchRfmStatistics()
  })
  return { fetchRfmStatistics, rfmStatistics }
}
