import * as React from 'react';
import { IRenderer } from '../../index.data';
import styles from './index.less';
import { ExpandedIcon, CollapsedIcon } from '../../../icons';
import { renderCatalogNo, hash } from 'valor-app-utils';
import { IStoreState } from '../../../index.data';
import { getRowNoCellValue } from '../../../store/selectors';
import { RendererProps } from '../../..';
import { connect } from 'unistore/react';
import equals from 'fast-deep-equal';
import RuntimeContext from '../../../RuntimeContext';

type Props = RendererProps<{ collapsed: boolean; path: number[]; isLeaf: boolean }>;

class RowNoRenderer extends React.Component<Props, any> {
  static contextType = RuntimeContext;
  context!: React.ContextType<typeof RuntimeContext>;

  constructor(props: any) {
    super(props);
  }

  shouldComponentUpdate(nextProps: Props, nextState: any) {
    return !equals(this.props, nextProps);
  }

  render() {
    const { rowNoTemplates } = this.context!;
    const { value, style } = this.props;
    if (!value) return null;

    const { collapsed, path, isLeaf } = value!;

    const content = renderCatalogNo(rowNoTemplates[path.length - 1], path.map(i => i + 1));

    return (
      <div className={styles['container']} style={style}>
        <div className={styles['h-box']}>
          <div className={styles['icon-container']}>
            {isLeaf ? null : collapsed ? <CollapsedIcon /> : <ExpandedIcon />}
          </div>
          <div className={styles['content']}>{content}</div>
        </div>
      </div>
    );
  }
}

// hack: 避免开发期数百个 performance 检查点 ( 仅这里就卡几秒, 当然只限开发期, 生产期无此问题 )
// 技巧: 将value用 {valueStr => value} 的方式缓存到map中
// 这样一来, 返回的始终是引用
// 在unitstore中进行比较时, 是使用 === 比较
// 如果没有变化, 根本不会执行下面的forceupdate
const valueRefMap: Record<string, ReturnType<typeof getRowNoCellValue>> = {};
const mapState = (state: IStoreState, props: any) => {
  const value = getRowNoCellValue(state, props.id);
  const valuestr = JSON.stringify(value);
  const existedValue = valueRefMap[valuestr];
  if (existedValue) {
    return { value: existedValue };
  }

  valueRefMap[valuestr] = value;
  return { value };
};

export default connect<any, any, IStoreState, any>(mapState)(RowNoRenderer);
