import React, { useEffect, useState } from 'react';
import { Select, Form, Input, Switch, TimePicker, Cascader, Row, Col } from 'antd';
import moment from 'moment';

import { dispatch } from '../../../../model';

const ScheduleAction = (props) => {
  const { action, id, form, tid, onChange } = props;

  const [ schedule, setSchedule ] = useState({});

  useEffect(() => {
    reset();
    if (action === 'add' && tid) {
      getScheduleForm();
    } else {
      getScheduleById();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [ action, id])

  const getScheduleForm = () => {
    dispatch({
      type: 'datasource.getScheduleForm',
      payload: {
        targetConfId: tid
      },
      callback: data => {
        setSchedule(data||{});
        onChange && onChange(data||{});
      }
    });
  }

  const getScheduleById = () => {
    dispatch({
      type: 'datasource.getScheduleById',
      payload: {
        id
      },
      callback: data => {
        function compare(val1, val2) {
          var a = val1.seq;
          var b = val2.seq;
          return (a - b);
        }

        (data?.targetParameters||[]).sort(compare);
        (data?.scheduleParameters||[]).sort(compare);

        setSchedule(data||{});
        setFormFiledsValue(data||{});
        onChange && onChange(data||{});
      }
    })
  }

  const setFormFiledsValue = (data) => {
    let _fieldsValue = {};

    (data?.targetParameters||[]).forEach(item => {
      _fieldsValue[item.name||''] = item.value||'';

      if (item.selectMode === 'switch') {
        _fieldsValue[item.name||''] = (item.value==="1") ? true: false;
      } else if (item.selectMode === 'timePicker') {
        _fieldsValue[item.name||''] = moment(item.value||'', 'HH:mm:ss');
      } else if (item.selectMode === 'cascader') {
        _fieldsValue[item.name||''] = (item.value||'').split(',');
      }
    });

    (data?.scheduleParameters||[]).forEach(item => {
      _fieldsValue[item.name||''] = item.value||'';
      if (item.selectMode === 'switch') {
        _fieldsValue[item.name||''] = (item.value==="1") ? true: false;
      } else if (item.selectMode === 'timePicker') {
        _fieldsValue[item.name||''] = moment(item.value||'', 'HH:mm:ss');
      } else if (item.selectMode === 'cascader') {
        _fieldsValue[item.name||''] = (item.value||'').split(',');
      }
    });

    form.setFieldsValue(_fieldsValue);
  }

  const reset =() => {
    form.resetFields();
  }

  const onValuesChange = (changedValues, allValues) => {
    let newSchedule = JSON.parse(JSON.stringify(schedule));

    (newSchedule?.targetParameters||[]).forEach(item => {
      item.value = allValues[item.name];

      if (item.selectMode === 'switch') {
        item.value = (allValues[item.name||'']===true)?'1':'0';
      } else if (item.selectMode === 'timePicker' && allValues[item.name]) {
        item.value = allValues[item.name||''].format('HH:mm:ss');
      } else if (item.selectMode === 'cascader' && allValues[item.name]) {
        item.value = (allValues[item.name||'']||'').join(',');
      }
    });

    (newSchedule?.scheduleParameters||[]).forEach(item => {
      item.value = allValues[item.name];

      if (item.selectMode === 'switch') {
        item.value = (allValues[item.name||'']===true)?'1':'0';
      } else if (item.selectMode === 'timePicker' && allValues[item.name]) {
        item.value = (allValues[item.name||'']||'').format('HH:mm:ss');
      } else if (item.selectMode === 'cascader' && allValues[item.name]) {
        item.value = (allValues[item.name||'']||'').join(',');
      }
    });

    onChange && onChange(newSchedule);
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };

  const formItemBody = (item) => {
    if (item.selectMode === 'switch') {
      return <Switch />;
    }

    if (item.selectMode === 'singleSelect') {
      const _datas = [];
      
      for (var key in item.selectItemMap) {
        _datas.push({key, value: item.selectItemMap[key]});
      }
        
      return (
        <Select>
        {
          _datas.map((_data, index) => {
            return (
              <Select.Option key={index} value={_data.key}>{_data.value}</Select.Option>
            );
          })
        }
        </Select>
      );
    }

    if (item.selectMode === 'cascader') {
      return <Cascader 
        options={item.selectItemList} 
        expandTrigger="hover"
      />
    }

    if (item.selectMode === 'timePicker') {
      return <TimePicker />;
    }

    return ( 
      item.show ? <Input placeholder={item.explain||''} /> 
      : <Input.Password placeholder={item.explain||''} visibilityToggle={false} /> 
    ) 
  }

  return (
    <Form {...formItemLayout} form={form} onValuesChange={onValuesChange}>
      <Row gutter={10}>
      {
        schedule && (schedule.targetParameters||[]).map((item, index) => {

          let _type = 'string';
          if (item.selectMode === 'switch') {
            _type = 'boolean';
          } else if (item.selectMode === 'timePicker') {
            _type = 'object';
          } else if (item.selectMode === 'cascader') {
            _type = 'array';
          }

          return (
            <Col span={12} key={index}>
              <Form.Item 
                label={item.cnName||''}
                name={item.name||''}
                key={index}
                rules={[{ required: item.required, message: '必填项', type: _type }]}
                valuePropName={(item.selectMode==='switch')? 'checked': 'value'}
              >
              { formItemBody(item) }
              </Form.Item>
            </Col>
          )
        })
      }
      {
        schedule && (schedule.scheduleParameters||[]).map((item, index) => {

          let _type = 'string';
          if (item.selectMode === 'switch') {
            _type = 'boolean';
          } else if (item.selectMode === 'timePicker') {
            _type = 'object';
          } else if (item.selectMode === 'cascader') {
            _type = 'array';
          }

          return (
            <Col span={12} key={index}>
              <Form.Item 
                label={item.cnName||''}
                name={item.name||''}
                rules={[{ required: item.required, message: '必填项', type: _type }]}
                valuePropName={(item.selectMode==='switch')? 'checked': 'value'}
              >
              { formItemBody(item) }
              </Form.Item>
            </Col>
          )
        })
      }
      </Row>
    </Form>
  );
}

export default ScheduleAction;