import { Commit, Dispatch } from './index'
import {
  useFetchOrg,
  useFetchMember,
  useFetchAuth,
  useFetchUser,
  useFetchOrgAuth,
} from '@/hooks/useFetch'
import dayjs from '@/util/dayjs'
import state from './state'

interface Method {
  commit: Commit
  dispatch: Dispatch
}

export default {
  async getAuth({ commit }: Method) {
    if (process.env.NODE_ENV !== 'production') {
      // 开发环境
      commit('SET_AUTH', {
        userid: 91541,
        orgid: '000001',
        // code: '001.001.031.014.205', // 最高权限
        code: '001.001.031.014.205.002.001', //牡丹社区委员会
      })
      return
    }

    const userid: number | null = (await useFetchAuth())?.customer?.id || null
    if (!userid) return
    const orgid: string =
      (
        await useFetchUser({
          keys: '组织id',
          q: `paths @ "userid" && string == "${userid}"`,
        })
      )?.[0]?.['组织id']?.[0] || ''

    const code: string =
      (
        await useFetchOrgAuth({
          keys: '权限编码',
          q: `paths @ "组织id" && string == "${orgid}"`,
        })
      )?.[0]?.['权限编码'] || ''

    commit('SET_AUTH', { userid, orgid, code })
  },
  async getBasicInfo({ commit }: Method, query?: string) {
    commit('SET_BASIC_INFO', {
      sum: await getSum(query),
      member: await getMember(query),
      organization: await getOrganization(query),
      age: await getAge(query),
    })
    commit('SET_FILTER_PATH', query)
  },
}

async function getSum(query?: string) {
  if (query && query.includes('所属小区')) {
    let communityQuery = query.split(',').find((e) => e.includes('所属小区'))
    if (query.includes('所属楼宇')) {
      communityQuery = [
        communityQuery,
        query.split(',').find((e) => e.includes('所属楼宇')),
      ].join(',')
    }
    const member1 =
      (
        await useFetchMember({
          a: 'id,count',
          q: `${communityQuery},paths @ "党员身份" && string == "正式党员"`,
        })
      )?.[0]?.__aggregate__ || 0
    const member2 =
      (
        await useFetchMember({
          a: 'id,count',
          q: `${communityQuery},paths @ "党员身份" && string == "预备党员"`,
        })
      )?.[0]?.__aggregate__ || 0
    return [
      {
        name: query.includes('所属楼宇') ? '楼内党员总数' : '居住在该小区党员',
        value: member1 + member2,
        unit: '位',
      },
      { name: '正式党员', value: member1, unit: '位' },
      { name: '预备党员', value: member2, unit: '位' },
    ]
  }
  const orgNum =
    (
      await useFetchOrg({
        a: 'id,count',
        keys: '是否虚拟组织',
        q: query,
      })
    )?.find((e: any) => !e['是否虚拟组织'])?.__aggregate__ || 0
  const member = await useFetchMember({
    a: 'id,count',
    keys: '是否居住在花木街道',
    q: query,
  })
  const inHuamu =
    member?.find((e: any) => e['是否居住在花木街道'])?.__aggregate__ || 0
  const notInHuamu =
    member?.find((e: any) => !e['是否居住在花木街道'])?.__aggregate__ || 0

  return [
    { name: '党组织', value: orgNum, unit: '个' },
    { name: '关系在街道内党员', value: inHuamu + notInHuamu, unit: '位' },
    { name: '街道居民党员', value: inHuamu, unit: '位' },
  ]
}

async function getMember(query?: string) {
  const result = { ...state.basicInfo.member }
  const res = await useFetchMember({
    a: 'id,count',
    keys: '党员类型',
    q: query,
  })
  const total = res.reduce(
    (acc: number, cur: any) => acc + (cur.__aggregate__ || 0),
    0,
  )
  result.source.forEach((item) => {
    const value =
      res.find((e: any) => item.name === e['党员类型'])?.__aggregate__ || 0
    item.value = value
    item.ratio = (value / total) * 100
  })
  return result
}

async function getOrganization(query?: string) {
  const result = { ...state.basicInfo.organization }
  if (query && query.includes('所属小区')) {
    result.source = []
    return result
  }
  result.source = [
    { name: '党委', value: 0, ratio: 0 },
    { name: '党总支', value: 0, ratio: 0 },
    { name: '党支部', value: 0, ratio: 0 },
    { name: '联合党支部', value: 0, ratio: 0 },
  ]
  const res = (
    await useFetchOrg({
      a: 'id,count',
      keys: '等级',
      q: query,
    })
  )?.filter((e: any) => result.source.some((n) => n.name === e['等级']))
  const total = res.reduce(
    (acc: number, cur: any) => acc + (cur.__aggregate__ || 0),
    0,
  )
  result.source.forEach((item) => {
    const value =
      res.find((e: any) => item.name === e['等级'])?.__aggregate__ || 0
    item.value = value
    item.ratio = (value / total) * 100
  })
  return result
}

async function getAge(query?: string) {
  const result = { ...state.basicInfo.age }
  const source = [
    {
      name: '18-25岁',
      range: [
        dayjs().subtract(25, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(18, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '26-35岁',
      range: [
        dayjs().subtract(35, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(26, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '36-50岁',
      range: [
        dayjs().subtract(50, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(36, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '50-70岁',
      range: [
        dayjs().subtract(70, 'year').format('YYYY-MM-DD'),
        dayjs().subtract(50, 'year').format('YYYY-MM-DD'),
      ],
    },
    {
      name: '70岁以上',
      range: [null, dayjs().subtract(71, 'year').format('YYYY-MM-DD')],
    },
  ]
  const res = await Promise.all(
    source.map(({ range }) => {
      const ageQuery = range[0]
        ? `paths @ "出生日期" && string >= "${range[0]}",paths @ "出生日期" && string <= "${range[1]}"`
        : `paths @ "出生日期" && string <= "${range[1]}"`
      return useFetchMember({
        a: 'id,count',
        q: query ? `${ageQuery},${query}` : ageQuery,
      })
    }),
  )
  result.source.forEach(
    (item, i) => (item.value = res[i]?.[0].__aggregate__ || 0),
  )
  return result
}
