/* eslint-disable no-underscore-dangle */
import React, { useEffect } from 'react';

import { Form, Modal, Input, TimePicker, message } from 'antd';
import moment from 'moment';
import { AddOrEditWorkTime } from '@/services/holidays/holidays';

const WorkTiemConfig = props => {
  const { onSubumit, handleCancel, visible, msg, modalType, allTime } = props;
  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
    if (visible) {
      getFormData();
    }
  }, [visible]);
  // 获取表单回显
  const getFormData = () => {
    console.log(msg, 'msg');
    form.setFieldsValue({
      workTime: [moment(msg.from, 'HH:mm:ss'), moment(msg.to, 'HH:mm:ss')],
    });
  };
  // 时间段是否重叠
  const isOverlap = (StartA, EndA, StartB, EndB) => {
    const getT = t => new Date(t);
    return !(getT(EndA) <= getT(StartB) || getT(StartA) >= getT(EndB));
  };

  // 提交表单
  const onFinish = () => {
    form.validateFields().then(validate => {
      if (validate) {
        let obj = {};
        console.log(modalType);
        console.log(validate);
        console.log(moment(validate.workTime[0]._d).format('HH:mm:ss'));
        let startTime = moment(validate.workTime[0]._d).format('HH:mm:ss');
        let endTime = moment(validate.workTime[1]._d).format('HH:mm:ss');
        for (let i = 0; i < allTime.length; i++) {
          if (allTime[i].name !== msg.name) {
            console.log(`${moment().format('YYYY-MM-DD')} ${allTime[i].from}`);
            if (
              isOverlap(
                `${moment().format('YYYY-MM-DD')} ${startTime}`,
                `${moment().format('YYYY-MM-DD')} ${endTime}`,
                `${moment().format('YYYY-MM-DD')} ${allTime[i].from}`,
                `${moment().format('YYYY-MM-DD')} ${allTime[i].to}`,
              )
            ) {
              message.error(`时间段与${allTime[i].name}时间段重合`);
              return;
            }
          }
        }

        AddOrEditWorkTime({ type: msg.type, startTime, endTime }).then(res => {
          if (res.code === 0) {
            message.success('修改成功');
            onSubumit();
          }
        });
      }
    });
  };
  return (
    <Modal
      title={`编辑${msg.name}时间`}
      visible={visible}
      onOk={onFinish}
      onCancel={handleCancel}
      maskClosable={false}
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
      >
        <Form.Item label="工作时间" name="workTime">
          <TimePicker.RangePicker />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default WorkTiemConfig;
