import { Input, Text, View } from '@tarojs/components'
import type { FC } from 'react'
import { useCallback, useMemo, useRef, useState } from 'react'
import LinkBlueTooth from '../components/bluetooth/LinkBlueTooth'
import styles from './index.module.scss'
import ColorCard from './components/ColorCard'
import Texture from './components/Texture'
import SelectProduct from '@/components/selectProduct/index'
import IconFont from '@/components/iconfont/iconfont'
import { ColorDetailedApi, ColorListApi, ColorSamplingSaveApi, TextureSaveApi } from '@/api/index'
import { breakupUrl, formatHashTag, formatImgUrl, formatUrl } from '@/common/format'
import { alert } from '@/common/common'
import useUploadCDNImg from '@/use/useUploadImage'
import { useBluetooth } from '@/use/contextBlueTooth'
import { toRgb } from '@/common/bluetooth/color/colorSpace'
// 颜色取样
const TakeColor: FC = () => {
  const { state, fetchData } = ColorListApi()
  const { uploadCDNImg } = useUploadCDNImg()
  const { state: detail, fetchData: detailFetchData } = ColorDetailedApi()
  const { state: textureSaveData, fetchData: textureSaveFetchData } = TextureSaveApi()
  const { state: saveData, fetchData: saveFetchData } = ColorSamplingSaveApi()
  const { measureAndGetLab, state: bluetoothState } = useBluetooth()
  const [searchValue, setSearchValue] = useState('')
  const [selectedProduct, setSelectedProduct] = useState<Record<string, any>>({})
  const [listData, setListData] = useState<Record<string, any>[]>([])

  const selectInput = async(event) => {
    if (event) {
      alert.showLoading('正在加载颜色')
      setSelectedProduct(event)
      const res = await fetchData({ id: event.id })
      if (res.success) {
        res.data?.list.forEach((item, index) => {
          item.currnetRgb = item.rgb
          item.currentLab = item.lab
          item.sampling = !(item.currentLab?.l == 0 && item.currentLab?.a == 0 && item.currentLab?.b == 0)
          item.moveBorder = 0
          item.key = index
        })
        setListData(res.data?.list)
        await detailFetchData({ id: event.id })
      }
      alert.hideLoading()
    }
    else {
      setListData([])
      alert.hideLoading()
    }
  }

  const clearSearchValue = () => {
    console.log('asdfasdf')
    setSearchValue('')
  }

  const [currentTakeColorIndex, setCurrentTakeColorIndex] = useState<number | null>(null)

  const handleTakeColor = (index: number) => {
    setCurrentTakeColorIndex(index)
  }

  // const listData = useMemo(() => {
  //   return state.data?.list?.filter(item => {
  //     if (searchValue) {
  //       return formatHashTag(item.product_color_name, item.product_color_code)!.includes(searchValue)
  //     }
  //     return true
  //   })
  // }, [state.data?.list, state])
  const productSelectEl = useRef<any>(null)

  const onSearchInput = (event) => {
    const current = event.detail.value
    if (current === '') {
      setListData(state.data.list)
    }
    else {
      setListData(
        state.data?.list?.filter((item) => {
          return formatHashTag(item.product_color_name, item.product_color_code)!.includes(current)
        }),
      )
    }
  }
  // 底部提交
  const handleSubmit = async() => {
    if (selectedProduct.id) {
      const params = {
        id: selectedProduct.id,
        product_color_absorb: state.data.list.map((item) => {
          return {
            product_color_id: item.product_color_id,
            l: item.currentLab.l,
            a: item.currentLab.a,
            b: item.currentLab.b,
            // absorb_lab_time: `${dayjs(new Date())
            //     .add(0, "day")
            //     .format("YYYY-MM-DD")} 00:00:00`
            absorb_lab_time: new Date(),
          }
        }),
      }
      alert.showLoading('保存中')
      const res = await saveFetchData(params)
      if (res.success) {
        alert.success('保存成功')
      }
      else {
        alert.error('保存失败')
      }
    }
    else {
      productSelectEl.current.clickEvent()
      alert.none('请选择面料')
    }
  }
  // 重置
  const handleReset = () => {
    console.log('handleReset')
    if (selectedProduct.id) {
      setListData(
        state.data.list.map((item) => {
          item.moveBorder = 0
          item.currnetRgb = item.rgb
          item.currentLab = item.lab
          item.sampling = !(item.currentLab?.l == 0 && item.currentLab?.a == 0 && item.currentLab?.b == 0)
          return item
        }),
      )
    }
    else {
      productSelectEl.current.clickEvent()
      alert.none('请选择面料')
    }
  }

  const [labPreview, setLabPreview] = useState({
    currnetRgb: {
      r: 0,
      g: 0,
      b: 0,
    },
  })

  const [showLabPreview, setShowLabPreview] = useState(false)

  const [uploadConfirmState, setUploadConfirmState] = useState(false)

  const handleUploadConfirm = async(file) => {
    setUploadConfirmState(false)
    if (file) {
      if (selectedProduct.id) {
        alert.showLoading('上传中')
        const res = await uploadCDNImg({ path: file.tempFilePath }, 'product', 'product')
        if (res && res?.code == 200) {
          // console.log('图片地址真实',`${IMG_CND_Prefix}${res.url}`);

          // TODO: 回填到存储的地方
          await textureSaveFetchData({
            id: selectedProduct.id,
            texture_url: breakupUrl(res.url),
            upload_texture_time: new Date(),
          })
          await detailFetchData({ id: selectedProduct.id })
          alert.none('上传成功')
          setUploadConfirmState(true)
        }
        else {
          res && alert.none(`${res.message}`)
        }
      }
      else {
        productSelectEl.current.clickEvent()
        alert.none('请选择面料')
      }
    }
    else {
      alert.none('请选择图片')
    }
  }
  const handlePrViewRgb = useCallback((event) => {
    setLabPreview(event)
    setShowLabPreview(true)
  }, [])
  return (
    <>
      <View className={styles.card}>
        <LinkBlueTooth />
        <SelectProduct selectColorId={selectedProduct?.id} onSelect={selectInput} ref={productSelectEl} />
      </View>
      <Texture uploadConfirmState={uploadConfirmState} onUploadConfirm={handleUploadConfirm} list={listData} detail={detail.data} />
      <View className={styles['list-box']}>
        <View className={styles['lb-title']}>
          <Text>颜色列表（{listData?.length ?? 0}）</Text>
          <View className={styles['lb-t-serach']}>
            <View className={styles['lb-t-search-content']}>
              <Input type="text" className={styles['input-bar']} onInput={onSearchInput} placeholder="筛选颜色或颜色编号" />
              <View onClick={clearSearchValue} className={styles['lb-t-sc-clear']}>
                {searchValue.length > 0 && <IconFont name="icon-guanbi" size={36}></IconFont>}
              </View>
            </View>
          </View>
        </View>
        {listData.length
          ? (
            listData.map((item, index) => {
              return (
                <ColorCard
                  currentTakeColorIndex={currentTakeColorIndex}
                  onPreviewRgb={handlePrViewRgb}
                  onTakeColor={handleTakeColor}
                  bluetoothState={bluetoothState}
                  measureAndGetLab={measureAndGetLab}
                  key={index}
                  item={item}
                  index={item.key}
                />
              )
            })
          )
          : (
            <View className={styles['not-list']}>-请取色-</View>
          )}
      </View>
      <View className={styles['fixedBottom-container']}>
        <View onClick={handleReset} hoverClass="filter">
          重置
        </View>
        <View onClick={handleSubmit} className={styles['fb-confirm']}>
          提交
        </View>
      </View>
      {showLabPreview && (
        <View catchMove onClick={() => setShowLabPreview(false)} className={styles['lab-view']}>
          <View
            style={{
              backgroundColor: `rgb(
            ${labPreview?.currnetRgb?.r},
            ${labPreview?.currnetRgb?.g},
            ${labPreview?.currnetRgb?.b}
        )`,
            }}
          ></View>
        </View>
      )}
    </>
  )
}

export default TakeColor
