import { Button, ScrollView, View } from '@tarojs/components'
import Taro, { useDidShow, usePullDownRefresh, useRouter } from '@tarojs/taro'
import React, { ReactNode, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'
import { alert, goLink } from '@/common/common'
import { formatDateTime, formatPriceDiv, formatWeightDiv } from '@/common/format'
import IconFont from '@/components/iconfont/iconfont'
import Popup from '@/components/popup'
import { MpPurchaserLabelAdd, MpPurchaserList } from '@/api/customer'
import NormalButton from '@/components/normalButton'

interface Props {
  showPopup: boolean
  handClose: () => void
  purchaser_id?: string | number
  diseShow?: () => void
}
const TagPopup = (props: Props, ref) => {
  const router = useRouter()

  const { fetchData } = MpPurchaserList()
  // 标签
  const [modeList, setModeList] = useState<any[]>([])
  const getList = async() => {
    const res = await fetchData()
    if (res.data) {
      setModeList([...res.data.list])
    }
  }

  // 选择标签
  const handCheckMode = (item) => {
    modeList.map((it) => {
      if (it.id === item.id) {
        it.checked = !it.checked
      }
      return it
    })
    setModeList([...modeList])
  }

  const handReset = () => {
    modeList.map((it) => {
      it.checked = false
      return it
    })
    setModeList([...modeList])
  }
  const { fetchData: addFetch } = MpPurchaserLabelAdd()
  const handSure = async() => {
    const arr: any[] = []
    const fltArr = modeList.filter((item) => { return item.checked })
    fltArr.forEach((item) => {
      arr.push({
        label_id: item.id,
      })
    })
    Taro.showLoading({
      title: '请稍等...',
      mask: true,
    })
    const res = await addFetch({ binding_label: arr, purchaser_id: Number(router.params.purchaser_id) })
    if (res.msg == 'success') {
      Taro.showToast({
        icon: 'success',
        title: '成功',
      })
      Taro.hideLoading()
    }
    else {
      Taro.showToast({
        icon: 'error',
        title: res.msg,
      })
      Taro.hideLoading()
    }
    props?.diseShow?.()
  }

  const isDisabled = useMemo(() => {
    const arr = modeList.filter((item) => { return item.checked })
    if (arr.length) {
      return false
    }
    else {
      return true
    }
  }, [modeList])

  const choseNums = useMemo(() => {
    const arr = modeList.filter((item) => { return item.checked })
    return arr.length
  }, [modeList])

  useImperativeHandle(ref, () => ({
    modeList,
    setModeList,
  }))
  useEffect(() => {
    getList()
  }, [])
  return (
    <Popup title="选择标签" show={props.showPopup} onClose={() => { props.handClose() }}>
      <ScrollView scrollY className={styles.scrollView}>
        <View className={styles.thirdBox}>
          <View className={styles.thirdTopfont}>自定义标签分组</View>
          <View className={styles.flexModebox}>
            {modeList.map((item, index) => {
              return (
                <View
                  onClick={() => {
                    handCheckMode(item)
                  }}
                  className={classnames(styles.modeBox, item.checked && styles.activemodeBox)}
                  key={index}
                >
                  {item.name}
                </View>
              )
            })}
          </View>
        </View>
      </ScrollView>
      <View className={styles.bottomBox}>
        <NormalButton onClick={handReset} customClassName={styles.resetBox} type="primary" size="normal" plain circle>重置</NormalButton>
        <NormalButton onClick={handSure} disabled={isDisabled} customClassName={classnames(!isDisabled && styles.activeButton, styles.button)} type="primary" size="normal" plain circle>保存({choseNums})</NormalButton>
      </View>
    </Popup>
  )
}
export default memo(forwardRef(TagPopup))
