import React from 'react';
import TemplateItem from './TemplateItem';
import styles from './TemplateList.less';

export default function OftenTemplates({
  userId,
  list = [],
  onClick,
}: {
  userId: number;
  list: {
    id: number;
    thumb: string;
    name: string;
    info: string;
    measureType: number;
    purchased: boolean;
    category?: string;
  }[];
  onClick: (id) => void;
}) {
  return (
    <>
      <div className={styles.title}>常用模板</div>
      <div className={styles.group}>
        <div className={styles.createRect} onClick={() => onClick('')}>
          <div className={styles.createRectCont}>
            <p></p>
            <span>空白模板</span>
          </div>
        </div>
        {oftenTemplates
          .read(userId)
          .map((templateId) => {
            const item = list.find((item) => item.id === templateId);
            if (!item) return;
            return (
              <TemplateItem
                category={item?.category}
                key={item.id}
                thumb={item.thumb}
                name={item.name}
                info={item.info}
                type={item.measureType}
                purchased={item.purchased}
                onCreate={() => onClick(item.id)}
              />
            );
          })
          .filter((v) => v)}
      </div>
    </>
  );
}

export const oftenTemplates = (function () {
  const add = (userId, templateId) => {
    let list = read(userId);
    if (~list.indexOf(templateId)) {
      list.splice(list.indexOf(templateId), 1);
      list.unshift(templateId);
    } else {
      list.unshift(templateId);
      list = list.slice(0, 3);
    }
    localStorage.setItem('often_templates_' + userId, JSON.stringify(list));
  };
  const read = (userId) => JSON.parse(localStorage.getItem('often_templates_' + userId) || '[]');
  return { add, read };
})();
