import { addDictionary, IOriginalDictionary, IQueryCommon, IRes, IResult } from '@/api/common'
import axios from '@/utils/request'
import { base, IFlaw, IFlawParam, IInterface, IParam } from './common'
import { drainageTypeKey, drainageTypeKeyDefaultValues } from '@/utils/constant'
import store from '@/store'
import { IPoint } from '../../configuration/api/common'

const uris = {
  base: `${base}/defectinfo`,
  page: `${base}/defectinfo/page`,
  del: `${base}/defectinfo/deleteByIds`,
  dictionary: '/base/code/getByKeys',
  interface: `${base}/defectinfo/interfaceList`,
  params: `${base}/defectinfo/getParamSetByCode`,
  points: `${base}/surveysite/list`
}

export const addFlaw = (data: Partial<IFlawParam>) =>
  axios.request<IRes<boolean>>({
    url: uris.base,
    method: 'post',
    data
  })

export const deleteFlaw = (id: string) => axios.request<IRes<boolean>>({ url: `${uris.base}/${id}`, method: 'delete' })

export const updateFlaw = (data: IFlawParam) =>
  axios.request<IRes<boolean>>({
    url: uris.base,
    method: 'put',
    data
  })

export const getFlaw = (id: string) => axios.request<IResult<IFlaw>>({ url: `${uris.base}/${id}`, method: 'get' })

export const flawPage = (params: Partial<IFlaw & IQueryCommon>) =>
  axios.request<IRes<IFlaw[]>>({ url: uris.page, method: 'get', params })

export const deleteFlawBatch = (ids: string) =>
  axios.request<IRes<boolean>>({ url: uris.del, method: 'delete', params: { ids } })

/** 获取字典值 */
export const getDictKeys = async (keys: string = drainageTypeKey.codeKey) => {
  const { result } = await axios.request<{ result: { [x: string]: IOriginalDictionary[] } }>({
    url: uris.dictionary,
    method: 'get',
    params: { keys }
  })
  if (!keys.includes(',')) {
    const { [keys]: values = [] } = result
    if (values.length === 0 && keys === drainageTypeKey.codeKey) {
      const { username: creater = '' }: { username: string } = store.state.user || {}
      addDictionary({ ...drainageTypeKey, ulevel: '1', creater }),
        drainageTypeKeyDefaultValues.map((item) => addDictionary({ ulevel: '2', ...drainageTypeKey, creater, ...item }))
      const temp = (await getDictKeys()) as IOriginalDictionary[]
      return temp
    }
    return values || []
  }
  return result || {}
}

export const fetchInterfaces = () => axios.request<IResult<IInterface[]>>({ url: uris.interface, method: 'get' })
export const fetchParams = (code: string) =>
  axios.request<IResult<IParam[]>>({ url: `${uris.params}/${code}`, method: 'get' })

export const fetchPoints = (params) => axios.request<IRes<IPoint[]>>({ url: uris.points, method: 'get', params })
