import request from '@/utils/axiosReq'
import { CommonQueryResult } from '~/common'

export function Query<T = any>(params): Promise<CommonQueryResult<T>> {
  if (NEW_DATACONTENT_ID.includes(params.id)) {
    return NewQuery<T>(params)
  }
  return request({
    url: '/openApi/query',
    method: 'post',
    data: params,
  })
}

function NewQuery<T = any>(params): Promise<CommonQueryResult<T>> {
  return request({
    url: '/newOpenApi/search',
    method: 'post',
    data: params,
  })
}

export async function myQuery(id, ...dataContent) {
  const params = {
    id,
    dataContent,
  }
  try {
    const result = await Query(params)
    if (Number(result.code) === 0) {
      return result.returnData.listValues
    } else {
      return Promise.reject(result.message)
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

export async function htQuery(id, ...dataContent) {
  const params = {
    id,
    dataContent,
  }
  try {
    const result = await Query(params)
    if (Number(result.code) === 0) {
      return result.returnData
    } else {
      return []
    }
  } catch (error) {
    return []
  }
}

function NewGeneralDataReception(func: any) {
  return func
}

export function GeneralDataReception(params): Promise<CommonQueryResult> {
  const { serviceId, dataContent } = params
  if (
    NEW_SERVICE_ID.includes(Number(serviceId)) ||
    serviceId == 65004 ||
    serviceId == 65007
  ) {
    const newData = JSON.parse(dataContent)
    const { event } = newData
    const eventType = event ?? params.event
    let key: any = null
    if (newData?.event) {
      delete newData.event
    }
    if (eventType == 2) {
      if (newData.hasOwnProperty('IDKey')) {
        key = newData['IDKey']
      } else {
        for (const item in newData) {
          if (
            item.includes('id') ||
            item.includes('Id') ||
            item.includes('ID')
          ) {
            key = item
          }
        }
      }
      return NewGeneralDataReception(
        dataToChange(serviceId, newData, eventType, key)
      )
    } else {
      if (newData?.IDKey) {
        delete newData.IDKey
      }
      return NewGeneralDataReception(
        dataToChange(serviceId, newData, eventType)
      )
    }
  }
  return request({
    url: '/openApi/generalDataReception',
    method: 'post',
    data: params,
  })
}

//增/删/改
export async function dataToChange(
  id: number,
  data: any,
  event: number,
  key?: string
) {
  try {
    const params = {
      serviceId: id,
      dataContent: formatChange(data, event, key),
      event: `${event}`,
      // authId: this.AauthId
    }
    const { code, message } = await sendData(params)
    return { code, message }
  } catch (error) {
    return { code: 1, message: error }
  }
}

function sendData(params) {
  return request({
    url: '/externalApi/openApi/sendData',
    method: 'post',
    data: params,
  })
}

//新增
export function newData(params) {
  return request({
    url: '/externalApi/openApi/sendData',
    method: 'post',
    data: params,
  })
}

//修改
export function modifyData(params) {
  return request({
    url: '/externalApi/openApi/sendData',
    method: 'post',
    data: params,
  })
}

//删除movedata
export function moveData(params) {
  return request({
    url: '/externalApi/openApi/sendData',
    method: 'post',
    data: params,
  })
}

function formatChange(data, event, key) {
  const datas: any = []
  const flag = Array.isArray(data)
  if (flag) {
    for (let i = 0; i < data.length; i++) {
      let obj: any = {}
      if (event == 1) {
        obj.Value = data[i]
      } else if (event == 2) {
        obj.Value = data[i]
        obj.filter = {}
        if (Array.isArray(key)) {
          const keys = <any>[]
          const vals = <any>[]
          obj.filter = []
          for (let j = 0; j < key.length; j++) {
            const dep = key[i]
            keys.push(Object.keys(dep))
            vals.push(Object.values(dep))
          }
          const nobj = {
            left: '(',
            column: `${keys[i]}`,
            comparator: '=',
            value: `${vals[i]}`,
            right: ')',
            connector: 'and',
          }
          obj.filter.push(nobj)
          if (obj.Value.hasOwnProperty(keys[i])) {
            delete obj.Value[keys[i]]
          }
        } else {
          obj.filter[key] = data[i][key]
          if (obj.Value[key]) {
            delete obj.Value[key]
          }
        }
      } else {
        obj = data[i]
      }
      datas.push(obj)
    }
  } else {
    let obj: any = {}
    if (event == 1) {
      obj.Value = data
    } else if (event == 2) {
      obj.Value = data
      obj.filter = [
        {
          left: '(',
          column: `${key}`,
          comparator: '=',
          value: `${data[key]}`,
          right: ')',
          connector: 'and',
        },
      ]
      if (obj.Value[key]) {
        delete obj.Value[key]
      }
    } else {
      obj = data
    }
    datas.push(obj)
  }
  return datas
}
