import React, { useState } from 'react';
import './ExpandableTable.css';

export default function ExpandableTable({ data = [], columns = [], idKey = 'id' }) {
  const [openSet, setOpenSet] = useState({});
  const toggle = (id) => setOpenSet((s) => ({ ...s, [id]: !s[id] }));

  return (
    <table className="kole-exptable">
      <thead>
        <tr>
          <th style={{ width: 40 }} />
          {columns.map((c) => (
            <th key={c.key}>{c.title}</th>
          ))}
        </tr>
      </thead>
      <tbody>
        {data.map((row) => (
          <React.Fragment key={row[idKey]}>
            <tr className="kole-row">
              <td>
                <button
                  className={'kole-exp-toggle' + (openSet[row[idKey]] ? ' is-open' : '')}
                  onClick={() => toggle(row[idKey])}
                >
                  ▶
                </button>
              </td>
              {columns.map((c) => (
                <td key={c.key}>{row[c.key]}</td>
              ))}
            </tr>
            {openSet[row[idKey]] && (
              <tr className="kole-exp-row">
                <td />
                <td colSpan={columns.length}>
                  <div className="kole-exp-panel">
                    <div>备注：{row.detail.note}</div>
                    <div className="kole-exp-sub">
                      {row.detail.items.map((it, i) => (
                        <div key={i}>· {it}</div>
                      ))}
                    </div>
                  </div>
                </td>
              </tr>
            )}
          </React.Fragment>
        ))}
      </tbody>
    </table>
  );
}
