import React from 'react';
import { View } from '@tarojs/components';
import { ROLE_CITIZEN } from '@/utils/user';
import { getIndexData } from '@/services/stat';
import useShow from '@/layouts/hooks/useShow';
import style from './stat-card.module.less';

export default React.forwardRef((props, ref) => {
  const { duty } = props;

  const [list, setList] = React.useState([]);
  const dutyRef = React.useRef();
  dutyRef.current = duty;

  const classNames = React.useMemo(() => {
    return [
      style['stat-card-box'],
      !duty || duty == ROLE_CITIZEN ? style['no-bg-effect'] : false
    ].filter(Boolean).join(' ');
  }, [duty])

  React.useEffect(() => {
    if (duty) {
      getIndexData(duty).then(setList);
    }
  }, [duty]);

  React.useImperativeHandle(ref, () => ({
    refresh: () => {
      if (duty) {
        getIndexData(duty).then(setList);
      }
    }
  }), [duty]);

  useShow(() => {
    if (dutyRef.current) {
      getIndexData(dutyRef.current).then(setList);
    }
  });

  return (
    <View className={classNames}>
      <View className={style['stat-card']}>
        {
          list.map(x => (
            <View key={x.name} className={style.item}>
              <View>{x.value}</View>
              <View className={style.sub}>{x.name}</View>
            </View>
          ))
        }
      </View>
    </View>
  )
})
