/*
 * @Author: your name
 * @Date: 2021-12-07 09:28:41
 * @LastEditTime: 2022-02-28 14:11:18
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /MedicalWisdomCheckSys/src/pages/GradeHospitalAccreditation/accreditationDetail/components/materialTable/index.tsx
 */


import React, { useEffect, useState,useRef } from 'react';
import MccsSelect from '@/components/MccsProFormSelect/index';

import { Input, Row, Col, Button, Checkbox, Divider, Pagination, Empty,Spin,Tooltip } from 'antd';

import './style.less';
import { CheckboxChangeEvent } from 'antd/lib/checkbox';


const { Search } = Input;

const TableItem: React.FC<any> = ({ data, actionHandle,checkBoxChangeHandle }) => {

    //注意！！！！data类型有待补充
    const textWraperSpanRef = useRef(null);
    const subTextRef = useRef(null);
    const [ifShowTip,setIfShowTip] = useState(false);
    const [ifHasMore,setifHasMore] = useState(false);

    const onVisibleChangeHanfle = (bool:boolean)=>{
         if(bool){
            setIfShowTip(ifHasMore);
         }else{
            setIfShowTip(false);
         }
    }

    useEffect(()=>{
        if(textWraperSpanRef.current&&subTextRef.current){
            setifHasMore(textWraperSpanRef.current['clientWidth'] > subTextRef.current['clientWidth'])
        }
    },[]);

    return (
        <div className='tableChild'>
            {
                //用于测量渲染出文案的长度
            }
            <div ref={textWraperSpanRef} style={{height:0.1,position:'absolute',visibility:'hidden'}}>{`档次：${data.grade}   目录：${data.directory}`}</div>

            <Checkbox className='check' onChange={(e:CheckboxChangeEvent)=>checkBoxChangeHandle(e,data)} />
            <div className='tableChildContent' ref={subTextRef}>
                {(data.sort&&data.profileName)&&<div className='mainText'>{`${data.sort}.${data.profileName}`}</div>}
                <Tooltip title={`档次：${data.grade}   目录：${data.directory}`} visible={ifShowTip} onVisibleChange={onVisibleChangeHanfle}>
                    <div className='subText' >{`档次：${data.grade}   目录：${data.directory}`}</div>
                </Tooltip>
            </div>
            <div className='action'>
                <a onClick={() => actionHandle('EDIT',[data])}>修改</a><Divider type='vertical' /><a onClick={() => actionHandle('DEL',[data])}>删除</a>
            </div>
        </div>
    )
}

const MaterialTable: React.FC<MaterialTable.MaterialTableProps> = (props) => {

    const { selectOptions, request, addHandle, tableItemActionHandle } = props;
    const [list, setList] = useState<any[]>([]);
    const [selectorFilter, setSelectorFilter] = useState<string>('');  //下拉筛选
    const [keyword, setKeyword] = useState<string>('');
    const [relaodData, setRelaodData] = useState(false);
    const [loading,setLoading] = useState(false); //加载中
    const [pageData, setPageData] = useState<{
        pageSize: number,
        current: number,
    }>({ current: 1, pageSize: 10 });
    const [total,setTotal] = useState(0);
    const [checkedList,setCheckedList] = useState<any[]>([]); //已勾选的项集合


    const geData = async () => {
        if (request) {
            setLoading(true);
            const res = await request({ ...pageData, keyword, selectorFilter:selectorFilter=='全部'?'':selectorFilter });
            if (res) {
                setList(res.list);
                setPageData({
                    pageSize: res.pageSize,
                    current: res.current
                });
                setTotal(res.total);
                setRelaodData(false);
                setLoading(false);
            }
        }
    }

    const tableItemAction = async (type: 'EDIT' | 'DEL', data: any[]) => {
        if (tableItemActionHandle) {
            const resp = await tableItemActionHandle(type, data);
            if (resp) {
                geData();
            }
        }
    }

    const checkBoxChangeHandle = (e:CheckboxChangeEvent,data:any)=>{
       if(e.target.checked){
        setCheckedList([...checkedList,data]);
       }else{
          let _checkedList = checkedList;
          _checkedList.splice(_checkedList.findIndex(t=>t.id == data.id),1);
          setCheckedList([..._checkedList]);
       }
    }
    
    //批量删除
    const batchDelList = async ()=>{
        if (tableItemActionHandle) {
            const resp = await tableItemActionHandle('DEL',checkedList);
            if (resp) {
                geData();
                setCheckedList([]);
            }
        }
    }


    useEffect(() => {
        //刷新数据
        if (relaodData) {
            geData();
        }
    }, [relaodData]);

    useEffect(() => {
        if (props.reload) {
            setRelaodData(true);
        }
    }, [props]);

    useEffect(() => {
        geData();
    }, [])

    return (
        <div className='materialTable'>
            <div className='tableFilter'>
                <Row>
                    <Col span={8}>
                        <MccsSelect
                            selectList={selectOptions ? [{ label: '全部', value: '全部' }, ...selectOptions] : []}
                            width="sm"
                            fieldProps={{
                                defaultValue: '全部',
                                onChange: val => {
                                    setSelectorFilter(val);
                                    setRelaodData(true);
                                }
                            }}
                        />
                    </Col>
                    <Col span={15} offset={1}>
                        <Search placeholder={'请输入'}
                            allowClear
                            onSearch={val => {
                                setKeyword(val);
                                setRelaodData(true);
                            }}
                            onChange={e => {
                                const key = e.target.value;
                                if (!key || key.length == 0) {
                                    setKeyword(key);
                                    setRelaodData(true);
                                }
                            }}
                        />
                    </Col>
                </Row>
            </div>
            <div className='titleAndAction'>
                <div className='tableTitle'>资料目录</div>
                <div className='actionBtnGroup'>
                    {checkedList.length>0&&<Button className='actionBtn' onClick={batchDelList}>{`批量删除(${checkedList.length})`}</Button>}
                    <Button type='primary' className='addBtn actionBtn' onClick={() => addHandle && addHandle()}>新增</Button>
                </div>
            </div>
            <div className='tableList'>
                {loading&&<div style={{display:'flex',width:'100%',height:'100%',justifyContent:'center',alignItems:'center'}}><Spin /></div>}
                {
                    (list.length == 0&&!loading) && (
                        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    )
                }
                {
                    !loading&&list.map((item, index) => (
                        <TableItem key={index} data={item} actionHandle={tableItemAction} checkBoxChangeHandle={checkBoxChangeHandle} />
                    ))
                }
            </div>
            <div style={{ display: 'flex', justifyContent: 'center',alignItems:'center' }}>
                {/* <Pagination size="small" total={50} /> */}
                <Pagination
                    size="small"
                    hideOnSinglePage={true}
                    showLessItems={true}
                    showSizeChanger
                    simple={true}
                    current={pageData.current}
                    onChange={(page, pageSize) => {
                        setPageData({
                            current:page,
                            pageSize:pageSize?pageSize:10
                        });
                        setRelaodData(true);
                    }}
                    defaultCurrent={3}
                    total={total}
                />
                <div style={{fontSize:12}}>10条/页</div>
            </div>
        </div>
    )
}

export default MaterialTable;
