import { randomUUID } from '@/tools';

type Data<T extends any = any> = Record<string, T>

export function fromSchemeRequest(data: Data) {
  return {
    children: data?.types?.map((item: Data) => {
      return {
        id: data?.id ?? randomUUID(),
        title: item?.type || '',
        children: item?.groups?.map((item: Data) => {
          return {
            ...fragment(item),
            descriptions: item?.attrs?.map(fragment) ?? [],
            media: fromSchemeMedia(item.items ?? []),
            goods: fromSchemeGoods(item),
          };
        }) ?? [],
      };
    }) ?? [],
    miniProgramURL: data?.appletImg,
    payLock: data?.payLock,
  } as { children: SchemeProps[], miniProgramURL?: string; payLock?: boolean };
}


function fragment(data: Data<string>) {
  return {
    id: data?.id ?? randomUUID(),
    title: data?.name || '',
    description: data?.description,
  };
}

export interface SchemeProps {
  id: string;
  title: string;
  children: {
    id: string;
    title: string;
    description?: string;
    descriptions: {
      id: string;
      title: string;
      description?: string;
    }[];
    goods?: SchemeGoodsProps;
    media: SchemeMediaProps[];
  }[];
}

export interface SchemeMediaProps {
  title: string;
  description: string;
  type: 'image' | 'video' | 'text';
  url: string;
  poster: string;
}

function fromSchemeMedia(data: Data[]) {
  const media: SchemeMediaProps[] = [];
  for ( const item of data ) {
    const type = item.mediaUrl ? 'video' : item.imgUrl ? 'image' : item.name ? 'text' : null;
    if ( !type ) continue;

    const title = item.type === 'medicine' ? [ item.name, `${ item.doase || '' }${ item.unit || '' }` ].filter(Boolean).join(' ') : item.name;
    media.push({
      type, title, description: item.description || '',
      url: item.mediaUrl ?? item.imgUrl, poster: item.imgUrl,
    });
  }
  return media;
}

export interface SchemeGoodsProps {
  type: 'link' | 'miniprogram' | string;
  value: string;
  label?: string;
}

function fromSchemeGoods(data?: Data): SchemeGoodsProps | void {
  const result = {
    type: { URL: 'link' }[<string>data?.buyType] ?? data?.buyType,
    label: data?.buyName ?? '去购买',
    value: data?.buyUrl,
  } satisfies SchemeGoodsProps;
  if (result.type === 'miniprogram') { result.value = data.miniprogram; }
  return result.value ? result : void 0;
}