import request from './request.js';
import { getDefaultAvatarUrl } from './avatar.js';

export const ZHIDING_HF_MAP = { 1: '想接', 2: '已婉拒', 3: '等会接' };

export async function fetchMyZhidingOrders() {
  try {
    const res = await request({ url: '/dingdan/zdcx', method: 'POST', data: {} });
    const body = res?.data;
    if (body && (body.code === 200 || body.code === 0) && body.data) {
      return body.data.list || [];
    }
  } catch (e) {
    console.warn('fetchMyZhidingOrders failed', e);
  }
  return [];
}

export async function submitZhidingResponse(dingdanId, huifu, dengHuiNote = '') {
  const res = await request({
    url: '/dingdan/zdhf',
    method: 'POST',
    data: {
      dingdan_id: dingdanId,
      huifu,
      deng_hui_note: dengHuiNote,
    },
  });
  return res?.data;
}

export function processZhidingList(list, app, uid, highlightOrderId = '') {
  const defAvatar = getDefaultAvatarUrl(app);
  const oss = app.globalData?.ossImageUrl || '';
  return (list || []).map((item) => {
    let avatar = defAvatar;
    if (item.zhiding_avatar) {
      avatar = item.zhiding_avatar.startsWith('http') ? item.zhiding_avatar : oss + item.zhiding_avatar;
    }
    return {
      ...item,
      isMyZhiding: true,
      zhiding_avatar_full: avatar,
      zhiding_hf_text: item.zhiding_hf_text || ZHIDING_HF_MAP[item.zhiding_hf] || '',
      isHighlighted: highlightOrderId && item.dingdan_id === highlightOrderId,
    };
  }).filter((item) => String(item.zhiding_uid) === String(uid));
}

/** 横幅只展示尚未回复的指定单（已等会接/不想接的不占横幅） */
export function filterZhidingBannerList(list) {
  return (list || []).filter((item) => !item.zhiding_hf);
}
