import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request'

import { Form, Input, message, Modal, Upload } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import type { UploadChangeParam } from 'antd/es/upload'
import type { UploadFile, UploadProps } from 'antd/es/upload/interface'

import { MaterialService } from '../Material.service'
import { useLogin2p } from 'Login2p/Login2pContext'
import NButton from 'components/NButton/NButton'
import styles from '../css/NoPermission.module.scss'

const { Item } = Form
interface IUploadInfoModelProps {
  visible: boolean
  onCloseModel: () => void
  handleSuccess: () => void
}

/**
 * 上传名片弹框（用于机构申请权限）
 */
const UploadInfoModel: React.FC<IUploadInfoModelProps> = props => {
  const { visible, onCloseModel, handleSuccess } = props
  const login2p = useLogin2p()
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>()

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传名片</div>
    </div>
  )

  const { run: UploadBusinessCard } = useRequest(MaterialService.postUploadBusinessCard, {
    manual: true,
    onSuccess: res => {
      if (res.data.Success) {
        setImageUrl(undefined)
        message.success(res.data.Msg)
        handleSuccess()
      } else {
        message.info(res.data.ErrMsg || res.data.Msg)
      }
    }
  })
  const { run: uploadImg } = useRequest(MaterialService.postUploadImage, {
    manual: true,
    onSuccess: res => {
      message.info(res.data.Msg)
      setImageUrl(res.data?.Data?.ResourceUrl)
      setLoading(false)
    }
  })
  useEffect(() => {
    return () => {
      form.resetFields()
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [form])

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleFinish = async () => {
    if (!imageUrl) {
      message.error('请上传名片')
      return
    }
    try {
      const values = await form.validateFields()
      UploadBusinessCard({
        BusinessCardUrl: imageUrl,
        RealName: values.RealName,
        Mobile: values.Mobile,
        CompanyName: values.CompanyName,
        InviteShareCode: login2p.inviteCode || sessionStorage.getItem('invite_code') || ''
      })
    } catch (errorInfo) {}
  }
  const uploadProps: UploadProps = {
    name: 'file',
    multiple: false,
    listType: 'picture-card',
    showUploadList: false,
    withCredentials: true,
    customRequest: option => {
      uploadImg(option.file)
    },
    onChange: (info: UploadChangeParam<UploadFile>) => {
      if (info.file.status === 'uploading') {
        setLoading(true)
        return
      }
    }
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const normFile = (e: any) => {
    if (Array.isArray(e)) {
      return e
    }
    return e && e.fileList
  }
  const handleToClose = () => {
    // 关闭前把名片给清除了
    setImageUrl(undefined)
    onCloseModel()
  }
  return (
    <Modal
      open={visible}
      onCancel={handleToClose}
      destroyOnClose={true}
      maskClosable={false}
      title="上传名片"
      footer={null}
    >
      <div className="m-b-md">当前没有所属机构，请上传您的名片</div>
      <Form form={form} labelAlign="left">
        <Item
          label="上传名片"
          name="BusinessCardUrl"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          valuePropName="fileList"
          getValueFromEvent={normFile}
        >
          <Upload {...uploadProps}>
            {imageUrl ? <img src={imageUrl} alt="file" style={{ width: '100%' }} /> : uploadButton}
          </Upload>
        </Item>
        <Item
          label="姓名"
          name="RealName"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          rules={[{ required: true, message: '请输入姓名!' }]}
        >
          <Input placeholder="请输入姓名" />
        </Item>
        <Item
          label="公司名"
          name="CompanyName"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          rules={[{ required: true, message: '请输入公司名!' }]}
        >
          <Input placeholder="请输入公司名" />
        </Item>
        <Item
          label="手机号"
          name="Content"
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 19 }}
          rules={[{ required: true, message: '' }]}
          initialValue={login2p.userInfo?.Mobile}
        >
          <Input disabled />
        </Item>
        <Item>
          <div className={styles['paymodel-footer-wrapper']}>
            <NButton type="white" onClick={handleToClose} size="large" className="pay-btn m-r-md">
              取消
            </NButton>
            <NButton type="primary" size="large" className="pay-btn" onClick={handleFinish}>
              提交
            </NButton>
          </div>
        </Item>
      </Form>
    </Modal>
  )
}

export default UploadInfoModel
