import {useState, useEffect} from 'react'
import Request from "../utils/request"

interface IotCopumns {
  id: number
  type_code: number
  type_name: string
}

/**
 * @description 获取IOT 设备类型列表
 */
export const useIotList = () => {
  const [state, setState] = useState<{ loading: boolean; dataSource: IotCopumns[] }>({loading: false, dataSource: []})
  const request = () => {
    Request.sendRequest({
      url: '/v1/iot/type_list'
    }).then((data: any) => {
      setState(preState => ({...preState, loading: false, dataSource: data.list}))
    }).catch(error => {
      setState(preState => ({...preState, loading: false}))
    })
  }
  return {state, request} as const
}
/**
 * @description 获取验Iot 设备列表
 */
export const useDeviceList = () => {
  const [state, setState] = useState<{
    loading: boolean;
    dataSource: IotCopumns[];
    online: number;
    offline: number;
    total: number
  }>({loading: false, dataSource: [], online: 0, offline: 0, total: 0})
  const request = (params: { page: number, page_size: number; device_code: number }) => {
    Request.sendRequest({
      url: '/v1/iot/list',
      params
    }).then((data: any) => {
      setState(preState => ({...preState, loading: false, ...data, dataSource: data.list}))
    }).catch(error => {
      setState(preState => ({...preState, loading: false}))
    })
  }
  return {state, request} as const
}

interface IotLastInfoRecord {
  name: string;
  unit: string;
  value: string;
}

/**
 * @description 获取 IOT 设备实时数据
 */

export const useDeviceInfo = () => {
  const [state, setState] = useState<{ list: IotLastInfoRecord[]; loading: boolean; pic: string }>({
    loading: false,
    list: [],
    pic: ""
  })
  const request = (params: { sn: number; device_code: number }) => {
    Request.sendRequest({
      url: '/v1/iot/last',
      params
    }).then((data: any) => {
      setState(preState => ({...preState, loading: false, ...data, dataSource: data.list}))
    }).catch(error => {
      setState(preState => ({...preState, loading: false}))
    })
  }
  return {state, request} as const
}