import { ScrollView, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import type { FC } from 'react'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import { formatDateTime, formatHashTag } from '@/common/format'
import { toRgb } from '@/common/bluetooth/color/colorSpace'
import { usePropsValue } from '@/use/useCommon'

interface PropsType {
  showModal: boolean
  onVisibleChange?: (visible: boolean) => void
  onColor?: Function
}
interface HistoryListItem {
  p_time: number
  lab: number[]
  code: string
  name: string
}
const HistoryColor = (props: PropsType, ref) => {
  const { onColor, showModal, onVisibleChange } = props

  const [visible, setVisible] = usePropsValue({
    value: showModal,
    defaultValue: showModal,
    onChange: onVisibleChange,
  })

  useImperativeHandle(
    ref,
    () => {
      return {
        show: () => setVisible(true),
        hide: () => setVisible(false),
        visible,
      }
    },
    [visible],
  )

  const closeEven = () => {
    console.log('closeEven')
    setVisible(false)
  }
  const [list, setList] = useState<HistoryListItem[]>([])

  // 获取本地列表（无差别存储版本）
  const getList = () => {
    const historyColorList = Taro.getStorageSync('historyColor')
    console.log('historyColorList==>', historyColorList)
    setList(historyColorList || [])
  }
  useEffect(() => {
    if (visible) {
      getList()
    }
  }, [visible])

  // 保留1位小数
  const noScale = (val, num = 1) => {
    return val?.toFixed(num)
  }
  // rgb转换字符串
  const labRoRgb = (val) => {
    const rgb = toRgb(val)
    return `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`
  }

  const getInfo = (val) => {
    const index = list.findIndex(item => item.p_time == val.p_time)
    const tempList = JSON.parse(JSON.stringify(list))
    tempList.splice(index, 1)
    tempList.unshift(val)
    setList(tempList)
    Taro.setStorageSync('historyColor', tempList)
    onColor && onColor(val)
    setVisible(false)
  }

  return (
    <View className={styles.history_color}>
      <Popup title="历史取样记录 ( 最近30条 )" show={visible} onClose={closeEven}>
        <ScrollView className={styles['selectList-scroll-color']} scrollY>
          <View className={styles.selectCon}>
            {list?.length
              ? (
                list.map((item, index) => {
                  return (
                    <View key={index} className={styles.selectList} onClick={() => getInfo(item)}>
                      <View className={styles.rgbColor} style={{ background: labRoRgb(item.lab) }}></View>
                      <View className={styles.product_con}>
                        <View className={styles.product_name}>{formatHashTag(item.code, item.name)}</View>
                        <View className={styles.date}>{formatDateTime(item.p_time)}</View>
                      </View>
                      <View className={styles.labColor}>
                        <View className={styles.labColor_btn}>+</View>
                        <View className={styles.labColor_con}>
                          <View className={styles.L}>L*：{noScale(item.lab[0])}</View>
                          <View className={styles.a}>a*：{noScale(item.lab[1])}</View>
                          <View className={styles.b}>b*：{noScale(item.lab[2])}</View>
                        </View>
                      </View>
                    </View>
                  )
                })
              )
              : (
                <View className={styles.noData}>暂无数据</View>
              )}
          </View>
        </ScrollView>
      </Popup>
    </View>
  )
}
export default forwardRef(HistoryColor)
