/* eslint-disable @typescript-eslint/ban-ts-comment */
import React, { ReactNode, useEffect, useState } from 'react';
import classNames from 'classnames';
import { ArrowIcon } from '../common-view';

import './index.scss';

interface oplistI {
  dataSource: any[];
  renderItem: (record: any, index: number) => any;
  renderDetails: (record: any, index: number) => any;
  clickRowOpen: boolean;
  hasBorder: boolean;
  iconSize: number;
}

export default function OPList(props: oplistI) {
  const {
    dataSource,
    renderItem,
    renderDetails,
    clickRowOpen = true,
    hasBorder = true,
    iconSize = 14,
  } = props;
  const [openState, setOpenState] = useState([]);

  useEffect(() => {
    // @ts-ignore
    setOpenState(Array(dataSource.length).fill(false));
  }, [dataSource]);

  const changeOpen = (index: number, from: 'item' | 'icon') => {
    if (
      (clickRowOpen && from === 'icon') ||
      (!clickRowOpen && from === 'item')
    ) {
      return;
    }
    const oldVal = openState[index];
    // @ts-ignore
    openState[index] = !oldVal;
    setOpenState(openState.slice());
  };

  return (
    <div className='operate-list'>
      {Array.isArray(dataSource)
        ? dataSource.map((item, index) => (
            <div
              className={classNames('operate-list__item', {
                'operate-list__item_border': hasBorder,
                'operate-list__item_border_first': hasBorder && index === 0,
              })}
            >
              {/* 展示的内容 */}
              <div
                onClick={() => {
                  changeOpen(index, 'item');
                }}
                className='operate-list__display'
              >
                <div
                  onClick={() => {
                    changeOpen(index, 'icon');
                  }}
                  className={classNames('operate-list__icon', {
                    'operate-list__item_seleced': openState[index],
                  })}
                >
                  <ArrowIcon size={iconSize} color='#196EE6'></ArrowIcon>
                </div>
                <div className='operate-list__display-content'>
                  {renderItem instanceof Function
                    ? renderItem(item, index)
                    : null}
                </div>
              </div>
              {openState[index] ? (
                <div className='operate-list__extends'>
                  {renderDetails instanceof Function
                    ? renderDetails(item, index)
                    : null}
                </div>
              ) : null}
            </div>
          ))
        : null}
    </div>
  );
}
