import React, { useState, useEffect } from 'react';
import {
    Form,
    Card,
    Space,
    Table,
    Popconfirm,
    Spin,
    Tooltip,
    notification,
} from 'antd';

import {
    DoubleLeftOutlined,
    DoubleRightOutlined,
    PlusSquareFilled,
    RightOutlined,
    EditTwoTone,
    DeleteOutlined
} from '@ant-design/icons';
import classnames from 'classnames';
import PageContainer from '@/components/BasePageContainer';
import { GetCM_Ledger_LoadLedgers, CM_Ledger_RmoveLedger } from '@/services/standingBook/api';
import AddModal from './editorModal'
import styles from './standingBook.less';
const standingBook = props => {
    const [allData, setAllData] = useState([]);
    const [tableData, setTableData] = useState([]);
    const [treeLoading, setTreeLoading] = useState(false);
    const [maxLength, setMaxLength] = useState(0);
    const [treeVisible, setTreeVisible] = useState(true); // 左边列表是否可见
    const [formObj, setFormObj] = useState('');
    const [flag, setFlag] = useState(0); // 弹窗类型
    const [isVisible, setIsVisible] = useState(false); // 弹窗
    const [isType, setIsType] = useState(''); // 弹窗类型
    const [pickItem, setPickItem] = useState('');
    const { Item } = Form;

    const editor = record => {
        setFormObj(record);
        setIsType('edit');
        setIsVisible(true);

    };
    const Submit = prop => {
        setIsVisible(false);
        setFlag(flag + 1);
    };

    const columns = [
        {
            title: '台账类型',
            dataIndex: 'AccountType',
            key: 'AccountType',
            width: 100,
        },
        {
            title: '台账名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
            width: 200,
        },

        {
            title: '台账表名',
            dataIndex: 'tableName',
            key: 'tableName',
            align: 'center',
            width: 300,
        },
        {
            title: '台账字段',
            dataIndex: 'fields',
            key: 'fields',
            align: 'center',

        },
        {
            title: '检索字段',
            dataIndex: 'searchFields',
            key: 'searchFields',
            align: 'center',
  
        },
        {
            title: '添加字段',
            dataIndex: 'addFields',
            key: 'addFields',
            align: 'center',
         
        },

        {
            title: '编辑字段',
            dataIndex: 'editFields',
            key: 'editFields',
            align: 'center',
    
        },
        {
            title: '前端字段',
            dataIndex: 'webFields',
            key: 'webFields',
            align: 'center',
       
        },
        {
            title: '手持字段',
            dataIndex: 'mobileFields',
            key: 'mobileFields',
            align: 'center',
    
        },
        {
            title: '操作',
            ellipsis: true,
            align: 'center',
            render: (text, record) => (
                <Space>
                    <Tooltip title="编辑此表">
                        <EditTwoTone
                            onClick={() => editor(record)}
                            style={{ fontSize: '16px' }}
                        />
                    </Tooltip>


                    <Tooltip title="删除此表">
                        <Popconfirm
                            placement="bottomRight"
                            title={
                                <p>
                                    是否删除此表
                                </p>
                            }
                            // title={`确认删除用户${currentUser}`}
                            okText="确认"
                            cancelText="取消"
                            onConfirm={() => deleteChart(record)}
                        >
                            <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                        </Popconfirm>
                    </Tooltip>

                </Space>
            ),
        },
    ];


    useEffect(() => {
        setTreeLoading(true);
        GetCM_Ledger_LoadLedgers().then(res => {
            setTreeLoading(false);
            if (res.msg === 'Ok' && res.data.root) {
                setMaxLength(res.data.root.length + 1)
                let arr = formateArrDataA(res.data.root, 'type')
                let newArr = []
                Object.keys(arr).map((item, index) => {
                    newArr.push(item)
                })
                setAllData(arr);
                setPickItem(newArr[0])
                console.log(newArr, 'newArr');
                setTableData(newArr);
            }
        });

    }, [flag]);
    const formateArrDataA = (initialArr, name) => {
        // 判定传参是否符合规则
        if (!(initialArr instanceof Array)) {
            return '请传入正确格式的数组'
        }
        if (!name) {
            return '请传入对象属性'
        }
        //先获取一下这个数组中有多少个"name"
        let nameArr = []
        for (let i in initialArr) {
            if (nameArr.indexOf(initialArr[i][`${name}`]) === -1) {
                nameArr.push(initialArr[i][`${name}`])
            }
        }
        //新建一个包含多个list的结果对象
        let tempObj = {}
        // 根据不同的"name"生成多个数组
        for (let k in nameArr) {
            for (let j in initialArr) {
                if (initialArr[j][`${name}`] == nameArr[k]) {
                    // 每次外循环时新建一个对应"name"的数组, 内循环时当前数组不变
                    tempObj[nameArr[k]] = tempObj[nameArr[k]] || []
                    tempObj[nameArr[k]].push(initialArr[j])
                }
            }
        }
        for (let keys in tempObj) {
            let arr = []
            tempObj[keys].map((item, index) => {
                tempObj[keys] = arr;
                item.key = index
                arr.push(item)
            })
        }
        return tempObj
    }
    // 删除表字段
    const deleteChart = record => {
        CM_Ledger_RmoveLedger({ ledgerId: record.ID }).then(res => {
            if (res.msg === 'Ok' || res.msg === '') {
                notification.success({
                    message: '提示',
                    duration: 3,
                    description: '删除成功',
                });
                setFlag(flag + 1);
            } else {
                notification.error({
                    message: '提示',
                    duration: 3,
                    description: res.msg,
                });
            }
        });
    };
    //显示弹框
    const showPopup = () => {
        setIsVisible(true)
        setIsType('add')
    }
    const onSubmit = () => {
        setIsVisible(false);
        setFlag(flag + 1)
    };
    return (
        <PageContainer className={styles.userManageContainer}>
            <div className={styles.contentContainers}>
                <Spin spinning={treeLoading} tip="loading...">

                    <Card
                        className={classnames({
                            [styles.orgContainer]: true,
                            [styles.orgContainerHide]: !treeVisible,
                        })}
                    >
                        {treeVisible ? <>
                            <div>
                                <span
                                    style={{
                                        fontSize: '15px ',
                                        fontWeight: 'bold',
                                        color: '#333E51',
                                        paddingLeft: '14px'
                                    }}
                                >
                                    台账列表
                                </span>
                                <Tooltip title="添加台账表">
                                    <PlusSquareFilled
                                        style={{
                                            color: '#1890FF',
                                            fontSize: '25px',
                                            verticalAlign: 'middle',
                                            float: 'right',
                                            paddingRight: '14px'
                                        }}
                                        onClick={e => showPopup()}
                                    />
                                </Tooltip>
                                <hr style={{ width: '100%', color: '#eeecec' }} />
                                {
                                    tableData.length>0 && (tableData.map((item, index) => {
                                        return <div className={classnames({
                                            [styles.listItem]: true,
                                            [styles.pickItem]: item === pickItem,
                                        })} onClick={e => setPickItem(item)} key={index}>{item}({allData[item] ? allData[item].length : ''}) {item === pickItem ? <RightOutlined /> : ''} </div>
                                    })
                                    )}
                            </div></> : ''}

                        <div className={styles.switcher}>
                            {treeVisible && (
                                <Tooltip title="隐藏台账列表">
                                    <DoubleLeftOutlined onClick={() => setTreeVisible(false)} />
                                </Tooltip>
                            )}
                            {!treeVisible && (
                                <Tooltip title="显示台账列表">
                                    <DoubleRightOutlined onClick={() => setTreeVisible(true)} />
                                </Tooltip>
                            )}
                        </div>
                    </Card>
                </Spin>
                <div
                    className={classnames({
                        [styles.userContainer]: true,
                        [styles.userContainerHide]: !treeVisible,
                    })}
                >
                    <Table
                        size="small"
                        rowKey='ID'
                        bordered
                        onRow={record => {
                            return {
                              onDoubleClick: event => {event.stopPropagation(); editor(record)}, //双击
                            };
                          }}
                        columns={columns}
                        dataSource={allData[pickItem]}
                        // loading={tableLoading}
                        scroll={{ x: 'max-content', y: 'calc(100vh - 150px)' }}
                        // scroll={{ x: 'max-content' }}
                        pagination={{
                            showTotal: (total, range) =>
                                `第${range[0]}-${range[1]} 条/共 ${total} 条`,
                            pageSizeOptions: [10, 20, 50, 100],
                            defaultPageSize: 20,
                            showQuickJumper: true,
                            showSizeChanger: true,
                        }}
                    />
                </div>
                <AddModal visible={isVisible} type={isType} formObj={formObj} maxLength={maxLength} callBackSubmit={onSubmit} onCancel={() => setIsVisible(false)} tableData={tableData} />
            </div>

        </PageContainer>

    );
};
export default standingBook;