import { geelibGet, geelibPost } from './geelib-client.mjs'

const PRIORITY_MAP = {
  low: 1,
  medium: 2,
  high: 3,
  urgent: 4,
}

export async function cmdGetUserInfo() {
  return geelibGet('/ones/user/userInfo', { need_share: 0 })
}

export async function cmdListProjects(query = '') {
  return geelibGet('/projects/subBusMgr/getCanAccessSubList', {
    query,
    simple: 2,
  })
}

export async function cmdGetProjectDetail(subId) {
  return geelibGet('/projects/subBusMgr/getSubDetail', { sub_id: subId })
}

export async function cmdListProjectMembers(subId) {
  return geelibGet('/projects/subBusMgr/getSubUserListSortByInitial', {
    sub_id: subId,
  })
}

export async function cmdListMatterTypes(subId) {
  return geelibGet('/matter/Matter/getMatterType', {
    sub_id: subId,
    page: 0,
    pageSize: 9999,
  })
}

export async function cmdListMatterStatuses(subId, typeId) {
  return geelibGet('/matter/matterType/getMatterTypeStatusList', {
    sub_id: subId,
    type_id: typeId,
  })
}

/** 从 getMatterList 响应中解析工作项列表（GeeLib 返回 matterList）。 */
export function extractMatterList(data) {
  if (!data || typeof data !== 'object') {
    return []
  }
  if (Array.isArray(data.matterList)) {
    return data.matterList
  }
  if (Array.isArray(data.list)) {
    return data.list
  }
  if (Array.isArray(data.data)) {
    return data.data
  }
  return []
}

export async function cmdListMatters(opts) {
  const customContent = {}
  if (opts.statusId !== undefined) {
    customContent.status = [opts.statusId]
  }
  if (opts.assigneeId !== undefined) {
    customContent.executor = [opts.assigneeId]
  }
  const body = {
    sub_id: opts.subId,
    type_id: [opts.typeId],
    page: opts.page ?? 1,
    pageSize: opts.pageSize ?? 20,
    title: opts.keyword ?? '',
    order_by: [],
    customContent,
    is_favor: 0,
    simple: 0,
    from_v3: 1,
    tree: 0,
    need_user_name: 1,
  }
  return geelibPost('/matter/Matter/getMatterList', body)
}

export async function cmdGetMatter(subId, matterId) {
  return geelibGet('/matter/Matter/getMatterDetail', {
    sub_id: subId,
    id: matterId,
    need_options: 1,
  })
}

export async function cmdUpdateMatter(opts) {
  const results = []

  const hasOtherFields =
    opts.title !== undefined ||
    opts.description !== undefined ||
    opts.assigneeId !== undefined ||
    opts.priority !== undefined ||
    opts.progress !== undefined ||
    opts.sprintId !== undefined

  if (hasOtherFields) {
    const body = {
      sub_id: opts.subId,
      id: opts.matterId,
    }
    if (opts.title !== undefined) body.title = opts.title
    if (opts.description !== undefined) body.content = opts.description
    if (opts.assigneeId !== undefined) body.executor = opts.assigneeId
    if (opts.priority !== undefined) {
      body.priority = PRIORITY_MAP[opts.priority] ?? opts.priority
    }
    if (opts.progress !== undefined) body.progress = opts.progress
    if (opts.sprintId !== undefined) body.sprint_id = opts.sprintId
    const r = await geelibPost('/matter/Matter/editMatter', body)
    results.push({ fields: 'other', ...r })
  }

  if (opts.statusId !== undefined) {
    const statusBody = {
      sub_id: String(opts.subId),
      id: opts.matterId,
      data: { cf_id: '1', cf_value: String(opts.statusId) },
      additional_attribute: [],
      remark: '',
      toUsers: [],
    }
    const sr = await geelibPost('/matter/Matter/editMatter', statusBody)

    if (sr.errno === 2000) {
      const detail = await geelibGet('/matter/Matter/getMatterDetail', {
        sub_id: opts.subId,
        id: opts.matterId,
        need_options: 1,
      })
      const actualStatus = detail.data?.matter_status
      if (actualStatus !== opts.statusId) {
        const missingFields = (detail.data?.matterCustomAttributes ?? [])
          .filter(a => a.is_required && a.matterCustomAttributeValue === null)
          .map(a => `「${a.cf_name}」(${a.cf_key})`)
        const hint =
          missingFields.length > 0
            ? `原因：工作项存在未填的必填字段：${missingFields.join('、')}。请先在 Geelib 网页端补全后重试。`
            : '状态未变更，可能存在未知的状态流转限制。'
        results.push({
          fields: 'status',
          errno: sr.errno,
          errmsg: `API 返回成功但状态实际未变更（当前状态：${detail.data?.status_name ?? actualStatus}）。${hint}`,
        })
      } else {
        results.push({
          fields: 'status',
          errno: 2000,
          errmsg: '状态变更成功',
          actual_status: detail.data?.status_name,
        })
      }
    } else {
      results.push({ fields: 'status', ...sr })
    }
  }

  if (results.length === 0) {
    return { errno: 2000, errmsg: '无需更新（未提供任何修改字段）' }
  }
  if (results.length === 1) {
    return results[0]
  }
  return results
}

export async function cmdGetComments(subId, matterId) {
  return geelibGet('/bservice/Comment/getList', {
    sub_id: subId,
    type: 'matter',
    id: matterId,
  })
}

export async function cmdAddComment(subId, matterId, content) {
  return geelibPost('/bservice/Comment/add', {
    sub_id: subId,
    type: 'matter',
    id: matterId,
    content,
  })
}
