import { ProForm, ProFormRadio, ProFormText } from '@ant-design/pro-components';
import { Col, Button, Row, Space, Modal, Input, message, Spin } from 'antd';
import { FileExcelFilled } from '@ant-design/icons';
import { useState, useEffect, useRef } from 'react';
import SelectVehicle from '@/components/SelectVehicle';
import SelectFunction from '@/components/SelectFunction';
import SelectCondition from '@/components/SelectCondition';
import SelectLevel from '@/components/SelectLevel';
import type { RcFile, UploadFile } from 'antd/es/upload/interface';
import { exportUrlConnect, imgUploadImage, RateExportPost, tagRateExportPost } from '@/services/SearchVehicle/searchVehicle';
import { downloadExcel } from "@/utils";


type LayoutType = Parameters<typeof ProForm>[0]['layout'];
const LAYOUT_TYPE_HORIZONTAL = 'horizontal';


const SearchVehicle: React.FC = (props: any) => {
  const formRef = useRef() as any;
  const [formLayoutType, setFormLayoutType] = useState<LayoutType>(
    'horizontal',
  );

  const [data, setData] = useState(props.data);
  const [open, setOpen] = useState(false);
  const [res, setRes] = useState(null) as any;
  const [fileName, setFileName] = useState<any>('') as any;
  const [searchObj, setSearchObj] = useState<any>(null) as any;
  const [searchTags, setSearchTags] = useState<any>(null) as any;


  useEffect(() => {

    if (props.data) {
      setData(props.data)
    }
    return () => {

    }
  }, [props.data])


  const onLabelChange = (type: string, value: any) => {

    switch (type) {
      case 'level':
        formRef?.current?.setFieldsValue({
          level: value,
          vehicle: ''
        });
        setSearchObj({
          level: value
        })
        break;
      case 'tags':
        let vehicle = formRef?.current?.getFieldValue('vehicle')
        if (vehicle) {
          // 筛选功能选择下拉
          setSearchTags({
            tags: value,
            vid: vehicle
          })
        }
        break;

      default:
        break;
    }
  };
  const onChange = (type: string, value: string[]) => {

    switch (type) {
      case 'vehiclebrand':
        formRef?.current?.setFieldsValue({
          vehicle: '',
        });
        break;
      case 'vehicle':
        formRef?.current?.setFieldsValue({
          vehiclebrand: '',
        });
        break;
      default:
        break;
    }
    let data = formRef.current?.getFieldsFormatValue?.()
    console.log(data);

    props?.config?.submitter ? '' : props.submit(type, value)
  };

  // base64转换为file文件流
  const base64toFile = (dataurl: any, filename = 'file') => {
    let arr = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let suffix = mime.split('/')[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], `${filename}.${suffix}`, {
      type: mime,
    })
  }


  const exportFunction = () => {

    if (!data || data.length <= 0) {
      Modal.warning({
        content: '请先查询',
        centered: true
      });
      return
    }
    props.setSpinning(true)

    if (props?.config?.importEchar) {
      // echar导出
      let importEchar = props?.config?.importEchar
      let imageUrl = props?.config?.imageUrl

      let file = base64toFile(imageUrl, 'file')

      // 先上传截图
      const formData = new FormData();
      formData.append('file', file as RcFile);
      // You can use any AJAX library you like
      imgUploadImage(formData).then((res: any) => {
        console.log(res);
        var urldata = res as any

        switch (importEchar) {
          // 搭载率分析
          case 'carry':

            RateExportPost({ data: urldata }).then(async (res) => {
              console.log(res);
              setOpen(true)
              setRes(res)
            }).catch((error) => {
              console.log(error);
              message.error('导出错误');
              props.setSpinning(false)
            })

            break;

          // 标签分析
          case 'label':

            tagRateExportPost({ data: urldata }).then(async (res) => {
              console.log(res);
              setOpen(true)
              setRes(res)
            }).catch((error) => {
              console.log(error);
              message.error('导出错误');
              props.setSpinning(false)
            })

            break;

          default:
            break;
        }
      });

    } else {
      // 通用excel导出
      exportUrlConnect({ data: data }).then(async (res) => {
        console.log(res);
        setOpen(true)
        setRes(res)
      }).catch((error) => {
        console.log(error);
        message.error('导出错误');
        props.setSpinning(false)
      })
    }
  };

  const onOk = () => {
    close()
    if (!res) {
      Modal.warning({
        content: '下载失败',
        centered: true
      });
      return
    }
    const blob = new Blob([res], { type: 'application/vnd.ms-excel;charset=utf-8' });
    downloadExcel(blob, fileName);
  }

  const close = () => {
    props.setSpinning(false)
    setOpen(false)
  }


  return (
    <div style={{ marginBottom: 20, background: '#fff', padding: 20 }}>
      <Row justify='start'  >
        <Col span={20}>
          <ProForm<{
            name: string;
            company?: string;
            useMode?: string;
          }>
            layout={formLayoutType}
            formRef={formRef}
            submitter={props?.config?.submitter ? {
              render: (props, doms) => {
                return formLayoutType === LAYOUT_TYPE_HORIZONTAL ? (
                  <Row>
                    <Col offset={10}>
                      <Space>{doms}</Space>
                    </Col>
                  </Row>
                ) : (
                  doms
                );
              },
              searchConfig: {
                resetText: '重置',
                submitText: '查询',
              },
            } : false}
            onFinish={async (values) => {
              await props.submit('all', values)
              // message.success('提交成功');
            }}
            onReset={async (values) => {
              setSearchObj({})
            }}
          >
            <ProForm.Group>
              {
                props?.config?.level ? <SelectLevel
                  name="level"
                  width="lg"
                  label="车型级别"
                  change={(e: any, label: any) => { onChange("level", e); onLabelChange("level", label) }}
                  onClear={() => {
                    setSearchObj({})
                  }}
                  multiple={props?.config?.multiple}
                  vehicleUrl={props?.config?.vehicleUrl}
                ></SelectLevel> : false
              }
            </ProForm.Group>
            <ProForm.Group>
              {
                props?.config?.vehicle ? <SelectVehicle
                  name="vehicle"
                  width="lg"
                  label="车型选择"
                  change={(e: any) => { onChange("vehicle", e) }}
                  multiple={props?.config?.multiple}
                  vehicleUrl={props?.config?.vehicleUrl}
                  searchObj={searchObj}
                  onClear={() => {
                    setSearchTags({})
                  }}
                ></SelectVehicle> : false
              }
            </ProForm.Group>
            <ProForm.Group>
              {
                props?.config?.label ? <SelectVehicle
                  name="label"
                  width="lg"
                  label="标签选择"
                  change={(e: any) => { onChange("label", e) }}
                  // multiple={props?.config?.multiple}
                  multiple={false}
                  vehicleUrl={props?.config?.labelUrl}
                  onClear={() => {
                    setSearchTags({})
                  }}
                ></SelectVehicle> : false
              }
            </ProForm.Group>
            <ProForm.Group>
              {
                props?.config?.vehicleLarge ? <SelectVehicle
                  name="vehicleLarge"
                  width="lg"
                  label="车型分类"
                  change={(e: any) => { onChange("vehicleLarge", e) }}
                  multiple={props?.config?.multiple}
                  vehicleUrl={props?.config?.vehicleUrl}
                ></SelectVehicle> : false
              }
            </ProForm.Group>
            <ProForm.Group>
              {
                props?.config?.vehiclebrand ? <SelectVehicle
                  name="vehiclebrand"
                  width="lg"
                  label="品牌选择"
                  change={(e: any) => { onChange("vehiclebrand", e) }}
                  multiple={props?.config?.multiple}
                  vehicleUrl={props?.config?.brandUrl}
                ></SelectVehicle> : false
              }
            </ProForm.Group>
            {/* <ProForm.Group>
              {
                props?.config?.tags ? <SelectVehicle
                  name="tags"
                  width="lg"
                  label="功能标签"
                  change={(e: any) => { onChange("tags", e); onLabelChange("tags", e) }}
                  multiple={props?.config?.multiple}
                  vehicleUrl={props?.config?.tagsUrl}
                ></SelectVehicle> : false
              }
            </ProForm.Group> */}
            <ProForm.Group>
              {
                props?.config?.function ? <SelectFunction
                  name="function"
                  width="lg"
                  label="功能选择"
                  change={(e: any) => { onChange("function", e) }}
                  multiple={props?.config?.multiple}
                  searchObj={searchTags}
                ></SelectFunction> : false
              }
            </ProForm.Group>
            <ProForm.Group>
              {
                props?.config?.time ? <SelectVehicle
                  name="time"
                  width="lg"
                  label="分析期间"
                  change={(e: any) => { onChange("time", e) }}
                  multiple={props?.config?.multiple}
                  // multiple={false}
                  vehicleUrl={props?.config?.timeUrl}
                ></SelectVehicle> : false
              }
            </ProForm.Group>

            {
              props?.config?.condition ? <SelectCondition
              ></SelectCondition> : false
            }
          </ProForm>
        </Col>
        <Col span={4}>
          {
            <Button disabled={!data || data.length <= 0 ? true : false} type="primary" ghost icon={<FileExcelFilled />} onClick={() => { exportFunction() }}>
              导出功能数据
            </Button>
          }
        </Col>
      </Row>

      <Modal
        open={open}
        title="输入Excel名称"
        onOk={() => { onOk() }}
        onCancel={() => { close() }}
      >
        <Space>
          名称：<Input placeholder="输入Excel名称" value={fileName} onChange={(e) => {
            setFileName(e.target.value)
          }} />
        </Space>
      </Modal>
    </div>


  );
};

export default SearchVehicle;