import React from 'react';
import moment from 'moment';
import { Form, Input, DatePicker, InputNumber, Select, Row, Col } from 'antd';
import { MapPosition, ErrorBoundary } from '@sensoro/sensoro-design';
import cloneDeep from 'lodash/cloneDeep';
import { UploadImageProps } from '@sensoro/sensoro-design/es/upload-image/upload-image';
import { UploadImage } from '@sensoro/library/lib/components/upload';
import { FormilyData, FormilyType } from './interface';
import { FormItemProps } from 'antd/es/form/FormItem';

interface FormilyRenderProps {
  list: FormilyData<boolean>[];
  span?: 12 | 24;
  formItemMap?: Partial<Record<FormilyType, FormItemProps>>;
  uploadImage?: UploadImageProps;
  getPopupContainer?: (triggerNode: HTMLElement) => HTMLElement;
}

const { RangePicker } = DatePicker;
const { TextArea } = Input;
const { Option } = Select;

function range(start: number, end: number) {
  const result = [];
  for (let i = start; i < end; i++) {
    result.push(i);
  }
  return result;
}

const FormilyRender: React.FC<FormilyRenderProps> = ({
  span,
  list = [],
  formItemMap = {},
  uploadImage,
  getPopupContainer,
}) => {
  function disabledDate(current: moment.Moment) {
    return current && current > moment().endOf('day');
  }

  function disabledTime(current: moment.Moment) {
    const currentDate = moment();
    const hour = currentDate.hour();
    const minute = currentDate.minute();
    const second = currentDate.second();

    // 如果上今天之前的则不限制
    if (current && current.isBefore(currentDate, 'days')) {
      return {
        disabledHours: () => [],
        disabledMinutes: () => [],
        disabledSeconds: () => [],
      };
    }

    return {
      disabledHours: () => {
        return range(hour + 1, 24);
      },
      disabledMinutes: (selectedHour: number) => {
        if (selectedHour === hour) {
          return range(minute + 1, 60);
        } else if (selectedHour > hour) {
          return range(1, 60);
        } else {
          return [];
        }
      },
      disabledSeconds: (selectedHour: number, selectedMinute: number) => {
        if (selectedHour === hour) {
          if (selectedMinute === minute) {
            return range(second + 1, 60);
          }

          if (selectedMinute > minute) {
            return range(1, 60);
          }
        }

        if (selectedHour > hour) {
          return range(1, 60);
        }

        return [];
      },
    };
  }

  const getMaterialTypeItem = (data: FormilyData<boolean>) => {
    const { options = [], type } = data;

    if (type === 'inputs') {
      return <Input placeholder="请输入" />;
    }

    if (type === 'numberInputs') {
      return <InputNumber placeholder="请输入" min={0} />;
    }

    if (type === 'locations') {
      return <MapPosition style={{ height: 300 }} />;
    }

    if (type === 'videos') {
      return (
        <UploadImage desc="限3张，JPG/PNG格式，大小不超过1M" {...uploadImage} />
      );
    }

    if (type === 'multiInputs') {
      return <TextArea placeholder="请输入" />;
    }

    if (type === 'selects') {
      return (
        <Select
          placeholder="请选择"
          getPopupContainer={
            getPopupContainer ? getPopupContainer : () => document.body
          }
        >
          {options.map(item => (
            <Option key={item.id} value={item.id}>
              {item.name}
            </Option>
          ))}
        </Select>
      );
    }

    if (type === 'multiSelects') {
      return (
        <Select
          mode="multiple"
          placeholder="请选择"
          getPopupContainer={
            getPopupContainer ? getPopupContainer : () => document.body
          }
        >
          {options.map(item => (
            <Option key={item.id} value={item.id}>
              {item.name}
            </Option>
          ))}
        </Select>
      );
    }

    if (type === 'dates') {
      return data.internal ? (
        <DatePicker
          showTime
          disabledDate={disabledDate}
          disabledTime={disabledTime}
          getPopupContainer={
            getPopupContainer ? getPopupContainer : () => document.body
          }
        />
      ) : (
        <DatePicker
          getPopupContainer={
            getPopupContainer ? getPopupContainer : () => document.body
          }
          showTime
        />
      );
    }

    if (type === 'dateBetweens') {
      return (
        <RangePicker
          getPopupContainer={
            getPopupContainer ? getPopupContainer : () => document.body
          }
        />
      );
    }
    return null;
  };

  return (
    <ErrorBoundary>
      <Row>
        {list.map(item => {
          const config = formItemMap[item.type] || {};
          const rules = cloneDeep(config?.rules || []);

          if (item.required) {
            rules.push({ required: true, message: '信息不能为空' });
          }

          return (
            <Col key={item.id} span={span}>
              <Form.Item
                name={item.id}
                label={item.name}
                {...config}
                rules={rules}
              >
                {getMaterialTypeItem(item)}
              </Form.Item>
            </Col>
          );
        })}
      </Row>
    </ErrorBoundary>
  );
};

FormilyRender.defaultProps = {
  list: [],
  span: 12,
  formItemMap: {
    inputs: {
      rules: [{ max: 50, message: '最多50个字符' }],
    },
    multiInputs: {
      rules: [{ max: 200, message: '最多200个字符' }],
    },
  },
};

export default FormilyRender;
