import { PlusOutlined, MinusOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons';
import {
  ProTable,
  ModalForm,
} from '@ant-design/pro-components';
import { Button, Card, Popconfirm, Tag, Space, message, Spin, Modal, Input } from 'antd';
import { useRef, useState, useEffect } from 'react';
import React from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import FunctionImport from '@/pages/VehicleInformationManagement/FunctionImport';
import { modelsDataSearchConnect, modelsDataRemoveConnect, vehicleModelExportPost } from '@/services/SearchVehicle/searchVehicle';
import { downloadExcel } from "@/utils";



export default () => {
  const formRef = useRef<any>();
  const actionRef = useRef<any>();
  const [modalVisit, setModalVisit] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [data, setData] = useState<any>([]);
  const [spinning, setSpinning] = useState<any>(false);
  const [selectedRowsData, setSelectedRowsData] = useState<any>([]);
  const [batch, setBatch] = useState<any>(true);
  const [open, setOpen] = useState(false);
  const [res, setRes] = useState(null) as any;
  const [fileName, setFileName] = useState<any>('') as any;
  const [pageSize, setPageSize] = useState<any>(10);

  useEffect(() => {
    return () => {
    };
  }, []);

  const columns = [
    { align: 'center', search: false,title: "序号", width: 68, render: (text, record, index) => `${index + 1}`, },
    {
      dataIndex: 'name',
      align: 'center',
      title: '车型',
      // search: false,
      render: (_: any, record: any) => {
        return <>  <Space size={[0, 8]} wrap>
          {record?.name}
        </Space></>
      },
    },
    {
      dataIndex: 'brand',
      align: 'center',
      title: '品牌',
      search: false,
      render: (_: any, record: any) => {
        return <>  <Space size={[0, 8]} wrap>
          {record?.serial?.brand?.name}/
          {record?.level?.name}/
          {record?.level?.code}
        </Space ></>
      },
    },
    {
      dataIndex: 'year',
      align: 'center',
      title: '年份',
      search: false,
      render: (_: any, record: any) => {
        return <>  <Space size={[0, 8]} wrap>
          {record?.year}
        </Space></>
      },
    },
    {
      title: '操作',
      align: 'center',
      dataIndex: 'x',
      valueType: 'option',
      render: (_: any, record: any) => {
        return <>
          <Popconfirm
            title="确认删除？"
            onConfirm={() => { confirm(record) }}
            onCancel={cancel}
          >
            <Button
              key="remove"
              type="primary"
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </>
      },
    },
  ];

  const confirm = (e: any) => {
    console.log(e);

    setSpinning(true)
    let data = [e.id] as any
    modelsDataRemoveConnect(data).then((res) => {
      console.log(res);
      message.success('数据删除成功');
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })
  };

  const confirmAll = (e: any) => {
    let data = [] as any

    for (let index = 0; index < selectedRowsData.length; index++) {
      const element = selectedRowsData[index];
      data.push(element.id)
    }

    console.log(e);
    setSpinning(true)
    modelsDataRemoveConnect(data).then((res) => {
      console.log(res);
      message.success('数据批量删除成功');
      setSelectedRowsData([])
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      setSpinning(false)
    })
  };


  const exportAll = (e: any) => {
    let data = [] as any
    for (let index = 0; index < selectedRowsData.length; index++) {
      const element = selectedRowsData[index];
      data?.push(element)
    }

    console.log(data);

    setSpinning(true)
    vehicleModelExportPost({ data: data }).then((res) => {
      console.log(res);

      setOpen(true)
      setRes(res)

      setSelectedRowsData([])
      setSpinning(false)
      // 刷新
      actionRef.current.reload();
    }).catch((error) => {
      console.log(error);
      message.error('请求出错');
      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 = () => {
    setSpinning(false)
    setOpen(false)
  }

  const cancel = (e: React.MouseEvent<HTMLElement>) => {
    console.log(e);
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any, selectedRows: any) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);

      if (selectedRows && selectedRows.length > 0) {
        setBatch(false)
      } else {
        setBatch(true)
      }
      setSelectedRowsData(selectedRows)
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };


  const toBack = (type: any) => {
    setTimeout(() => {
      setModalVisit(false);
      if (type) {
        actionRef.current.reload();
      }
    }, 300);
  }

  return (
    <PageContainer>
      <Spin tip="Loading..." size="large" spinning={spinning}>
        <ProTable
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          columns={columns}
          actionRef={actionRef}
          cardBordered
          request={modelsDataSearchConnect as any}
          columnsState={{
            persistenceKey: 'pro-table-singe-demos',
            persistenceType: 'sessionStorage',
            onChange(value: any) {
              console.log('value: ', value);
            },
          }}
          scroll={{ y: 480 }}
          rowKey="id"
          // search={false}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            showSizeChanger: true,
            pageSize: pageSize,
            onChange: (page: any, pageSize: any) => setPageSize(pageSize),
          }}
          dateFormatter="string"
          toolBarRender={() => [
            <Button
              key="button"
              ghost
              icon={<ImportOutlined />}
              type="primary"
              onClick={() => {
                setModalVisit(true);
                setIsEdit(false);
              }}
            >
              数据录入
            </Button>,
            <Popconfirm
              title="确认导出？"
              disabled={batch}
              onConfirm={exportAll}
              onCancel={cancel}
            >
              <Button
                key="button"
                ghost
                icon={<ExportOutlined />}
                type="primary"
                disabled={batch}
                danger
              >
                批量导出
              </Button>
            </Popconfirm>
            ,
            <Popconfirm
              title="确认删除？"
              onConfirm={confirmAll}
              onCancel={cancel}
              disabled={batch}

            >
              <Button
                key="button"
                icon={<MinusOutlined />}
                type="primary"
                disabled={batch}
                danger
              >
                批量删除
              </Button>
            </Popconfirm>
            ,
          ]}
        //search={false}
        />

        {/* 数据录入 */}
        <ModalForm
          formRef={formRef}
          title="数据录入"
          visible={modalVisit}
          onVisibleChange={setModalVisit}
          width={1200}
          submitter={false}
        >
          <Card>
            <FunctionImport type="data" toBack={(type: any) => { toBack(type) }}></FunctionImport>
          </Card>
        </ModalForm>

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

};