
import { Image, Text, Textarea, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import { useBluetooth } from '../../use/contextBlueTooth'
import { toRgb } from '../../common/bluetooth/color/colorSpace'
import LinkBlueTooth from './compoents/bluetooth/LinkBlueTooth'
import styles from './index.module.scss'
import { productabsorbcontrast } from '@/api/mine'

export default () => {
  // 搜索参数
  const [searchField, setSearchField] = useState({
    l1: '',
    a1: '',
    b1: '',
    l2: '',
    a2: '',
    b2: '',
  })
  interface ColorList {
    one?: any
    two?: any
  }
  const [colorList, setColorList] = useState<ColorList>({
    one: null,
    two: null,
  })
  const { state: colorState, measureAndGetLab } = useBluetooth()

  const getLab = async(val) => {
    if (colorState.connected) {
      const res = await measureAndGetLab()
      if (val === 1) {
        setColorList({ ...colorList, one: res })
      }
      else {
        setColorList({ ...colorList, two: res })
      }
    }
    else {
      Taro.showToast({
        title: '请链接设备',
        icon: 'none',
      })
    }
  }
  const getNowTime = () => {
    const yy = new Date().getFullYear()
    const MM = (new Date().getMonth() + 1) < 10 ? `0${new Date().getMonth() + 1}` : (new Date().getMonth() + 1)
    const dd = new Date().getDate() < 10 ? `0${new Date().getDate()}` : new Date().getDate()
    const HH = new Date().getHours() < 10 ? `0${new Date().getHours()}` : new Date().getHours()
    const mm = new Date().getMinutes() < 10 ? `0${new Date().getMinutes()}` : new Date().getMinutes()
    const ss = new Date().getSeconds() < 10 ? `0${new Date().getSeconds()}` : new Date().getSeconds()
    return `${yy}-${MM}-${dd} ${HH}:${mm}:${ss}`
  }
  // 监听lab数据变化
  const [blueToothColor, setBlueToothColor] = useState('')
  const [blueToothColorTwo, setBlueToothColorTwo] = useState('')
  const [time, setTime] = useState('')
  const [timeTwo, setTimeTwo] = useState('')
  useEffect(() => {
    if (colorState.deviceLab) {
      if ((colorList as any).one?.constructor === Object) {
        const rgb = toRgb([(colorList as any).one?.L, (colorList as any).one?.a, (colorList as any).one?.b])
        setBlueToothColor(`rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`)
        setTime(getNowTime())
        setSearchField({ ...searchField, l1: rgb[0], a1: rgb[1], b1: rgb[2] })
      }
      if ((colorList as any).two?.constructor === Object) {
        const rgb = toRgb([(colorList as any).two?.L, (colorList as any).two?.a, (colorList as any).two?.b])
        setBlueToothColorTwo(`rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`)
        setTimeTwo(getNowTime())
        setSearchField({ ...searchField, l2: rgb[0], a2: rgb[1], b2: rgb[2] })
      }
    }
  }, [colorList])
  const reset = () => {
    setColorList({})
    setBlueToothColor('')
    setBlueToothColorTwo('')
    setTime('')
    setTimeTwo('')
    setData('')
    setResult('')
  }
  const [data, setData] = useState('')
  const [result, setResult] = useState('')
  const { fetchData } = productabsorbcontrast()
  const handTake = async() => {
    if (searchField.l1 === '') {
      Taro.showToast({
        title: '请填充基础样品',
        icon: 'none',
      })
      return
    }
    if (searchField.l2 === '') {
      Taro.showToast({
        title: '请填充对比样品',
        icon: 'none',
      })
      return
    }
    const query = {
      ...searchField,
    }
    const res = await fetchData(query)
    if (res.data) {
      setData(res.data)
      const diffarray = [
        res.data.reddish && '偏红',
        res.data.yellowish && '偏黄',
        res.data.greenish && '偏绿',
        res.data.bluish && '偏蓝',
        res.data.whitish && '偏亮',
        res.data.darker && '偏暗',
      ]
      const resCont = diffarray.filter(item => item).join(',')
      setResult(resCont)
    }
  }
  return (
    <View className={styles.body}>
      {/* <View className={styles.topBox}>
                <View className={styles.leftBox}>
                    <View className={styles.leftFont}>蓝牙设备</View>
                    <View className={styles.borderBox}></View>
                    <View className={styles.cricleBox}></View>
                    <View className={styles.notNet}></View>
                </View>
                <Text className={classnames("iconfont icon-a-moreback", styles.iconMore)}></Text>
            </View> */}
      <LinkBlueTooth />
      <View className={styles.contBox} >
        <View className={styles.firstBox} style="margin-right:27px">
          <View className={styles.firstLeftName} >基础样品</View>
          {
            blueToothColor === ''
                        && <View className={styles.firstLeftbox} onClick={() => getLab(1)}>
                          <View className={styles.clickFont} >点击取色</View>
                        </View>
          }
          {blueToothColor && <View className={classnames(styles.color_bock)} onClick={() => getLab(1)} style={{ background: blueToothColor }}></View>

          }
          {
            time === '' && <View className={styles.nameColor}>--</View>
          }
          {
            time && <View className={styles.nameColor}>{time}</View>
          }
        </View>
        <View className={styles.firstBox}>
          <View className={styles.firstLeftName}>对比样品</View>
          {
            blueToothColorTwo === ''
                        && <View className={styles.firstLeftbox} onClick={() => getLab(2)}>
                          <View className={styles.clickFont} >点击取色</View>
                        </View>
          }
          {blueToothColorTwo && <View className={classnames(styles.color_bocktwo)} onClick={() => getLab(2)} style={{ background: blueToothColorTwo }}></View>

          }
          {
            timeTwo === '' && <View className={styles.nameColor}>--</View>
          }
          {
            timeTwo && <View className={styles.nameColor}>{timeTwo}</View>
          }
        </View>
      </View>
      <View className={styles.reslutBox}>
        <View className={styles.reslutTitle}>
          <View className={styles.titleLeft}>测量结果</View>
          {
            (data as any).ciede_2000 >= 1
                        && <View className={styles.titleRiht}>不合格</View>
          }
          {
            (data as any).ciede_2000 <= 1
                        && <View className={styles.titleRiht1}>合格</View>
          }

        </View>
        {
          data === ''
                    && <View className={styles.notResult}>暂无数据</View>
        }
        {
          data
                    && <View className={styles.notBox}>
                      <View className={styles.notLeft}>色差值: {(data as any).ciede_2000}</View>
                      {
                        !(data as any).reddish && !(data as any).yellowish && !(data as any).greenish && !(data as any).bluish && !(data as any).whitish && !(data as any).darker
                            && <View className={styles.notright}>无明显色差</View>
                      }
                      {
                        result
                            && <View className={styles.notright}>{result}</View>
                      }
                    </View>
        }
      </View>
      <View className={styles.bottomBox}>
        <View className={styles.leftBtn} onClick={() => reset()}>重置</View>
        <View className={styles.rightBtn} onClick={() => handTake()}>提交</View>
      </View>
    </View >
  )
}
