import consts from '@/consts'
import { queryClientWithTelephone } from '@/services/customer'
import { useDebounceFn } from 'ahooks'
import { Input, Alert, Popover } from 'antd'
import { useState } from 'react'
import { validateEnum } from '@/pages/Customer/Company/components/AddCompany/CompanyFormItem'
import { useModal } from '@/components/ModalStore'

const TelephoneFormItem = ({ value, onChange, validateFn }) => {
  const dispatchModal = useModal()
  const [state, setState] = useState({
    inputVal: value,
    visible: false,
    list: null
  })
  const triggerChange = changedValue => {
    onChange?.(changedValue)
  }

  const queryList = async search => {
    if (!search) return
    const { code = -1, data } = await queryClientWithTelephone({
      current: 1,
      pageSize: 20,
      search
    })
    if (code === consts.RET_CODE.SUCCESS) {
      const { client = [] } = data
      setState({ ...state, list: client, visible: !!client?.length })
      if (client?.length) {
        validateFn(validateEnum.Warning)
      } else {
        validateFn(validateEnum.Success)
      }
    }
  }

  const { run: handleQueryList, cancel: cancelQuerying } = useDebounceFn(queryList, { wait: 600 })

  const handleOnInputChange = async e => {
    const val = e.target.value || ''
    if (!val) {
      cancelQuerying()
      setState({ ...state, inputVal: val, list: null, visible: false })
      validateFn(validateEnum.Error)
    } else {
      setState({ ...state, inputVal: val })
      if (val?.length > 10) {
        validateFn(validateEnum.Validating)
        handleQueryList(val)
      }
    }
    triggerChange(val)
  }

  const { visible, list, inputVal } = state
  return (
    <Popover
      placement="bottom"
      visible={list && list?.length && visible}
      onVisibleChange={e => setState({ ...state, visible: e })}
      title={
        <Alert
          message="已存在相同手机号码，请确认是否继续添加"
          type="warning"
          style={{ padding: '5px', margin: '10px 0' }}
        />
      }
      trigger="click"
      content={
        <ul className="list-none">
          {list?.map(item => {
            return (
              <p key={item.id}>
                <span
                  className="text-primary cursor-pointer hover:text-hex-967bbd"
                  onClick={() => {
                    dispatchModal('D_CLIENT_DETAIL', { dataId: item.id })
                    setState({ ...state, visible: false })
                  }}
                >
                  {item.clientName}
                </span>
                <span className="mx-1">/</span>
                <span>{item.districtName?.replaceAll(' / ', ',')}</span>
              </p>
            )
          })}
        </ul>
      }
    >
      <Input
        type="tel"
        autoComplete="false"
        value={inputVal}
        placeholder="请输入手机号码"
        onChange={handleOnInputChange}
        className="company-input"
      />
    </Popover>
  )
}

export default TelephoneFormItem
