import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux'
import { Table, Modal, message, Menu, Dropdown, Space, Form, Input, Button, Row, Col, Select } from 'antd';
import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import AddSubOrg from './AddSubOrg';
import './index.less';
import apiObj from '@api/index';
import OrgContext from './org-context';
import { pickCheckedTreeIds, getValueFromEvent, getCookie } from '@utils/index'

const { post, api, xPost } = apiObj;
const { Option } = Select;
function OrgManager() {
    useEffect(() => {
        //监听resize事件
        // setTableHt(window.innerHeight - 260);
        // window.addEventListener('resize', () => {
        //     setTableHt(window.innerHeight - 260);
        // });
        //刷新列表
        setOrgType(getCookie('hosType'))
        getTableData();
        //解绑事件
        // return function clear() {
        //     window.removeEventListener("resize");
        // }

    }, []);

    const [dataSource, setDataSource] = useState([]);   //列表数据
    // const [tableHt, setTableHt] = useState(300);   //表格滚动高度
    const [visible, setVisible] = useState(false);   //删除禁用确认弹窗显示
    const [addVisible, setAddVisible] = useState(false);         //新增页面显示
    const [confirmLoading, setConfirmLoading] = useState(false);
    //弹窗类型：1删除 2有子组织、用户删除 3禁用 4有子组织、用户禁用 5重置密码
    const [modalType, setModalType] = useState(1);
    const [operId, setOperId] = useState('');    //当前操作的组织id
    const [orgId, setOrgId] = useState('');      //上级组织id
    const [orgName, setOrgName] = useState('');      //上级组织名称，新增修改用
    const [orgDetail, setOrgDetail] = useState(null);
    const [typeId, setTypeId] = useState('');
    const [orgType, setOrgType] = useState(getCookie('hosType'));
    // const [hisTypeList, setHisTypeList] = useState([]);
    const [type, setType] = useState('');
    //从state中取出状态、类型列表
    const staticInfo = useSelector(state => {
        return state.staticInfo;
    });
    const { hisTypeList, statusList } = staticInfo;
    const tipText = {
        1: '确定要删除该组织？',
        2: '当前组织内可能包含子组织或其相关用户，删除后所包含信息将一并被删除',
        3: '确定要禁用该组织？',
        4: '当前组织内可能包含子组织或其相关用户，禁用后所包含信息将一并被禁用',
        5: '确定要重置该组织密码？',
        6: '您还有内容未保存，确定要退出？',
    };

    //获取表格数据
    function getTableData(param = {}) {
        post(api.getHospitalListInfo, param).then((res) => {
            if (res.data.code === 200) {
                let data = res.data.data
                let obj = {};
                if (orgType == 4) {
                    data.map((it, i) => {
                        delete it.children
                        it.depts.forEach(its => {
                            its.hospitalId = it.hospitalId
                        });
                        it.children = it.depts
                    });
                }
                setOrgId(data[0] ? data[0].hospitalId : '');
                setOrgName(data[0] ? data[0].hospitalName : '')
                setDataSource(data);
            }

        })
    }
    //启用/禁用
    function enable(flag, id, type) {
        const param = { HospitalId: id || operId, status: flag, type: type || typeId };
        xPost(api.disableHospital, param).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setVisible(false);
                message.success((flag ? '启用' : '禁用') + "成功");
            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    //重置密码
    function onResetPsd() {
        const param = { HospitalId: operId };
        xPost(api.resetPassword, param).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setVisible(false)
                message.success("重置成功");
            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    //删除
    function onDelete() {
        const param = { HospitalId: operId, type: typeId };
        xPost(api.deleteHospital, 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, flag) {
        setModalType(type);
        setOperId(id);
        setVisible(true);
        setTypeId(flag)
    }
    //弹窗确认事件
    function handleOk() {
        if ("1,2".indexOf(modalType) > -1) {
            onDelete();
        } else if ("3,4".indexOf(modalType) > -1) {
            enable(0);
        } else if (modalType === 5) {
            onResetPsd();
        }

    }
    //弹窗取消
    function handleCancel() {
        setVisible(false);
        setAddVisible(false);
    }
    //新增子组织弹窗
    function showAddOrg() {
        setAddVisible(true);
        setType(1)
        setOrgDetail({
            parentId: orgId,
            parentName: orgName,
            status: 1,
            type: orgType == 4 ? '科室' : ''
        })
    }
    function getOrgDetail(id, type) {
        xPost(api.getHospitalById, { HospitalId: id, type: type }).then((res) => {
            const { data, code } = res.data;
            if (code === 200) {
                structDetail(data);
                //setOrgDetail(res.data.data);
            } else {
                message.warning(res.data.message || '获取详情失败')
            }
        });
    }
    function structDetail(data) {
        const content = JSON.parse(JSON.stringify(data).replace(/getHospitalUserDTO/g, "addHospitalUserVO"));
        const menuData = content.getRoleDTO ? content.getRoleDTO.loginUserMenuResourceTree : [];
        content.confirmPsd = content.addHospitalUserVO.password
        let softwares = [], sids = [];
        for (let i = 0; i < menuData.length; i++) {
            const obj = pickCheckedTreeIds(menuData[i]);
            softwares.push(obj);
            sids.push(obj.id);
        }
        const fData = Object.assign({}, content, { softwares, sids });
        setOrgDetail(fData);
    }
    //修改子组织
    function editSubOrg(id, type, deptId) {
        if (orgType == 4) {
            getOrgDetail(deptId, type);
        } else {
            getOrgDetail(id, type);
        }
        setAddVisible(true);
        setType(2)
        setOperId(id);
    }
    //保存
    function addSubOrg(formData) {
        const param = formData;
        let url = api.addHospital
        const arr = formData.softwares.filter((it) => {
            if (Object.keys(it).length && it.softwareMenuIds && it.softwareMenuIds.length) {
                return it;
            }
        });
        if (orgType == 4) {
            param.type = 5
            param.addHospitalUserVO = {
                username: '122',
                password: '111'
            }
            param.softwares = [{
                id: 1,
                softwareMenuIds: ['1'],
                softwareResourceIds: ['2'],
            }]
        } else {
            formData.softwares = arr;
        }
        if (type == 2) {
            url = api.updateHospital
            param.id = operId
        }

        post(url, param).then((res) => {
            if (res.data.code === 200) {
                getTableData();
                setAddVisible(false);
                setOrgDetail(null)
                message.success("添加成功");

            } else {
                message.warning(res.data.message || '操作失败');
            }
        }).catch(() => {
            message.error("接口出错");
        });
    }
    function goBack() {
        setAddVisible(false);
        setOrgDetail(null)
        getTableData();
    }
    //表格渲染
    function RenderTable() {
        let columns
        if (orgType == 4) {
            columns = [
                {
                    title: '组织机构层级', key: 'type', render: (row) => {
                        if (row.children) {
                            return row.hospitalName
                        } else {
                            return row.deptName;
                        }
                    }
                },
                { title: '类型', width: 150, key: 'type', dataIndex: 'typeName' },
                {
                    title: '病区', key: 'type', render: (row) => {
                        if (row.children) {
                            return '-'
                        } else {
                            return row.regionName;
                        }
                    }
                },
                {
                    title: '状态', width: 120, key: 'status', render: (row) => {
                        if (row.children) {
                            return '-'
                        } else {
                            return (<span className={(row.status === '1') ? 'Enable' : 'Disable'}>{row.statusName}</span>);
                        }
                    }
                },
                { title: '创建时间', width: 240, dataIndex: 'gmtCreate', key: 'gmtCreate' },
                {
                    title: '操作', width: 240, key: 'operation', render: (row) => {
                        //console.log(21,row)
                        if (row.rootFlag) {
                            return '-'
                        }
                        const menu = (
                            <Menu>
                                <Menu.Item key="0" onClick={() => showModal(5, row.hospitalId)}>重置密码</Menu.Item>
                                <Menu.Item key="1" onClick={() => showModal((row.hasUserFlag || row.hasHospitalFlag ? 2 : 1), row.hospitalId, row.type)}>删除</Menu.Item>
                            </Menu>
                        );
                        return (<Space size="middle">
                            <a onClick={() => editSubOrg(row.hospitalId, row.type, row.deptId)}>修改</a>
                            {row.status === '1' ? (<a className='disable' onClick={() => showModal(row.hasUserFlag || row.hasHospitalFlag ? 4 : 3, row.hospitalId, row.type)}>禁用</a>) : (<a onClick={() => enable(1, row.hospitalId, row.type)}>启用</a>)}
                            <Dropdown overlay={menu} trigger={['click']}>
                                <a className="ant-dropdown-link">
                                    更多 <DownOutlined />
                                </a>
                            </Dropdown>
                        </Space>)
                    }
                },
            ];
            return (
                <Table
                    pagination={false}
                    scroll={{ y: 'calc(100vh - 320px)' }}
                    className="components-table-demo-nested"
                    rowKey={record => record.deptId}
                    columns={columns}
                    dataSource={dataSource}
                />
            )
        } else {
            columns = [
                { title: '组织机构层级', dataIndex: 'hospitalName', key: 'hospitalName' },
                {
                    title: '类型', width: 150, key: 'type', render: (row) => {
                        if (row.children) {
                            return '-'
                        } else {
                            return row.typeName;
                        }
                    }
                },
                {
                    title: '状态', width: 120, key: 'status', render: (row) => {
                        if (row.children) {
                            return '-'
                        } else {
                            return (<span className={(row.status === '1') ? 'Enable' : 'Disable'}>{row.statusName}</span>);
                        }
                    }
                },
                { title: '创建时间', width: 240, dataIndex: 'gmtCreate', key: 'gmtCreate' },
                {
                    title: '操作', width: 240, key: 'operation', render: (row) => {
                        //console.log(21,row)
                        if (row.rootFlag) {
                            return '-'
                        }
                        const menu = (
                            <Menu>
                                <Menu.Item key="0" onClick={() => showModal(5, row.hospitalId)}>重置密码</Menu.Item>
                                <Menu.Item key="1" onClick={() => showModal((row.hasUserFlag || row.hasHospitalFlag ? 2 : 1), row.hospitalId, row.type)}>删除</Menu.Item>
                            </Menu>
                        );
                        return (<Space size="middle">
                            <a onClick={() => editSubOrg(row.hospitalId, row.type)}>修改</a>
                            {row.status === '1' ? (<a className='disable' onClick={() => showModal(row.hasUserFlag || row.hasHospitalFlag ? 4 : 3, row.hospitalId, row.type)}>禁用</a>) : (<a onClick={() => enable(1, row.hospitalId, row.type)}>启用</a>)}
                            <Dropdown overlay={menu} trigger={['click']}>
                                <a className="ant-dropdown-link">
                                    更多 <DownOutlined />
                                </a>
                            </Dropdown>
                        </Space>)
                    }
                },
            ];
            return (
                <Table
                    pagination={false}
                    scroll={{ y: 'calc(100vh - 320px)' }}
                    className="components-table-demo-nested"
                    rowKey={record => record.hospitalId}
                    columns={columns}
                    dataSource={dataSource}
                />
            )
        }

    }
    //筛选项渲染
    const [form] = Form.useForm();
    const onFinish = (values: any) => {
        getTableData(values);
        console.log('筛选项:', values);
    };
    const onReset = () => {
        form.resetFields();
        getTableData();
    };
    if (addVisible && orgDetail) {
        return (
            <OrgContext.Provider value={{ type, save: addSubOrg, detail: orgDetail }}>
                <AddSubOrg back={goBack} />
            </OrgContext.Provider>
        )
    }
    return (
        <div className='wrapper'>
            <div className="filter-box">
                <Form form={form} name="control-hooks" onFinish={onFinish} initialValues={{ type:'',status: '' }}>
                    <Row gutter={24}>
                        <Col span={5} key={0}>
                            <Form.Item name="hospitalName" label="组织名称" getValueFromEvent={getValueFromEvent}>
                                <Input placeholder='组织名称' autoComplete="off" />
                            </Form.Item>
                        </Col>
                        <Col span={5} key={1}>
                            <Form.Item name="type" label={orgType == 4 ? '所属病区' : '类型'}>
                                <Select
                                    allowClear
                                >
                                    {hisTypeList.map((item) => {
                                        return (
                                            <Option value={item.name} key={item.name}>{item.val}</Option>
                                        )
                                    })}
                                </Select>
                            </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={() => showAddOrg()}>新增子组织</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 OrgManager;