import { Input, Button, Spin, message, Popconfirm, Modal } from 'antd'
import React, { useState, useEffect, useRef } from 'react'
import styles from '@/pages/Customer/Company/components/ConnectCompany/index.less'
import { SearchOutlined } from '@ant-design/icons'
import { useDebounceFn } from 'ahooks'
import { apiAddClient, apiChangeClient, queryClient } from '@/services/customer'
import consts from '@/basic/consts'
import { formatValues } from '@/components/LazyCascader'
import AddClient from '../AddClient'

const ConnectClient = ({
  onCancel,
  dataId,
  onSelect,
  preUrl = 'client',
  showFooter = true,
  otherParams = {},
  ...resetModalProps
}) => {
  const scrollRef = useRef()
  const [state, setState] = useState({
    laoding: true,
    client: [],
    searchVal: '',
    noMore: false,
    current: 1,
    pageSize: 10,
    total: 0
  })
  const initData = async params => {
    const { data: { client, total } = { client: [], total: 0 }, code = -1 } = await queryClient({
      ...params,
      waiver: true
    })
    if (code === consts.RET_CODE.SUCCESS) {
      if (params?.current === 1) {
        scrollRef.current?.scrollTo({ top: 0 })
        // 请求的是第一页或者搜索框
        setState({ ...state, client, total, laoding: false, searchVal: params?.search })
      } else {
        setState({
          ...state,
          client: state.client.concat(client),
          total,
          searchVal: params?.search,
          laoding: false,
          current: params?.current || 1
        })
      }
    }
  }

  useEffect(() => {
    initData({ current: 1, pageSize: 10 })
  }, [])
  const onChange = e => {
    const { value = '' } = e.target || e.currentTarget
    initData({ search: value, current: 1, pageSize: state.pageSize })
  }

  const { run: handleInputChange } = useDebounceFn(onChange)

  const addConfirm = async values => {
    const payload = formatValues(values)
    const { code = -1, msg = '新增成功' } = await apiAddClient(payload)
    if (code === consts.RET_CODE.SUCCESS) {
      if (Object.hasOwnProperty.call(values, `${preUrl}Id`)) {
        message.success('新增成功并且绑定成功')
        onSelect(values.name)
        onCancel()
      } else {
        message.success(msg)
        initData()
      }
    }
  }

  // 商机/软件锁关联客户
  const connectClient = async clientId => {
    const { code = -1 } = await apiChangeClient(preUrl, { id: dataId, clientId, ...otherParams })
    if (code === consts.RET_CODE.SUCCESS) {
      // message.success('关联成功')
      onSelect()
      onCancel()
    }
  }

  const handleListScroll = () => {
    // 未滚动到底部
    if (
      scrollRef.current.scrollHeight - scrollRef.current.clientHeight <=
      scrollRef.current.scrollTop
    ) {
      // 已到底部
      if (state.current * state.pageSize > state.total) {
        setState({ ...state, noMore: true })
        return
      }
      state.current * state.pageSize < state.total &&
        initData({ current: state.current + 1, pageSize: state.pageSize, search: state.searchVal })
    }
  }

  return (
    <Modal
      {...resetModalProps}
      onCancel={onCancel}
      width="50vw"
      title={
        <Input
          prefix={<SearchOutlined />}
          className={styles.inputSearch}
          placeholder="输入客户名称搜索"
          onChange={handleInputChange}
        />
      }
    >
      <div
        className={styles.modalContent}
        ref={scrollRef}
        onScroll={handleListScroll}
        style={{ paddingBottom: 0 }}
      >
        <Spin spinning={state.laoding}>
          {state.client.map(item => (
            <div key={item.id} className={styles.card}>
              <span className="w-1/6">{item.clientName}</span>
              <span className="w-1/6">{item.position}</span>
              <span className="w-1/6">{item.telephone}</span>
              <span className="w-1/2 flex justify-between">
                <span>{item.companyName}</span>
                <Popconfirm
                  title="确认选择ta"
                  onConfirm={() => connectClient(item.id)}
                  okText="确认"
                  cancelText="取消"
                >
                  <Button type="primary" size="small">
                    选择ta
                  </Button>
                </Popconfirm>
              </span>
            </div>
          ))}
        </Spin>
        {state.noMore && <div className="text-center text-gray-400 my-4">已到底部</div>}
      </div>
      {showFooter ? (
        <div className={styles.modalFooter}>
          <AddClient
            onConfirm={addConfirm}
            dataId={dataId}
            dataType={preUrl}
            buttonProps={{ ghost: true }}
            btnTitle={'添加并关联到新客户'}
          />
        </div>
      ) : null}
    </Modal>
  )
}

export default ConnectClient
