
import { useEffect, useRef, useState } from 'react'
import Taro from '@tarojs/taro'
import { getFollowRecord, addFollowRecord } from '@/services/person'

export default function useFollow(customer) {
  const [submitting, setSubmitting] = useState(false)
  const [followList, setFollowList] = useState([])
  const queryRef = useRef()
  queryRef.current = () => {
    getFollowRecord({
      pageNumber: 1,
      pageSize: 100,
      customerId: customer.customerId,
      recordType: '跟进',
    }).then((res) => {
      const { records } = res
      setFollowList(records || [])
    })
  }

  const addFollow = (data) => {
    const payload = {
      recordType: '添加跟进',
      recordContent: data,
      customerSex: customer.sex,
      customerId: customer.customerId,
    }

    setSubmitting(true)

    addFollowRecord(payload).then((res) => {
      Taro.showToast({
        title: '添加成功',
        icon: 'none',
      })

      setFollowList([res].concat(followList))
      setSubmitting(false)
    }).catch(() => setSubmitting(false))
  }

  useEffect(() => {
    if (customer.customerId) {
      queryRef.current()
    }
  }, [customer?.customerId])

  return [followList, submitting, addFollow]
}
