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

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

import { PersonalService } from 'Personal/Personal.service'
import { MaterialService } from 'Material/Material.service'
import styles from '../css/ApplyAdivise.module.scss'

interface IApplyAdiviseProps {
  visible: boolean
  onCloseModel: () => void
}

/**
 * 优化建议
 */
const ApplyAdivise: React.FC<IApplyAdiviseProps> = props => {
  const { visible, onCloseModel } = props
  const [loading, setLoading] = useState(false)
  const [adviseText, setAdviseText] = useState<string>()
  const [fileList, setFileList] = useState<UploadFile[]>([])
  const [allImg, setAllImg, getAllImg] = useGetState<string[]>([])

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

  const { run } = useRequest(PersonalService.postAdiviceAdd, {
    manual: true,
    onSuccess: res => {
      res.data.Ret === 200 ? message.success('已发送') : message.info(res.data.Msg)
      handleToClose()
      setAdviseText(undefined)
      setFileList([])
      setAllImg([])
    }
  })

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleFinish = () => {
    if (!adviseText?.replace(/\s/g, '')) return message.error('优化建议不能为空')
    run(adviseText, allImg)
  }

  const handleToClose = () => {
    setAdviseText(undefined)
    setFileList([])
    setAllImg([])
    onCloseModel()
  }
  const handleChangeAdivise = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    setAdviseText(e.target.value)
  }
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const handleUpload = async (options: any) => {
    setLoading(true)
    await MaterialService.postUploadImage(options.file).then(res => {
      if (res.data?.Data?.ResourceUrl) {
        handleInitFileList([...getAllImg(), res.data?.Data?.ResourceUrl])
        setAllImg([...getAllImg(), res.data?.Data?.ResourceUrl])
      }
      setLoading(false)
    })
  }
  const handleInitFileList = (arr: string[]) => {
    const fileList = arr.map(url => {
      return {
        uid: url,
        url,
        name: url,
        status: 'done'
      } as UploadFile
    })
    setFileList(fileList)
  }

  const handleRemoveImg = (file: UploadFile) => {
    const urlList = allImg.filter(url => url !== file.url)
    setAllImg(urlList)
    handleInitFileList(urlList)
  }

  const beforeUpload = (file: RcFile, FileList: RcFile[]) => {
    if (FileList.length > 3) {
      message.error('最多上传3张图片')
    }
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg'
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    // const isLt2M = file.size / 1024 / 1024 < 2
    // if (!isLt2M) {
    //   message.error('Image must smaller than 2MB!')
    // }
    return isJpgOrPng && !(FileList.length > 3)
  }

  return (
    <Modal
      open={visible}
      title="优化建议"
      onOk={handleFinish}
      onCancel={handleToClose}
      destroyOnClose={true}
      maskClosable={false}
      // footer={null}
      centered
    >
      <div className="padding-l-md padding-r-md">
        <label className={`com-fw-bold ${styles['mb12']}`}>
          <span className={styles['red-xin']}>*</span>
          优化建议
        </label>
        <Input.TextArea
          showCount
          maxLength={100}
          placeholder="您有任何使用建议，可以提供给我们，以便为您提供更好的产品服务。"
          rows={4}
          value={adviseText}
          onChange={handleChangeAdivise}
          className={styles['mb12']}
        />
        <label className={`com-fw-bold ${styles['mb12']}`}>上传图片</label>

        <Upload
          customRequest={handleUpload}
          multiple
          maxCount={3}
          listType="picture-card"
          fileList={fileList}
          beforeUpload={beforeUpload}
          onRemove={handleRemoveImg}
        >
          {fileList.length >= 3 ? null : uploadButton}
          {/* {imageUrlList.map(item => (
            <img src={item.url} alt="file" style={{ width: '100%' }} key={item.id} />
          ))}
          {imageUrlList.length >= 3 ? null : uploadButton} */}
        </Upload>
        <span className={styles['sm-gray']}>注：支持上传jpg、jpeg、png格式，最多上传3张图片</span>
      </div>
    </Modal>
  )
}

export default ApplyAdivise
