import { Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { FC } from 'react'
import { useEffect, useMemo, useState } from 'react'
import LineBluetooth from '../components/bluetooth/LinkBlueTooth'
import styles from './index.module.scss'
import HistoryColor from './components/HistoryColor'
import LabColor from './components/LabColor'
import RecommendColor from './components/RecommendColor'
import SelectProduct from '@/components/selectProduct'
import { useBluetooth } from '@/use/contextBlueTooth'
import { FindColorListApi } from '@/api/index'
import Loading from '@/components/loading'
import { throttle } from '@/common/util'

const FindColor: FC = () => {
  const { measureAndGetLab, disconnect, state: bluetoothState } = useBluetooth()
  const { state: colorState, fetchData: ApiFindColorList } = FindColorListApi()

  const [list, setList] = useState([])
  const [product, setProduct] = useState<Record<string, any>>({})

  // 获取数据
  const getData = async(lab) => {
    const res = await ApiFindColorList({
      product_id: product.id,
      l: lab[0],
      a: lab[1],
      b: lab[2],
    })
    if (res.success) {
      setList(res.data.list)
    }
  }

  const [labArray, setlabArray] = useState<Array<any>>([])
  const [labtime, setLabtime] = useState<any>(+new Date())
  // 点击获取lab按钮
  const labEven = throttle(async() => {
    if (!bluetoothState.connected) {
      Taro.showToast({ title: '请先链接设备', icon: 'none' })
      return
    }
    if (!product) {
      Taro.showToast({ title: '请选择面料', icon: 'none' })
      return
    }
    await measureAndGetLab()
  }, 500)

  const selectInput = (val) => {
    setProduct(val)
    setLabtime('')
    setlabArray([])
    setList([])
  }

  const getColor = (val) => {
    console.log('val===>', val)
    setList([])
    setlabArray(val.lab)
    setLabtime(val.p_time)
    setProduct({
      code: val.code,
      default: val.default,
      id: val.id,
      name: val.name,
    })
    getData(val.lab)
  }
  const [showHistory, setShowHistory] = useState(false)

  const handleVisibleChange = (visible) => {
    setShowHistory(visible)
  }

  const ResultContainer = useMemo(() => {
    if (!colorState.loading && list?.length > 0) {
      return <RecommendColor customStyle={{ flex: 1 }} list={list} />
    }
    else if (!colorState.loading && labArray.length == 0) {
      return <View className={styles.noList}>-请取色-</View>
    }
    else if (!colorState.loading && labArray.length > 0 && list?.length == 0) {
      return <View className={styles.noList}>-暂无数据-</View>
    }
    else if (colorState.loading) {
      return <Loading />
    }
  }, [colorState, list])

  // 历史取样
  const historyShowEven = () => {
    setShowHistory(true)
  }
  // 本地存储取色记录(无差别存储版本)
  const localSave = (lab) => {
    const historyColorList = Taro.getStorageSync('historyColor') || []
    const obj = {
      ...product,
      p_time: +new Date(),
      lab,
    }
    historyColorList.unshift(obj)
    if (historyColorList.length > 30) { historyColorList.pop() }
    Taro.setStorageSync('historyColor', historyColorList)
  }
  useEffect(() => {
    if (!product) {
      Taro.showToast({ title: '请选择面料', icon: 'none' })
      return
    }
    if (bluetoothState.deviceLab) {
      setLabtime(+new Date())
      setlabArray([bluetoothState.deviceLab.L, bluetoothState.deviceLab.a, bluetoothState.deviceLab.b])
      // console.log('state.labArray::',state.labArray)
      localSave([bluetoothState.deviceLab.L, bluetoothState.deviceLab.a, bluetoothState.deviceLab.b])
      getData([bluetoothState.deviceLab.L, bluetoothState.deviceLab.a, bluetoothState.deviceLab.b])
    }
  }, [bluetoothState.deviceLab])

  return (
    <View className={styles.findColor_main}>
      <View className={styles.findColor_main_search}>
        <LineBluetooth></LineBluetooth>
        <SelectProduct selectColorId={product?.id} onSelect={selectInput} />
      </View>
      <LabColor lab={labArray} time={labtime} onLab={labEven} />
      <View className={styles.findColor_main_title}>
        <View className={styles.RecommendColor_title}>
          <Text>推荐数 ({list?.length})</Text>
          <Text onClick={historyShowEven}>历史取样</Text>
        </View>
      </View>
      <HistoryColor showModal={showHistory} onColor={getColor} onVisibleChange={handleVisibleChange} />
      {ResultContainer}
      <View className="common_safe_area_y"></View>
    </View>
  )
}

export default FindColor
