import { queryIotList } from '@/services/controller';
import { UnityAction } from '@/utils/utils';
import { useParams, useRequest } from '@umijs/max';
import { Spin } from 'antd';
import { useEffect, useState } from 'react';
import styles from '../index.less';

const Work = (props) => {
  const { projectId } = useParams();
  const [select, setSelect] = useState();

  const { data, loading } = useRequest(queryIotList, {
    defaultParams: [projectId],
    onSuccess(res) {
      UnityAction.sendMsg('ACData', JSON.stringify(res.list));
    },
  });

  const getIconStatus = (status) => {
    if (status == 1) return '';
    if (status == 2) return styles.offline;
    if (status == 3) return styles.error;
  };

  const onHandleSelect = (item) => {
    setSelect(item.id);
    UnityAction.sendMsg('ACItem', String(item.id));
  };

  useEffect(() => {
    UnityAction.addEventListener('ACItem', (id) => {
      setSelect(id);
    });

    return () => UnityAction.off('ACItem');
  }, []);

  return (
    <div>
      <div className={styles.top}>
        <div className={styles.left}>
          <img
            className={styles.img}
            src={require('@/assets/air-conditioner.png')}
          />
          <div>
            <div className="value-number">{data?.pagination?.total}</div>
            空调数量
          </div>
        </div>
        <div className={styles.right}>
          <div>
            <i className={styles.icon}></i> 在线：{data?.online_count}
          </div>
          <div>
            <i className={`${styles.icon} ${styles.offline}`}></i> 离线：
            {data?.offline_count}
          </div>
        </div>
      </div>
      <Spin spinning={loading}>
        <div className={styles.listContent}>
          {data?.list?.map((item) => (
            <div
              key={item.id}
              onClick={() => onHandleSelect(item)}
              className={`card-box ${styles.item} ${
                select == item.id ? 'card-select' : ''
              }`}
            >
              <i className={`${styles.icon} ${getIconStatus(item.status)}`}></i>
              {item.name}
            </div>
          ))}
        </div>
      </Spin>
    </div>
  );
};

export default Work;
