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

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

const ColSettingModal = (props) => {
  const {visible, onCancel} = props;

  const [loadingAttrs, setLoadingAttrs] = useState(false);
  const [attrs, setAttrs] = useState(undefined);
  const [catagories, setCatagories] = useState(undefined);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [confirmLoading, setConfirmLoading] = useState(false);

  useEffect(() => {
    if (visible) {
      getAttrs();
      getPreference();
    }
  }, [visible]);

  const getAttrs = () => {
    setLoadingAttrs(true);
    dispatch({
      type: 'pds.getAttrs',
      payload: {
        modelName: 'DataService'
      },
      callback: data => {
        setAttrs(data);
        setCatagories(Array.from(new Set((data||[]).map(item => item.status))));
        setLoadingAttrs(false);
      },
      error: () => {
        setLoadingAttrs(false);
      }
    })
  }

  const getPreference = () => {
    dispatch({
      type: 'pds.getCols',
      payload: {
        modelName: 'DataService'
      },
      callback: data => {
        setCheckedKeys(data?.map(item => item.titleCnName));
      }
    })
  }

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

    if (checked) {
      attrs?.forEach(col => {
        newCheckedKeys.push(col.name);
      });
    }

    setCheckedKeys(newCheckedKeys);
  }

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

  const onModalCancel = () => {
    onCancel && onCancel();
  }

  const onModalOk = () => {
    if ((checkedKeys||[]).length === 0) {
      showMessage('warn', '不可进行全不选操作');
      return;
    }

    setConfirmLoading(true);
    dispatch({
      type: 'pds.saveCols',
      payload: { 
        params: {modelName: 'DataService'},
        data: checkedKeys?.map(item => {
          return { titleCnName: item }
        })
      },
      callback: () => {
        setConfirmLoading(false);
        onCancel && onCancel(true);
        showMessage('success', '操作成功');
      },
      error: () => {
        setConfirmLoading(false);
      }
    })
  }

  return (
    <Modal
      title='可见列设置'
      visible={visible}
      onCancel={onModalCancel}
      footer={[ 
        <Button
          key="0" 
          onClick={onModalCancel}
        >
        取消
        </Button>,
        <Button
          key="1" 
          type="primary"
          onClick={onModalOk}
          loading={confirmLoading}
        >
        确定
        </Button>,
      ]}
    >
      <div className='d-flex'>
        <Switch 
          checkedChildren="全不选" 
          unCheckedChildren="全选" 
          onChange={onCheckAllChange}
          style={{ marginLeft: 'auto' }}
        />
      </div>
      <div className='mt-3' style={{ maxHeight: 450, overflow: 'auto' }}>
        {
          catagories?.map((catagory, index) => {
            return (
              <div key={index}>
                <div className='flex' style={{ alignItems: 'center', padding: '5px 0 15px' }}>
                  <div style={{ width: 3, height: 14, backgroundColor: '#0069AC', marginRight: 5 }} />
                  <span style={{ fontWeight: 'bold', color: '#464646' }}>{catagory}</span>
                </div>
                <Row>
                {
                  attrs?.filter(col => col.status===catagory)?.map((col, index) => {
                    return (
                      <Col className='mb-3' key={index} md={6}>
                        <div className='d-flex'>
                          <Checkbox checked={ checkedKeys.indexOf(col.name||'')!==-1 } value={col.name} onChange={onCheckChange} >
                          </Checkbox>
                          <Typography.Paragraph className='ml-1' title={col.name} ellipsis>
                          {col.name}
                          </Typography.Paragraph>
                        </div>
                      </Col>
                    )
                  })
                }
                </Row>
              </div>
            )
          })
        }
      </div>
    </Modal>
  )
}

export default ColSettingModal;