import React, { useEffect, useState, useMemo } from 'react';
import { Modal, Checkbox, Row, Col, Divider, Input, Typography, Form, Switch, Select } from 'antd';

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

const ApprovalCheckbox = ({ value, onChange }) => {
  const handleChange = (e) => {
    onChange?.(e.target.checked?'是':'否');
  }

  return (
    <Checkbox 
      checked={value==='是'}
      onChange={handleChange} 
    />
  )
}

const UpdateTaskModal = (props) => {
  const { visible, onCancel, action, id, datasourceId,currentDatabase } = props;
  const [ schemas, setSchemas ] = useState([]);
  const [ filterSchemas, setFilterSchemas ] = useState([]);
  const [ selectedSchemas, setSelectedSchemas ] = useState([]);
  const [ taskSettings, setTaskSettings ] = useState({});
  const [ currentTask, setCurrentTask ] = useState({});
  const [ keyword, setKeyword ] = useState('');
  const [ confirmLoading, setConfirmLoading ] = useState(false);
  const [ checkAllValue, setCheckAllValue ] = useState(false);

  const [ form ] = Form.useForm();

  useEffect(() => {

    if (visible) {

      reset();

      if (action==='add' && datasourceId) {
        getTaskSettings();
      } else if (action==='edit' && id) {
        getTask();
      }
    }

    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible, action, id, datasourceId])

  useEffect(() => {
    setFilterSchemas((schemas||[]).filter(schema => (schema||'').indexOf(keyword)!==-1));
  }, [keyword, schemas])

  const getTask = () => {
    dispatch({
      type: 'datasource.getTask',
      payload: {
        harvestingTaskId: id
      },
      callback: data => {
        setCurrentTask(data);
        getTaskSettings(data&&data.target?(data.target.id||''):'', data)
      }
    })
  }

  const getTaskSettings = (sourceId = datasourceId, task = null) => {
    dispatch({
      type: 'datasource.getTaskSettingsByDatasource',
      payload: {
        datasourceId: sourceId
      },
      callback: data => {
        setTaskSettings(data);

        let recentSchemas = [];
        let _fieldsValue = {};

        data && (data.targetConfParameters||[]).forEach(item => {
          if (item.name === 'schema') {
            setSchemas(item.selectItem||[]);
            recentSchemas = item.selectItem||[];
          } else {
            _fieldsValue[item.name||''] = item.value||'';
          }
        })

        if (action === 'edit') {
          task && (task.targetConfParameters||[]).forEach(item => {
            if (item.name === 'schema') {
              setSelectedSchemas((item.value||'').split(',').filter(value=> recentSchemas.indexOf(value)!==-1));
            } else {
              _fieldsValue[item.name||''] = item.value||'';
            }
          })
        }

        form.setFieldsValue(_fieldsValue);
      }
    })
  }

  const onOk = async() => {
    try {
      const row = await form.validateFields();

      //深拷贝
      let newTask = JSON.parse(JSON.stringify(taskSettings));

      if (action === 'edit') {
        newTask = {...newTask, ...currentTask};
      }

      newTask && (newTask.targetConfParameters||[]).forEach(item => {
        if (item.name === 'schema') {
          item.value = selectedSchemas.join(',');
        } else {
          item.value = row[item.name]||'';
        }
      });

      setConfirmLoading(true);
      dispatch({
        type: 'datasource.saveTask',
        payload: {
          data: newTask
        },
        callback: data => {
          setConfirmLoading(false);
          onCancel && onCancel(true);
        },
        error: () => {
          setConfirmLoading(false);
        }
      })

    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  }

  const reset = () => {
    setSchemas([]);
    setSelectedSchemas([]);
    setTaskSettings({});
    setCheckAllValue(false);
    form.resetFields();
  }

  const onSearchInputChange = (e) => {
    setKeyword(e.target.value||'');
  }

  const onCheckAll =(checked)=>{        
    setCheckAllValue(checked);

    if (checked) {
      const _newSelectedSchemas = Array.from(new Set([...selectedSchemas, ...filterSchemas]));;

      setSelectedSchemas(_newSelectedSchemas);
    } else {
      setSelectedSchemas(selectedSchemas.filter(schema=>!filterSchemas.includes(schema)));
    }
  }

  const onCheckChange = (e) => {
    if (e.target.checked) {
      setSelectedSchemas([...selectedSchemas, e.target.value]);
    } else {
      const index = selectedSchemas.findIndex(key => key === e.target.value);
      selectedSchemas.splice(index, 1)
      setSelectedSchemas([...selectedSchemas]);
    }
  }

  const targetItem = (param) => {
    if (param.selectMode === 'singleSelect') {
      return (
        <Select allowClear>
        {
          param.selectItem?.map((item, index) => <Select.Option key={index} value={item}>{item}</Select.Option>)
        }
        </Select>
      )
    } else if (param.selectMode === 'checkBox') {
      return <ApprovalCheckbox />;
    }

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

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };

  return (
    <Modal
      className='update-task-modal'
      forceRender
      title={action==='add'?'新增任务':'修改任务'}
      visible={visible}
      width={600}
      onCancel={() => { onCancel && onCancel() }}
      onOk={onOk}
      confirmLoading={confirmLoading}
    >
      <Divider>{(currentDatabase?.type==="Neo4jTarget")?'neo4j数据库信息':'schema信息'}</Divider>
      <div className='d-flex mb-3' style={{ alignItems: 'center' }}>
        <span className='mr-3'>{(currentDatabase?.type==="Neo4jTarget")?'neo4j数据库搜索':'schema搜索'}:</span>
        <Input 
          placeholder={`请输入${(currentDatabase?.type==="Neo4jTarget")?'neo4j数据库':'schema'}名称`}
          allowClear 
          value={keyword}
          onChange={onSearchInputChange} 
          style={{ width: 230 }}
        />
         <Switch 
          checkedChildren="全不选" 
          unCheckedChildren="全选" 
          checked={ checkAllValue } 
          onChange={ onCheckAll } 
          style={{ marginLeft: 'auto' }}
        />
      </div>
      <div style={{ maxHeight: 300, overflow: 'auto' }}>
        <Row className='mb-3'>
        {
          (filterSchemas||[]).map((schema, index) => {
            return (
              <Col className='mt-1' key={index} md={8}>
                <div className='d-flex'>
                  <Checkbox checked={ selectedSchemas.indexOf(schema)!==-1 } value={schema||''} onChange={onCheckChange} >
                  </Checkbox>
                  <Typography.Paragraph className='ml-1' title={schema||''} ellipsis>
                  {schema||''}
                  </Typography.Paragraph>
                </div>
              </Col>
            );
          })
        }
        </Row>
      </div>
      <Divider>过滤信息</Divider>
      <Form {...formItemLayout} form={form}>
      {
        taskSettings && (taskSettings.targetConfParameters||[]).sort((val1, val2) => (val1.seq-val2.seq)).filter(item => item.name!=='schema').map((param, index) => {
          return (
            <Form.Item 
              label={param.cnName||''}
              name={param.name||''}
              key={index}
              rules={[{ required: param.required, message: '必填项'}]}
            >
            { targetItem(param) }
            </Form.Item>
          )
        })
      }
      </Form>
    </Modal>
  );
}

export default UpdateTaskModal;