import { MOCK_GEOPHYSICAL_DATA, MOCK_STATISTICS } from '@/mock/geophysicalData'
import { MOCK_DATA_FILES, nextFileId } from '@/mock/dataFiles'

/** @type {typeof MOCK_GEOPHYSICAL_DATA} */
let dataStore = [...MOCK_GEOPHYSICAL_DATA]
/** @type {Record<string, Array>} */
let fileStore = { ...MOCK_DATA_FILES }

/**
 * 数据大类与类型映射
 */
const CATEGORY_TYPE_MAP = {
  acoustic: ['ship_multibeam', 'submarine_multibeam', 'sidescan'],
  seismic: ['shallow_seismic', 'seismic_2d', 'seismic_3d', 'obn_seismic'],
  potential: ['gravity', 'ship_magnetic', 'submarine_magnetic'],
  ocean: ['ctd', 'adcp', 'heat_flow']
}

/**
 * 分页查询地球物理数据
 * @param {Object} params
 * @returns {Promise<{page: {records: Array, total: number}}>}
 */
export function dataPage(params = {}) {
  const {
    start = 0,
    limit = 10,
    query = '',
    data_type = '',
    data_status = '',
    data_secrecy = '',
    data_code = '',
    category = ''
  } = params

  let records = [...MOCK_GEOPHYSICAL_DATA]

  if (query) {
    const keyword = query.toLowerCase()
    records = records.filter((item) =>
      item.data_code.toLowerCase().includes(keyword) ||
      item.data_name.toLowerCase().includes(keyword) ||
      item.voyage_name.toLowerCase().includes(keyword)
    )
  }

  if (category && CATEGORY_TYPE_MAP[category]) {
    const types = CATEGORY_TYPE_MAP[category]
    records = records.filter((item) => types.includes(item.data_type))
  }

  if (data_code) {
    records = records.filter((item) => item.data_code.includes(data_code))
  }

  if (data_type) {
    records = records.filter((item) => item.data_type === data_type)
  }

  if (data_status) {
    records = records.filter((item) => item.data_status === data_status)
  }

  if (data_secrecy) {
    records = records.filter((item) => item.data_secrecy === data_secrecy)
  }

  const total = records.length
  const pageRecords = records.slice(start, start + limit)

  return Promise.resolve({
    success: true,
    page: {
      records: pageRecords,
      total
    }
  })
}

/**
 * 获取主页统计数据
 * @returns {Promise<{array: Array}>}
 */
export function reportMain() {
  return Promise.resolve({
    success: true,
    array: [MOCK_STATISTICS]
  })
}

/**
 * 本地 admin 登录
 * @param {Object} data
 * @returns {Promise<{success: boolean, entity?: string, message?: string}>}
 */
export function localLogin(data) {
  const { loginName, loginPass } = data
  if (loginName === 'admin' && loginPass === '21232f297a57a5a743894a0e4a801fc3') {
    return Promise.resolve({
      success: true,
      entity: 'admin-token-pdata'
    })
  }
  return Promise.resolve({
    success: false,
    message: '用户名或密码错误'
  })
}

/**
 * 查询单条地球物理数据
 * @param {Object} params
 * @returns {Promise<{success: boolean, entity: Object}>}
 */
export function dataFind(params = {}) {
  const { data_id } = params
  const entity = dataStore.find((item) => String(item.id) === String(data_id))
  if (!entity) {
    return Promise.resolve({ success: false, message: '数据不存在' })
  }
  return Promise.resolve({ success: true, entity: { ...entity } })
}

/**
 * 新增或编辑地球物理数据
 * @param {Object} data
 * @returns {Promise<{success: boolean, entity: Object}>}
 */
export function dataEdit(data = {}) {
  const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
  if (data.id) {
    const index = dataStore.findIndex((item) => String(item.id) === String(data.id))
    if (index === -1) {
      return Promise.resolve({ success: false, message: '数据不存在' })
    }
    dataStore[index] = { ...dataStore[index], ...data }
    return Promise.resolve({ success: true, entity: { ...dataStore[index] } })
  }

  const newId = Math.max(...dataStore.map((item) => item.id), 0) + 1
  const entity = {
    id: newId,
    data_status: '待审核',
    fill_time: data.fill_time || now,
    ...data
  }
  dataStore.unshift(entity)
  fileStore[newId] = fileStore[newId] || []
  return Promise.resolve({ success: true, entity: { ...entity } })
}

/**
 * 获取数据关联资源列表
 * @param {Object} params
 * @returns {Promise<{success: boolean, array: Array}>}
 */
export function dataFileList(params = {}) {
  const { data_id } = params
  const list = fileStore[data_id] || []
  return Promise.resolve({ success: true, array: [...list] })
}

/**
 * 上传文件（mock）
 * @param {Object} params
 * @returns {Promise<{success: boolean, entity: Object}>}
 */
export function dataFileUpload(params = {}) {
  const { data_id, file_name, file_size = 0 } = params
  if (!data_id) {
    return Promise.resolve({ success: false, message: '请先保存数据信息' })
  }
  if (!file_name) {
    return Promise.resolve({ success: false, message: '请选择文件' })
  }

  const record = {
    id: nextFileId(),
    file_name,
    file_size: Number(file_size) || 0,
    source_type: 'upload',
    file_path: `/local/upload/${file_name}`,
    create_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
  }

  if (!fileStore[data_id]) {
    fileStore[data_id] = []
  }
  fileStore[data_id].unshift(record)
  return Promise.resolve({ success: true, entity: record })
}

/**
 * 指定云资源路径（mock）
 * @param {Object} params
 * @returns {Promise<{success: boolean, entity: Object}>}
 */
export function dataCloudPathAdd(params = {}) {
  const { data_id, cloud_path, resource_name = '' } = params
  if (!data_id) {
    return Promise.resolve({ success: false, message: '请先保存数据信息' })
  }
  if (!cloud_path) {
    return Promise.resolve({ success: false, message: '请输入云资源路径' })
  }

  const fileName = resource_name || cloud_path.split('/').pop() || cloud_path
  const record = {
    id: nextFileId(),
    file_name: fileName,
    file_size: 0,
    source_type: 'cloud',
    file_path: cloud_path,
    create_time: new Date().toISOString().slice(0, 19).replace('T', ' ')
  }

  if (!fileStore[data_id]) {
    fileStore[data_id] = []
  }
  fileStore[data_id].unshift(record)
  return Promise.resolve({ success: true, entity: record })
}

/**
 * 删除数据资源
 * @param {Object} params
 * @returns {Promise<{success: boolean}>}
 */
export function dataFileDelete(params = {}) {
  const { data_id, file_id } = params
  const list = fileStore[data_id] || []
  fileStore[data_id] = list.filter((item) => String(item.id) !== String(file_id))
  return Promise.resolve({ success: true })
}
