import React, { useState, useEffect } from 'react';
import { Select, TimePicker } from 'antd';
const { Option } = Select;
import moment from 'moment';

const OnTime = (porps: any) => {
  // placeholder 默认显示  disabled  是否禁止
  // openSelect  选中函数  limit 限制时间    type 类型  时开始还是结束   1 就是结束 结尾是59
  // defaultValue 默认时间
  let { placeholder, disabled, openSelect, limit, type, defaultValue } = porps;

  const [imgOpen, setImgOpen] = useState(null as any);

  useEffect(() => {
    if (defaultValue != null) {
      let a = moment(defaultValue, 'HH:mm');
      setImgOpen(a);
    }
  }, [defaultValue]);

  // console.log(limit);
  // 生成数组 -- 时间
  const createArray = (num: any) => {
    var arr = [];
    for (let i = 0; i < num; i++) {
      if (i < 10) {
        arr[i] = `0${i}`;
      } else {
        arr[i] = i;
      }
    }
    return arr;
  };

  //小时
  const hourS = createArray(24).map((item) =>
    // 处理限制时间段
    limit ? (
      <Option value={item + (type ? ':59' : ':00')} key={item} disabled={Times(item, limit)}>
        {item + (type ? ':59' : ':00')}
      </Option>
    ) : (
      <Option value={item + (type ? ':59' : ':00')} key={item}>
        {item + (type ? ':59' : ':00')}
      </Option>
    ),
  );

  // 字符串截取判断
  function Times(item: any, openTime: string) {
    if (
      parseInt(item) >= parseInt(openTime.slice(0, 2)) &&
      parseInt(item) <= parseInt(openTime.slice(6, 8))
    ) {
      return false;
    } else {
      return true;
    }
  }

  return (
    <>
      {defaultValue ? (
        <TimePicker
          defaultValue={moment(defaultValue, 'HH:mm')}
          format="HH:mm"
          onChange={openSelect}
          placeholder={placeholder}
          defaultOpenValue={moment('00:00', 'HH:mm')}
          disabled={disabled}
        />
      ) : (
        <Select
          style={{ width: 140 }}
          placeholder={placeholder}
          disabled={disabled}
          onSelect={openSelect}
        >
          {hourS}
        </Select>
      )}
    </>
  );
};

export default OnTime;
