import { Form, Input, Button, Select, DatePicker, TreeSelect, Cascader } from 'antd';
import moment from 'dayjs';
import { SearchOutlined, ReloadOutlined, ExportOutlined } from '@ant-design/icons';
import React, { useImperativeHandle } from 'react';
import './index.scss';

const { RangePicker } = DatePicker;

// 搜索列表的类型
export interface searchColumns {
  type: 'input' | 'select' | 'rangePicker' | 'DatePicker' | 'Select' | 'TreeSelect' | 'Cascader';
  label?: string;
  name: string;
  placeholder: string;
  maxlength?: number;
  width?: number;
  options?: {
    id?: string | number | boolean | null;
    name?: string;
    value?: string | number | boolean | null;
    label?: string;
  }[];
  onSelect?: (value: any) => void;
  disable?: boolean;
  onChange?: any;
  showTime?: { format: 'HH:mm:ss' };
}

// 组件的类型
interface propsType {
  search?: searchColumns[];
  searchData?: any;
  preFixBtn?: React.ReactNode;
  sufFixBtn?: React.ReactNode;
  child?: React.ReactNode;
  children?: React.ReactNode;
  isExport?: boolean;
  exportEvent?: any;
  baseRef?: any;
  otherChild?: React.ReactNode;
}

const Index: React.FC<propsType> = (props) => {
  // 组件的默认值
  Index.defaultProps = {
    search: [],
    searchData: null,
    preFixBtn: null,
    sufFixBtn: null,
    child: null,
    children: null,
    isExport: false,
    exportEvent: null,
    baseRef: null,
    otherChild: null,
  };
  // 表单ref
  const [form] = Form.useForm();
  // 重置表格
  const handleRest = () => {
    form.resetFields();
    handleSubmit({});
  };
  // 提交数据
  const handleSubmit = (data: any) => {
    // console.log("提交数据 --->", data);
    if (data.startTime) {
      data.startTime = moment(data.startTime).format('YYYY-MM-DD');
    }
    if (data.endTime) {
      data.endTime = moment(data.endTime).format('YYYY-MM-DD');
    }
    Object.keys(data).forEach((k) => {
      const isRangPicker: boolean | undefined =
        props.search && props.search.some((v) => v.name === k && v.type === 'rangePicker');
      if (Array.isArray(data[k]) && isRangPicker) {
        data[k] = [
          `${moment(data[k][0]).format('YYYY-MM-DD')} 00:00:00`,
          `${moment(data[k][1]).format('YYYY-MM-DD')} 23:59:59`,
        ];
        data.startTime = data[k][0];
        data.endTime = data[k][1];
      }
    });
    // 过滤为空项
    const obj = Object.fromEntries(
      // 过滤为空项
      Object.entries(data).filter((i) => i[1] !== '' && i[1] !== undefined && i[1] !== null),
    );
    props.searchData(obj);
  };
  useImperativeHandle(props.baseRef, () => ({
    getForm: () => form,
  }));
  // 导出事件点击
  const exportClick = () => {
    props.exportEvent();
  };
  return (
    <div className='header'>
      {props?.preFixBtn && <div className='search-children'>{props?.preFixBtn}</div>}
      <Form
        layout='inline'
        form={form}
        initialValues={{ layout: 'inline' }}
        onFinish={handleSubmit}
      >
        {props?.child && <div className='search-children'>{props?.child}</div>}
        {props?.children && <div className='search-children'>{props?.children}</div>}
        {props?.search?.map((item: any) => {
          return (
            <Form.Item
              name={item.name}
              label={item.label}
              key={item.name}
              style={{ marginBottom: '10px' }}
            >
              {item.type === 'input' ? (
                <Input
                  placeholder={item.placeholder}
                  allowClear
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                  maxLength={50}
                />
              ) : item.type === 'select' ? (
                <Select
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                  placeholder={item.placeholder}
                  allowClear
                  onSelect={item.onSelect}
                >
                  {item.options.map((option: any) => {
                    return (
                      <Select.Option value={option.id} key={option.id}>
                        {option.name}
                      </Select.Option>
                    );
                  })}
                </Select>
              ) : item.type === 'Select' ? (
                <Select
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                  placeholder={item.placeholder}
                  allowClear
                  options={item.options}
                />
              ) : item.type === 'rangePicker' ? (
                <RangePicker
                  // showTime={{
                  //   // hideDisabledOptions: true,
                  //   defaultValue: [
                  //     moment("00:00:00", "HH:mm:ss"),
                  //     moment("23:59:59", "HH:mm:ss"),
                  //   ],
                  // }}
                  format='YYYY-MM-DD'
                  style={{ width: item.width ? `${item.width}px` : '200px' }}
                />
              ) : item.type === 'DatePicker' ? (
                <DatePicker
                  showTime={item.showTime}
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                />
              ) : item.type === 'TreeSelect' ? (
                <TreeSelect
                  allowClear
                  treeDefaultExpandAll
                  placeholder={item.placeholder}
                  treeData={item.options}
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'childNodes',
                  }}
                  popupClassName='head-search-treeSelect'
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                />
              ) : item.type === 'Cascader' ? (
                <Cascader
                  allowClear
                  changeOnSelect
                  placeholder={item.placeholder}
                  options={item.options}
                  style={{ width: item.width ? `${item.width}px` : '180px' }}
                />
              ) : (
                ''
              )}
            </Form.Item>
          );
        })}
        {props?.search && props?.search?.length > 0 && (
          <>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Button type='primary' htmlType='submit' icon={<SearchOutlined />}>
                搜索
              </Button>
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Button type='primary' onClick={handleRest} icon={<ReloadOutlined />}>
                重置
              </Button>
            </Form.Item>
            {!!props.otherChild && (
              <Form.Item style={{ marginBottom: '10px' }}>{props.otherChild}</Form.Item>
            )}
          </>
        )}
        {props.isExport ? (
          <Form.Item style={{ marginBottom: '10px' }}>
            <Button type='primary' onClick={exportClick} icon={<ExportOutlined />}>
              导出
            </Button>
          </Form.Item>
        ) : (
          ''
        )}
      </Form>
      {!!props?.sufFixBtn && <div className='search-sufFixBtn'>{props?.sufFixBtn}</div>}
    </div>
  );
};

export default Index;
