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

import { Button, Form, Input, message, Row, 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 { ITryType } from './NoPermission'
import styles from '../css/MaterialInfo.module.scss'

const { Item } = Form
interface IApplyPermissionProps {
  visible: boolean
  detailID?: number
  tryType?: ITryType
  onCloseModel: () => void
}

/**
 * 申请权限
 */
const ApplyPermission: React.FC<IApplyPermissionProps> = props => {
  const { visible, detailID, tryType, onCloseModel } = 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 } = useRequest(MaterialService.postApplyTry, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('已提交给您的对口销售，请耐心等待。') : message.info(res.data.Msg)
      handleToClose()
      setImageUrl(undefined)
    }
  })
  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 = (value: any) => {
    if (!imageUrl) {
      message.error('请上传名片')
      return
    }
    // 上传名片时，ApplyMethod为2，否则为1
    run({
      ApplyMethod: 2,
      BusinessCardUrl: imageUrl,
      CompanyName: value.CompanyName,
      DetailId: detailID,
      RealName: value.RealName,
      TryType: tryType
    })
  }
  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}
    >
      <Form form={form} onFinish={handleFinish} 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>

        <Row justify="center">
          <Item className={styles['margin-auto']}>
            <Button onClick={handleToClose} className="m-r-xs">
              取消
            </Button>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Item>
        </Row>
      </Form>
    </Modal>
  )
}

export default ApplyPermission
