import { Button, Form, Input, Radio, Select } from 'antd';
import { Uploader } from '~/components/uploader';
import { EnvironmentOutlined, UploadOutlined } from '@ant-design/icons';
import './index.scss';
import React, { FC, forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import deletePng from '~/assets/image/delete.png';
import SelectMapModal from '~/components/select-map';
import { PilotTrainAPI } from '~/api';
import { InterDataType, InterReqType } from '~/api/interface';
import { insertOrgType, licenceScaleList } from '~/api/interface/pilotTrainType';

//规模下拉返回类型
type scaleListType = InterDataType<licenceScaleList>;
interface selfProps {
  ref: any;
}
//上传机构请求类型
type insertOrgParametersType = Omit<InterReqType<insertOrgType>, 'trainingProgramsVOS'>;

const BaseInfo: FC<selfProps> = forwardRef((_props, ref) => {
  const [baseInfoForm] = Form.useForm<insertOrgParametersType>();
  //地图地点选择
  const [selectMapShow, setSelectMapShow] = useState<boolean>(false);
  // 位置信息
  const [position, setPosition] = useState<{
    lat: number;
    lon: number;
    address: string;
    adCode: number;
  }>();
  const [mainImgList, setMainImgList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  const [subImgList, setSubImgList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  const [videoList, setVideoList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  //规模下拉列表
  const [scaleList, setScaleList] = useState<scaleListType>([]);

  useImperativeHandle(ref, () => ({
    getForm: () => baseInfoForm,
    getDefaultDataEvent: () => ({
      setPosition,
      setMainImgList,
      setSubImgList,
      setVideoList,
    }),
    getPosition: () => position,
  }));

  //上传结果
  const uploaderChange = (
    value: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
    type: string,
  ) => {
    switch (type) {
      case 'mainImg':
        baseInfoForm.setFieldValue('mainImage', value[0].url || undefined);
        setMainImgList(value);
        break;
      case 'subImg':
        baseInfoForm.setFieldValue(
          'auxiliaryPicture',
          value.length ? value.map((v) => v.url).join(',') : undefined,
        );
        setSubImgList(value);
        break;
      case 'video':
        baseInfoForm.setFieldValue('video', value[0].url);
        setVideoList(value);
        break;
      default:
    }
  };
  //视频删除
  const deleteVideo = () => {
    setVideoList([]);
    baseInfoForm.setFieldValue('video', undefined);
  };
  //地图选点
  const showSelectMap = () => [setSelectMapShow(true)];
  const selectMapSubmit = (value: {
    lat: number;
    lon: number;
    address: string;
    adCode: number;
  }) => {
    baseInfoForm.setFieldsValue({
      region: [
        value.adCode.toString().substring(0, 2) + '0000',
        value.adCode.toString().substring(0, 4) + '00',
      ].join(','),
    });
    setPosition(value);
    setSelectMapShow(false);
  };
  const selectMapClose = () => {
    setSelectMapShow(false);
  };
  //机构规模
  const getLicenceScaleList = () => {
    PilotTrainAPI.getLicenceScaleList().then(({ result }) => {
      setScaleList(result || []);
    });
  };

  useEffect(() => {
    getLicenceScaleList();
  }, []);
  return (
    <div className='base-info'>
      <div className='base-info-header'>基本信息：</div>
      <div className='base-info-form'>
        <Form
          labelCol={{ span: 2 }}
          wrapperCol={{ span: 7 }}
          form={baseInfoForm}
          initialValues={{ testCenter: 1 }}
        >
          <Form.Item
            label='机构主图'
            name='mainImage'
            rules={[{ required: true, message: '请上传机构主图' }]}
          >
            <Uploader
              fileUpload
              listType='picture-card'
              onChange={(result) => uploaderChange(result, 'mainImg')}
              fileLength={1}
              fileSize={5}
              fileType={['image/jpg', 'image/jpeg', 'image/png']}
              defaultFileList={mainImgList}
            >
              <UploadOutlined />
            </Uploader>
          </Form.Item>
          <Form.Item label='机构副图' name='auxiliaryPicture'>
            <Uploader
              fileUpload
              listType='picture-card'
              onChange={(result) => uploaderChange(result, 'subImg')}
              fileLength={5}
              fileSize={5}
              fileType={['image/jpg', 'image/jpeg', 'image/png']}
              defaultFileList={subImgList}
            >
              <UploadOutlined />
            </Uploader>
          </Form.Item>
          <Form.Item label='机构视频' name='video'>
            {videoList.length ? (
              <div className='info-video-wrap'>
                {/* eslint-disable-next-line jsx-a11y/media-has-caption */}
                <video
                  src={videoList[0].url}
                  style={{ width: '200px', height: '200px' }}
                  controls
                />
                {<img src={deletePng} alt='删除' onClick={deleteVideo} />}
              </div>
            ) : (
              <Uploader
                fileUpload
                listType='text'
                onChange={(result) => uploaderChange(result, 'video')}
                fileSize={1024}
                fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
                fileLength={1}
                defaultFileList={videoList}
              >
                <Button icon={<UploadOutlined />} type='primary'>
                  上传视频
                </Button>
              </Uploader>
            )}
          </Form.Item>
          <Form.Item
            label='机构名称'
            name='name'
            rules={[{ required: true, message: '请输入机构名称' }]}
          >
            <Input placeholder='请输入机构名称' maxLength={25} />
          </Form.Item>
          <Form.Item
            label='机构地区'
            name='region'
            rules={[{ required: true, message: '请选择机构地区' }]}
          >
            <div className='region-info'>
              {position?.address ? <div>{position?.address}</div> : ''}
              <Button
                icon={<EnvironmentOutlined />}
                type='primary'
                onClick={showSelectMap}
              ></Button>
            </div>
          </Form.Item>
          <Form.Item label='考点机构' name='testCenter'>
            <Radio.Group>
              <Radio value={1}>是</Radio>
              <Radio value={0}>否</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label='机构规模' name='scaleId'>
            <Select placeholder='请选择机构规模'>
              {scaleList.map((scale) => (
                <Select.Option value={scale.id} key={scale.id}>
                  {scale.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label='机构描述' name='description'>
            <Input.TextArea placeholder='请选择机构描述' maxLength={225} rows={4} showCount />
          </Form.Item>
        </Form>
      </div>
      <SelectMapModal submit={selectMapSubmit} closed={selectMapClose} open={selectMapShow} />
    </div>
  );
});
export default BaseInfo;
