import React, { useEffect, useState } from 'react';
import { Input, Table, Tooltip } from 'antd';

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

const ConstraintDetail = (props) => {
  const [ loading, setLoading ] = useState(false);
  const [ rules, setRules ] = useState([]);
  const [ keyword, setKeyword ] = useState('');

  useEffect(() => {
    setLoading(true);
    dispatch({
      type: 'datamodel.getAllConstraints',
      callback: data => {
        setLoading(false);
        const _rules = [];
        (data||[]).forEach(constraint => {
          (constraint.allRules||[]).forEach(rule => {
            _rules.push({...constraint, ...{ ruleName: rule.name||'', ruleDesc: rule.desc||'' }});
          });
        });

        setRules(_rules);
      },
      error: () => {
        setLoading(false);
      }
    })
    //eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,
      render: (_, __, index) => {
        return (index+1).toString();
      },
      width: 60,
    },
    {
      title: '规范名称',
      dataIndex: 'name',
      width: 180,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '规范中文名称',
      dataIndex: 'cnName',
      width: 180,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '前置依赖',
      dataIndex: 'ruleName',
      width: 180,
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    },
    {
      title: '描述',
      dataIndex: 'ruleDesc',
      ellipsis: true,
      render: (text, _, __) => {
        return (
          <Tooltip title={text||''}>
            <span>{text||''}</span>
          </Tooltip>
        )
      }
    }
  ]

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

  return (
    <div>
      <div className='d-flex mb-3' style={{ alignItems: 'center' }}>
        <Input 
          placeholder="请输入前置依赖名称" 
          allowClear 
          value={keyword}
          onChange={onSearchInputChange} 
          style={{ width: inputWidth }}
        />
      </div>
      <Table
        loading={loading}
        columns={columns} 
        rowKey={'ruleName'}
        dataSource={(rules||[]).filter(item => (item.ruleName||'').indexOf(keyword)!==-1)}
        pagination={false} 
        sticky
      />
    </div>
  );
}

export default ConstraintDetail;