import PageContent from '@/components/PageContent';
import PageTitle from '@/components/PageTitle';
import { queryDevice, queryScanDuration } from '@/services/controller';
import { UnityAction } from '@/utils/utils';
import { useParams, useRequest } from '@umijs/max';
import { useCallback, useEffect } from 'react';
import styles from './index.less';

let timer;
function Hardware() {
  const { projectId } = useParams();

  const { data, run, loading } = useRequest(queryDevice, {
    manual: true,
    onSuccess(data) {
      UnityAction.sendMsg('devLocate', JSON.stringify(data.list));
    },
  });

  const { data: draw } = useRequest(queryScanDuration, {
    defaultParams: [projectId],
    formatResult(res) {
      return res.data.draw;
    },
  });

  const getDeviceIconClassName = useCallback((status) => {
    let statusClassName = '';
    if (status == 2) {
      statusClassName = styles.error;
    } else if (status == 3) {
      statusClassName = styles.offline;
    }

    return `${styles.icon} ${statusClassName}`;
  });
  const onHandleClick = item => {
    UnityAction.sendMsg('SingleDevLocate', JSON.stringify([item]));
  };
  useEffect(() => {
    if (!draw) return;
    run(projectId);
    timer = setInterval(() => {
      run(projectId);
    }, draw);
    return () => clearInterval(timer);
  }, [draw]);

  return (
    <PageContent closeable={false}>
      <PageTitle onReturn={() => UnityAction.sendMsg('menuItem', '智能管控')}>
        设备定位
      </PageTitle>

      {/* <Spin spinning={loading}> */}
      {data?.list?.map((item) => (
        <div
          key={item.id}
          className={`card-box ${styles.item}`}
          style={{ justifyContent: 'space-between' }}
          onClick={() => onHandleClick(item)}
        >
          <div>
            <i
              className={getDeviceIconClassName(item.mobile_device_status)}
            ></i>
            {item.mobile_device_name}
          </div>

          <div onClick={() => onHandleClick(item)}>定位</div>
        </div>
      ))}
      {/* </Spin> */}
    </PageContent>
  );
}

export default Hardware;
