import request from '@/config/axios'

export type WebtopoProjectVO = {
  id: number
  projectName: string
  deptId?: number
  thumbnail?: string
  createTime?: number | string
  linkedDevices?: WebtopoProjectLinkedDeviceVO[]
  linkedDeviceIds?: number[]
  remark?: string
  updateTime?: string
}

export type WebtopoProjectLinkedDeviceVO = {
  id: number
  deviceCode?: string
  deviceName?: string
  deviceStatus?: string | null
  pointParams?: WebtopoProjectLinkedDevicePointParamVO[]
}

export type WebtopoProjectLinkedDevicePointParamVO = {
  paramName?: string
  paramCode?: string
  paramValue?: unknown
  paramUnit?: string
}

export type WebtopoProjectDetailVO = WebtopoProjectVO & {
  dataModel?: unknown
  dataModelParseError?: string
}

export type WebtopoProjectPageReqVO = {
  deptId?: number
  pageNo: number
  pageSize: number
  projectName?: string
}

export type WebtopoProjectCreateReqVO = {
  projectName: string
  linkedDeviceIds?: number[]
  remark?: string
}

export type WebtopoProjectUpdateReqVO = WebtopoProjectCreateReqVO & {
  id: number
  thumbnail?: string
  dataModel?: string
}

export type WebtopoProjectCopyReqVO = {
  id: number
  projectName: string
  remark?: string
}

type ApiResult<T> = {
  code?: number
  data?: T
  msg?: string
}

const unwrapData = <T>(res: T | ApiResult<T>) => {
  if (res && typeof res === 'object' && 'data' in res) {
    return (res as ApiResult<T>).data as T
  }
  return res as T
}

const parseWebtopoDataModelResult = (dataModel: unknown) => {
  if (typeof dataModel !== 'string') {
    return {
      dataModel
    }
  }

  const trimmedDataModel = dataModel.trim()
  if (!trimmedDataModel) {
    return {
      dataModel: undefined
    }
  }

  try {
    return {
      dataModel: JSON.parse(trimmedDataModel)
    }
  } catch {
    return {
      dataModel: undefined,
      dataModelParseError: '拓扑数据格式错误，无法解析 JSON'
    }
  }
}

export const parseWebtopoDataModel = (dataModel: unknown) => {
  return parseWebtopoDataModelResult(dataModel).dataModel
}

export const WebtopoProjectApi = {
  createWebtopoProject: (data: WebtopoProjectCreateReqVO) => {
    return request.post<number | ApiResult<number>>({
      url: '/pms/iot-webtopo-project/create',
      data
    })
  },
  updateWebtopoProject: (data: WebtopoProjectUpdateReqVO) => {
    return request.put({
      url: '/pms/iot-webtopo-project/update',
      data
    })
  },
  copyWebtopoProject: (data: WebtopoProjectCopyReqVO) => {
    return request.post({
      url: '/pms/iot-webtopo-project/copyProject',
      data
    })
  },
  getWebtopoProjectPage: (params: WebtopoProjectPageReqVO) => {
    return request.get<WebtopoProjectVO[] | { list: WebtopoProjectVO[]; total: number }>({
      url: '/pms/iot-webtopo-project/page',
      params
    })
  },
  getWebtopoProject: async (id: number) => {
    const res = await request.get<WebtopoProjectDetailVO | ApiResult<WebtopoProjectDetailVO>>({
      url: '/pms/iot-webtopo-project/get',
      params: { id }
    })
    const data = unwrapData<WebtopoProjectDetailVO>(res)
    if (!data) {
      return data
    }

    const { dataModel, dataModelParseError } = parseWebtopoDataModelResult(data?.dataModel)

    return {
      ...data,
      dataModel,
      dataModelParseError
    }
  }
}
