import React, { useEffect, useState }  from 'react';
import { Row, Col, Checkbox, Typography, Button, Switch, Modal } from 'antd';

import { dispatch } from '../../../../model';
import './FilterElementModal.less';
import { AssetManageReference } from '../../../../util/constant';

//type
//global 全局设置
//admin 管理员
//user 普通用户

const FilterElementModal = (props) => {

  const { visible, onCancel, type = 'global', reference = AssetManageReference } = props;
  const [ elements, setElements ] = useState([]);
  const [ typesOfElements, setTypesOfElements ] = useState([]);
  const [ selectedKeys, setSelectedKeys ] = useState([]);
  const [ confirmLoading, setConfirmLoading ] = useState(false);

  useEffect(() => {

    if (visible) {
      getAllFilterElementIdsThenGetAllElements();
    }
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  const getAllFilterElementIdsThenGetAllElements = () => {

    let url = '';
    let payload = null;
    if (type === 'global') {
      url = 'assetmanage.listFilterElementIdsConfig';
    } else {
      url = 'assetmanage.listFilterElementIds';
      payload = {
        isAdmin: (reference===AssetManageReference)
      }
    }

    dispatch({
      type: url,
      payload,
      callback: data => {
        setSelectedKeys(data||[]);
        getAllElements();
      }
    })
  }

  const getAllElements = () => {

    let url = '';
    if (type === 'user') {
      url = 'assetmanage.listUserElements';
    } else {
      url = 'assetmanage.listElements';
    }

    dispatch({
      type: url,
      callback: data => {
        setElements(data||[]);
        convertElements(data||[]);
      }
    })
  }

  const convertElements = (elements) => {
    const _typesOfElements = [];

    const _types = [];

    (elements||[]).forEach(element => {
      if (_types.indexOf(element.type||'') === -1) {
        _types.push(element.type||'');
      }
    })

    _types.forEach(type => {
      const _elements =  (elements||[]).filter(element => (element.type||'') === type);
      _typesOfElements.push({ type, elements: _elements||[] });
    })

    setTypesOfElements(_typesOfElements);
  }

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

  const onCheckAllChange = (checked) => {
    
    const _selectedKeys = [];

    if (checked) {
      (elements||[]).forEach(element => {
        _selectedKeys.push(element.id||'');
      });
    } else {
      (elements||[]).forEach(element => {
        if (element.selectAble === '否') {
          _selectedKeys.push(element.id||'');
        }
      });
    }

    setSelectedKeys(_selectedKeys);
  }

  const onOk = () => {

    setConfirmLoading(true);

    let url = '';
    if (type === 'global') {
      url = 'assetmanage.setupFilterElementIdsConfig';
    } else {
      url = 'assetmanage.setupFilterElementIds';
    }

    dispatch({
      type: url,
      payload: {
        data: selectedKeys,
        params: {
          isAdmin: (reference===AssetManageReference) 
        }
      },
      callback: () => {
        reset();
        onCancel && onCancel(true);
      }, 
      error: () => {
        reset();
      }
    })
  }

  const cancel = () => {
    reset();
    onCancel && onCancel();
  }

  const reset = () => {
    setConfirmLoading(false);
  }

  return (
    <Modal 
      destroyOnClose centered
      visible={visible}
      title={type==='global'?'资产目录浏览管理':'可见列设置'}
      width={520}
      onCancel={cancel}
      bodyStyle={{ padding: '15px 15px 0px 15px', maxHeight: '80vh', overflow: 'auto' }}
      footer={[ 
        <Button
          key="0" 
          onClick={cancel}
        >
        取消
        </Button>,
        <Button
          key="1" 
          type="primary"
          onClick={onOk}
          loading={confirmLoading}
        >
        确定
        </Button>,
      ]}
    >
      <div className='d-flex'>
        <Switch 
          checkedChildren="全不选" 
          unCheckedChildren="全选" 
          onChange={onCheckAllChange}
          style={{ marginLeft: 'auto' }}
        />
      </div>
      <div>
      {
        (typesOfElements||[]).map((typeOfElements, index) => {
          const _type = typeOfElements.type||'';

          return (
            <div key={index}>
              <div className='flex' style={{ alignItems: 'center', padding: '15px 0' }}>
                <div style={{ width: 3, height: 14, backgroundColor: '#0069AC', marginRight: 5 }} />
                <span style={{ fontWeight: 'bold', color: '#464646' }}>{_type||''}</span>
              </div>
              <Row>
              {
                typeOfElements && typeOfElements.elements && typeOfElements.elements.map((element, _index) => {
                  return (
                    <Col className='mb-3' key={_index} md={6}>
                      <div className='d-flex'>
                      <Checkbox checked={ selectedKeys.indexOf(element.id||'')!==-1 } value={element.id||''} onChange={onCheckChange} disabled={element.selectAble==='否'||element.defaultSelected==='是'} >
                      </Checkbox>
                      <Typography.Paragraph className='ml-1' title={element.name||''} ellipsis>
                      {element.name||''}
                      </Typography.Paragraph>
                      </div>
                    </Col>
                  );
                })
              }
              </Row>
            </div>
          )
        })
      }
      </div>
    </Modal>
  );
}

export default FilterElementModal;