import { serialize } from 'object-to-formdata'
import { addDictionary, IOriginalDictionary, IQueryCommon, IRes, IResult } from '@/api/common'
import axios from '@/utils/request'
import { base, IFlaw } from './common'
import { drainageTypeKey, drainageTypeKeyDefaultValues } from '@/utils/constant'
import store from '@/store'

const uris = {
  base: `${base}/defectinfo`,
  page: `${base}/defectinfo/page`,
  del: `${base}/defectinfo/deleteByIds`,
  dictionary: '/base/code/getByKeys'
}

export const addFlaw = (data: Partial<IFlaw>) =>
  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: IFlaw) =>
  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 || {}
}
