import { useContext, useEffect, useState } from 'react';

import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { Col, Form, Input, Row, Upload, message, Button, Image, AutoComplete } from 'antd';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import Router from 'next/router';

import gApi from '~/api';
import Layout from '~/components/layout';
import { UserContext } from '~/lib/userProvider';

import api from './api';
import styles from './index.module.scss';

const beforeUpload = (file: RcFile) => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/png' ||
    file.type === 'image/bmp' ||
    file.type === 'image/gif';
  if (!isJpgOrPng) {
    message.error('请上传10M以内的JPG、JPEG、BMP、GIF、PNG格式图片');
  }
  // 限制上传10M
  const isLt2M = file.size / 1024 / 1024 < 10;
  if (!isLt2M) {
    message.error('请上传10M以内的JPG、JPEG、BMP、GIF、PNG格式图片');
  }
  return isJpgOrPng && isLt2M;
};

const normFile = (e: any) => {
  console.log('Upload event:', e);
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

type EnterpriseOption = {
  label: string;
  value: string;
  creditCode: string;
};

export default function Certification() {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const { userInfo, setUserInfo } = useContext(UserContext);
  const [enterpriseOptions, setEnterpriseOptions] = useState<Array<EnterpriseOption>>([]);
  const [form] = Form.useForm();
  const [token, setToken] = useState('');

  useEffect(() => {
    setToken(window.localStorage.getItem('token') || '');
  }, []);

  // 上传change事件
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    console.log('uploadChange', info);
    if (info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      setLoading(false);
      setImageUrl(info.file.response.result?.[0]);
    }
  };

  // 提交
  const onFinish = (values: any) => {
    console.log(values);
    api
      .companyAuth({
        ...values,
        licenseImg: imageUrl,
      })
      .then((res) => {
        console.log('提交结果', res);
        if (res.code === '200') {
          window.messageApi.success('提交成功,请等待审核');
          if (userInfo) {
            setUserInfo({
              ...userInfo,
              companyAuthStatus: 1,
            });
          }
          setTimeout(() => {
            if (Router.query.type === 'back') {
              Router.back();
            } else {
              Router.push('/');
            }
          }, 1000);
        }
      });
  };

  let handle: NodeJS.Timeout;
  // 搜索企业
  const onSearchEnterprise = (text: string) => {
    if (handle) {
      clearTimeout(handle);
    }
    handle = setTimeout(() => {
      api
        .fuzzyQueryCompany({
          searchKey: text,
        })
        .then((res) => {
          if (res.code === '200') {
            setEnterpriseOptions(
              res.result?.Result?.map((item) => {
                return {
                  label: item.Name,
                  value: item.Name,
                  creditCode: item.CreditCode,
                };
              }) || [],
            );
          } else {
            setEnterpriseOptions([]);
          }
        });
    }, 500);
  };

  // 选择的企业
  const onSelectEnterprise = (value: string, option: EnterpriseOption) => {
    form.setFieldValue('creditCode', option.creditCode);
  };

  return (
    <Layout>
      <div className={styles.banner}></div>
      <div
        className='page'
        style={{
          background: '#fff',
          position: 'relative',
          zIndex: 1,
          marginTop: 60,
        }}
      >
        <div
          className={styles.font1}
          style={{
            padding: '30px 0 23px 31px',
            borderBottom: '1px solid RGBA(231, 231, 231, 1)',
          }}
        >
          企业认证{' '}
          <span className={styles.font2} style={{ marginLeft: 28 }}>
            发布信息需完成以下认证
          </span>
        </div>
        <div>
          <Form form={form} style={{ padding: '70px 170px 162px 170px' }} onFinish={onFinish}>
            <Row justify='space-between'>
              <Col span={11}>
                <Form.Item
                  label='企业名称'
                  name='companyName'
                  rules={[{ required: true }]}
                  style={{ borderBottom: '1px solid RGBA(243, 243, 243, 1)' }}
                >
                  <AutoComplete
                    options={enterpriseOptions}
                    style={{ width: 200 }}
                    onSelect={onSelectEnterprise}
                    onSearch={onSearchEnterprise}
                    placeholder='请输入企业名称'
                    bordered={false}
                  />
                </Form.Item>
              </Col>
              <Col span={11}>
                <Form.Item
                  label='企业信用代码'
                  name='creditCode'
                  rules={[{ required: true }]}
                  style={{ borderBottom: '1px solid RGBA(243, 243, 243, 1)' }}
                >
                  <Input bordered={false} placeholder='请输入企业信用代码'></Input>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              name='licenseImg'
              rules={[{ required: true }]}
              valuePropName='fileList'
              getValueFromEvent={normFile}
              help={<div style={{ textAlign: 'center' }}>请上传营业执照</div>}
            >
              <Upload
                name='uploadFile'
                listType='picture-card'
                className={styles.upload}
                showUploadList={false}
                action={gApi.imgOss}
                beforeUpload={beforeUpload}
                onChange={handleChange}
                maxCount={1}
                headers={{ token }}
              >
                {imageUrl ? (
                  <Image
                    src={imageUrl}
                    alt='uploadFile'
                    style={{ width: '100%' }}
                    preview={false}
                  />
                ) : (
                  <div>
                    {loading ? <LoadingOutlined /> : <PlusOutlined />}
                    <div style={{ marginTop: 8 }}>上传营业执照</div>
                  </div>
                )}
              </Upload>
            </Form.Item>
            <div className={styles.font2} style={{ marginTop: 56 }}>
              1. 请上传最新的营业执照，证件需加盖与主体一致的单位公章。 <br />
              2.加盖公章的扫描件或复印件支持jpg.jpeg.bmp.gif.png格式图片，大小不超10M。
            </div>

            <Row justify='center'>
              <Button
                type='primary'
                htmlType='submit'
                style={{ marginTop: 20, padding: '0 129px' }}
                size='large'
              >
                提交认证
              </Button>
            </Row>
          </Form>
        </div>
      </div>
    </Layout>
  );
}
