
import { ScrollView, Text, View } from '@tarojs/components'
import Taro, { usePullDownRefresh, useReady } from '@tarojs/taro'
import classNames from 'classnames'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import Search from '@/components/searchBar'
import IconText from '@/components/iconText'
import NormalButton from '@/components/normalButton'
import LayoutBlock from '@/components/layoutBlock'
import Divider from '@/components/divider'
import Cell from '@/components/cell'
import TimePickerPopup from '@/components/timePickerPopup'
import { alert } from '@/common/common'
import type { InviteCodePopupRef } from '@/components/inviteCodePopup'
import InviteCodePopup from '@/components/inviteCodePopup'
import { GetInvitationRecordList } from '@/api/share'
import InfiniteScroll from '@/components/infiniteScroll'
import { dataLoadingStatus, debounce, getFilterData } from '@/common/util'
import { formatDateTime } from '@/common/fotmat'
import IconFont from '@/components/iconfont/iconfont'

const InviteCord = () => {
  const [formData, setFormData] = useState<{
    start_time?: string
    end_time?: string
    name?: string
    size?: number
    page?: number
  }>({
    size: 15,
    page: 1,
  })
  const onSearch = debounce((e) => {
    pageNum.current.page = 1
    setFormData(val => ({ ...val, name: e, size: 10 }))
    pageNum.current = { size: 10, page: 1 }
  }, 300)

  // 获取被邀请记录
  const { fetchData: getInviteeRecordAPI, state } = GetInvitationRecordList()
  const getInviteeRecord = async() => {
    const res = await getInviteeRecordAPI(getFilterData(formData))
    if (res.success) {
      setRecordList({ list: res.data.list, total: res.data.total })
      Taro.stopPullDownRefresh()
    }
  }

  // 页面下拉刷新
  usePullDownRefresh(() => {
    setFormData(prev => ({ ...prev, size: 10 }))
  })

  useEffect(() => {
    getInviteeRecord()
  }, [formData])

  const handleConfirm = () => {
    inviteCodePopupRef.current?.startDrawPoster()
  }

  const [recordList, setRecordList] = useState<{ list: any[]; total: number }>({ list: [{}, {}], total: 0 })

  const [showTime, setShowTime] = useState(false)

  const isFilter = useMemo(() => {
    if (formData?.start_time || formData?.end_time) {
      return true
    }
    return false
  }
  , [formData?.start_time, formData?.end_time])

  const handleClickTimePicker = () => {
    setShowTime(true)
  }

  const handClose = () => {
    setShowTime(false)
  }
  const onSelectDate = useCallback((val) => {
    if (!val.value?.start && !val.value?.end) {
      alert.error('请选择日期')
    }
    else {
      setFormData(e => ({ ...e, start_time: val.value.start, end_time: val.value.end }))
    }
    console.log('val::', val)
    handClose()
  }, [])

  const handleReset = () => {
    setFormData(e => ({
      ...e,
      start_time: '',
      end_time: '',
    }))
    handClose()
  }

  const total = useMemo(() => {
    if (formData.name || isFilter) {
      return recordList.list.length
    }
    return recordList.total
  }, [isFilter, formData.name, recordList])

  const inviteCodePopupRef = useRef<InviteCodePopupRef>(null)

  // 上拉加载数据
  const pageNum = useRef({ size: formData.size, page: formData.page })
  const getScrollToLower = () => {
    if (recordList.list.length < recordList.total) {
      pageNum.current.page!++
      const size = pageNum.current.size! * pageNum.current.page!
      setFormData(prev => ({ ...prev, size }))
    }
  }

  const statusMore = useMemo(() => {
    return dataLoadingStatus({ list: recordList.list, total: recordList.total, status: state.loading })
  }, [recordList, state])

  const handleCell = (phone: string) => {
    Taro.makePhoneCall({
      phoneNumber: phone,
    })
  }

  return (
    <View className={styles.main}>
      <View className={styles.search}>
        <Search showBtn={false} changeOnSearch={onSearch} placeholder="请输入邀请人" >
          <View className={styles.flexBox} onClick={handleClickTimePicker}>
            <IconText svg iconName="icon-xuanzhongshijian" text="日期" color={isFilter ? '#4581ff' : '#3a3a3a'} textCustomStyle={{ color: isFilter ? '#4581ff' : '#3a3a3a' }} customClass={styles['icon--manage--cancel']} />
          </View>
        </Search>
      </View>
      <View className={styles.content}>
        <View className={styles.total}>共 {total} 条数据</View>
        <InfiniteScroll safeAreaInsetBottom={false} selfonScrollToLower={getScrollToLower} statusMore={statusMore}>
          <View className={styles.scroll_list}>
            {recordList.list.map((item, index) => {
              return (
                <LayoutBlock key={index} circle customClassName={styles.layout}>
                  <View className={styles.title}>
                    <View className={styles.subTitle}>
                      <Text>
                        {item?.passive_invited_user_name}
                      </Text>
                      <View className={styles.cell} onClick={() => handleCell(item?.passive_invited_user_phone)}>
                        <IconFont name="icon-dianhua" size={30}></IconFont>
                        <Text>拨打</Text>
                      </View>
                    </View>
                    <View>{item?.invitation_way_name}</View>
                  </View>
                  <Divider direction="horizontal" customStyles={{ margin: '12px 0', marginBottom: '6px' }}></Divider>
                  <View className={styles.block_content}>
                    <Cell customDescClassName={styles.cell_desc} title="邀请人：" desc={item?.invite_user_name || '暂无信息'}></Cell>
                    <Cell customDescClassName={styles.cell_desc} title="邀请时间：" desc={formatDateTime(item?.invitation_time, 'YYYY-MM-DD') || '暂无信息'}></Cell>
                  </View>
                </LayoutBlock>
              )
            })}
          </View>
        </InfiniteScroll>
      </View>
      <View className={styles.bottomBar}>
        <NormalButton type="primary" round customTextClassName={styles.bottomBar__text} customClassName={styles.bottomBar__button} customStyles={{ width: '100%' }} onClick={handleConfirm}>生成邀请海报</NormalButton>
      </View>
      <TimePickerPopup showTime={showTime} end={formData?.end_time} start={formData?.start_time} closePopup={handClose}
        leftSlot={
          <NormalButton type="primary" plain round onClick={handleReset}>重置</NormalButton>
        }
        onSelectDate={onSelectDate}
      />
      <InviteCodePopup ref={inviteCodePopupRef}></InviteCodePopup>

    </View>
  )
}

export default InviteCord
