import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux'
/*import { useDispatch,useSelector } from 'react-redux'*/
import { Table, Modal, message, Space, Form, Input, Button, Row, Col, Select } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import AddRole from './AddRole';
import './index.less';
import apiObj from '@api/index';
import RoleContext from './role-context';
import { pickCheckedTreeIds, getValueFromEvent } from '@utils/index'
const { post, api, xPost } = apiObj;

const { Option } = Select;
function RoleManager() {
    useEffect(() => {
        getTableData();
    }, []);

    const [dataSource, setDataSource] = useState([]);   //列表数据
    const [roleDetail, setRoleDetail] = useState(null);   //角色详情数据
    const [visible, setVisible] = useState(false);   //删除禁用确认弹窗显示
    const [addVisible, setAddVisible] = useState(false);         //新增页面显示
    const [confirmLoading, setConfirmLoading] = useState(false);
    //弹窗类型：1删除 2有用户删除 3禁用 4有用户禁用
    const [modalType, setModalType] = useState(1);
    const [operId, setOperId] = useState('');    //当前操作的角色id
    const [total, setTotal] = useState(0);
    const [size, setSize] = useState(15);
    const [current, setCurrent] = useState(1);
    const [params, setParams] = useState({
        pages: 1,
        current: 1,
        size: 15
    });
    //从state中取出状态、类型列表
    const staticInfo = useSelector(state => {
        return state.staticInfo;
    });
    const { statusList } = staticInfo;
    const tipText = {
        1: '确定要删除该角色？',
        2: '当前角色存在用户，删除后用户将一并被删除',
        3: '确定要禁用该角色？',
        4: '当前角色存在用户，禁用后用户将一并被禁用',
    };
    let data = {
        pages: 1,
        current: 1,
        size: size
    }
    //获取表格数据
    function getTableData(param) {
        post(api.getRolePage, param || params).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                setDataSource(data.records);
                setTotal(data.total)
            }

        })
    }
    //启用/禁用
    function enable(flag, id) {
        const param = { roleId: id || operId, status: flag };
        xPost(api.disableRole, param).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setVisible(false);
                message.success((flag ? '启用' : '禁用') + "成功");
            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    //删除
    function onDelete() {
        const param = { roleId: operId };
        xPost(api.deleteRole, param).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setVisible(false);
                message.success("删除成功");
            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    //显示弹窗
    function showModal(type, id) {
        setModalType(type);
        setOperId(id);
        setVisible(true);
    }
    //弹窗确认事件
    function handleOk() {
        if ("1,2".indexOf(modalType) > -1) {
            onDelete();
        } else if ("3,4".indexOf(modalType) > -1) {
            enable(0);
        }
    }
    //弹窗取消
    function handleCancel() {
        setVisible(false);
        setAddVisible(false);
    }
    //新增角色弹窗
    function showAddRole() {
        setAddVisible(true);
    }
    function getRoleDetail(id) {
        return xPost(api.getRoleById, { roleId: id });
    }
    //修改角色
    async function editRole(id) {
        const data = await getRoleDetail(id);
        const detail = data.data;
        if (detail.code === 200) {
            const content = detail.data;
            const menuData = content.loginUserMenuResourceTree;
            const loginSoftwares = content.loginSoftwares;
            let softwares = [], sids = [];
            for (let i = 0; i < menuData.length; i++) {
                const obj = pickCheckedTreeIds(menuData[i]);
                softwares.push(obj);
            }
            for (let j = 0; j < loginSoftwares.length; j++) {
                const obj = loginSoftwares[j];
                if (obj.relation == '1') {
                    sids.push(obj.id);
                }
            }
            const fData = Object.assign({}, content, { sids, softwares });
            setRoleDetail(fData);
        }
        setAddVisible(true);
    }

    //保存
    function addRole(formData) {
        let url = api.addRole;
        const arr = formData.softwares.filter((it) => {
            if (Object.keys(it).length && it.softwareMenuIds && it.softwareMenuIds.length) {
                return it;
            }
        });
        if (roleDetail) {     //修改角色
            formData.id = roleDetail.id;
            url = api.updateRole;
        }
        formData.softwares = arr;
        post(url, formData).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setAddVisible(false);
                setRoleDetail(null)
                message.success("添加成功");
            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    function goBack() {
        setAddVisible(false);
        setRoleDetail(null)
        getTableData();
    }
    function onSizeChange(current, pageSize) {
        params.current = current
        params.size = pageSize
        setSize(pageSize)
        setCurrent(current)
        setParams(params)
        getTableData()
    }
    function changePage(page, pageSize) {
        params.current = page
        params.size = pageSize
        setCurrent(page)
        setParams(params)
        getTableData()
    }
    //表格渲染
    function RenderTable() {
        const columns = [
            { title: '角色名称', dataIndex: 'name', key: 'name' },
            { title: '角色描述', dataIndex: 'remark', key: 'remark' },
            {
                title: '状态', key: 'statusName', render: (row) => {
                    return (<span className={(row.status === '1') ? 'Enable' : 'Disable'}>{row.statusName}</span>)
                }
            },
            /*{ title: '创建时间', dataIndex: 'gmtCreate', key: 'gmtCreate' },*/
            {
                title: '操作', key: 'operation', render: (row, i) => {
                    //console.log(21,row)
                    if (row.rootFlag) {
                        return '-'
                    }
                    return (<Space size="middle">
                        <a onClick={() => editRole(row.id)}>修改</a>
                        {row.status === '1' ? (<a className="disable" onClick={() => showModal(row.hasUserFlag ? 4 : 3, row.id)}>禁用</a>) : (<a onClick={() => enable(1, row.id)}>启用</a>)}
                        <a className="delete" onClick={() => showModal(row.hasUserFlag ? 2 : 1, row.id)}>删除</a>
                    </Space>)
                }
            },
        ];
        return (
            <Table
                className="components-table-demo-nested"
                rowKey={record => record.id}
                scroll={{ y: 'calc(100vh - 360px)' }}
                columns={columns}
                dataSource={dataSource}
                pagination={{
                    current: current,
                    pageSize: size,
                    size: 'small',
                    showSizeChanger: true,
                    pageSizeOptions: ['15', '30', '60', '120'],
                    showTotal: (total, range) => `第${range[0]}-${range[1]} 条/共 ${total} 条数据`,
                    onShowSizeChange: (current, pageSize) => onSizeChange(current, pageSize), // 改变每页数量时更新显示
                    onChange: (page, pageSize) => changePage(page, pageSize),//点击页码事件
                    total: total
                }}
            />
        )
    }
    //筛选项渲染
    const [form] = Form.useForm();
    const onFinish = (values) => {
        const param = {
            ...data,
            ...params
        }
        setCurrent(1)
        setParams(param)
        getTableData(param);
    };
    const onReset = () => {
        setCurrent(1)
        setParams(data)
        form.resetFields();
        getTableData(data);
    };
    if (addVisible) {
        return (
            <RoleContext.Provider value={{ save: addRole, detail: roleDetail }}>
                <AddRole back={goBack} />
            </RoleContext.Provider>
        )
    }
    return (
        <div className='wrapper'>
            <div className="filter-box">
                <Form form={form} name="control-hooks" onFinish={onFinish} initialValues={{ status: '' }}>
                    <Row gutter={24}>
                        <Col span={5} key={0}>
                            <Form.Item name="name" label="角色名称" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder='角色名称' autoComplete='off' />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={2}>
                            <Form.Item name="status" label="当前状态">
                                <Select
                                    allowClear
                                >
                                    {statusList.map((item) => {
                                        return (
                                            <Option value={item.name} key={item.name}>{item.val}</Option>
                                        )
                                    })}
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={9} key={3}>
                            <Form.Item>
                                <Button type="primary" htmlType="submit">
                                    查询
                                </Button>
                                <Button htmlType="button" onClick={onReset}>
                                    重置
                                </Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </div>
            <div className="table">
                <div className="table-header">
                    <h2 className="table-title">组织管理</h2>
                    <Button type="primary" icon={<PlusOutlined />} onClick={() => showAddRole()}>新增角色</Button>
                </div>
                <RenderTable />
            </div>
            <Modal
                title="提示"
                okText='确定'
                cancelText='取消'
                width={400}
                visible={visible}
                onOk={handleOk}
                confirmLoading={confirmLoading}
                onCancel={handleCancel}
            >
                <p>{tipText[modalType]}</p>
            </Modal>
        </div>
    )
}

export default RoleManager;