import React, { Component } from 'react';
import { message } from 'antd';
import { $http } from '../../../containers/config/https';
import './CSS/rightmenu.less';
import ModificationPatientInfo from '../../registercard/component/ModificationPatientInfo';
import ShowMedicalRecordModal from '../../workstation/component/ShowMedicalRecordModal';

let userData = {};

class RightMenu extends Component {
    constructor({ history }) {
        super();
        userData = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {}
        this.history = history;
        this.state = {
            visible: false,
            menuList: [],
            filterMenuList: [],
            isShowMedicalRecordModal: false,
            historyAdmID: '',
            preSeparationBedFlag: '', // 预分床标志
        };
    }

    componentDidMount() {
        this.props.onRef(this);
        this.getMenuList();
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.preSeparationBedFlag !== prevState.preSeparationBedFlag) {
            return {
                preSeparationBedFlag: nextProps.preSeparationBedFlag
            }
        }
        return null
    }

    componentDidUpdate(nextProps, prevState) {
        if (prevState.preSeparationBedFlag !== this.state.preSeparationBedFlag) {
            this.handleFilterMenuList();
        }
    }

    componentWillUnmount() {
        this.setState = (state, callback) => { return; }
    }

    openWindowBySubTab = (item) => {
        if (item.code == 'ModifyPatInfo') { //  修改患者信息
            let data = {
                params: [
                    JSON.parse(sessionStorage.patientData)
                ]
            }
            $http.post('urlDeault', this, {
                code: '03050274',
                data: data,
                success: (res) => {
                    if (+res.errorCode === 0) {
                        this.modifyPatInfoChild.showModifDom(res.result);
                    }
                }
            })
            return;
        }
        if (item.code == 'medicalRecord') { // 查看病历
            this.setState({ isShowMedicalRecordModal: true })
            return;
        }
        if (item.code == 'presplittingBed') { // 分配临时床位 - 预分床
            this.props.handleSeparateBeds && this.props.handleSeparateBeds();
            return;
        }
        if (item?.code === 'wristbandPrint') { // 打印腕带
            this.props.handlePrintBedCard && this.props.handlePrintBedCard('wristbandPrint');
            return;
        }
        if ((item.value == '') || (item.value == undefined)) {
            message.warning('未维护跳转组件!');
        } else {
            this.props.history.push(item.code);
        }
    }

    /**
     * 获取菜单
     */
    getMenuList = () => {
        let that = this;
        let data = {
            params: [{
                type: userData.groupDesc && userData.groupDesc.indexOf('护士') < 0 ? 'BedMenu' : 'BedMenuNur'
            }]
        }
        $http.post('urlDeault', this, {
            code: '01010013',
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    that.setState({
                        menuList: res?.data || [],
                    }, () => {
                        this.handleFilterMenuList();
                    })
                }
            }
        })
    }

    _handleContextMenu = (event) => {
        event.preventDefault();
        let patientData = window.sessionStorage.patientData ? JSON.parse(window.sessionStorage.patientData) : {};
        if (patientData.admID == '') {
            return;
        }
        this.setState({ visible: true });
        const clickX = event.clientX;
        const clickY = event.clientY;
        const screenW = window.innerWidth;
        const screenH = window.innerHeight;
        const rootW = this.root.offsetWidth;
        const rootH = this.root.offsetHeight;

        // right为true，说明鼠标点击的位置到浏览器的右边界的宽度可以放contextmenu。
        // 否则，菜单放到左边。
        // top和bottom，同理。
        const right = (screenW - clickX) > rootW;
        const left = !right;
        const top = (screenH - clickY) > rootH;
        const bottom = !top;

        if (right) {
            this.root.style.left = `${clickX + 5}px`;
        }

        if (left) {
            this.root.style.left = `${clickX - rootW - 5}px`;
        }

        if (top) {
            this.root.style.top = `${clickY + 5}px`;
        }

        if (bottom) {
            this.root.style.top = `${clickY - rootH - 5}px`;
        }
    }

    _handleClick = (event) => {
        const { visible } = this.state;
        const wasOutside = !(event.target.contains === this.root);
        if (wasOutside && visible) this.setState({ visible: false, });
    }

    _handleScroll = () => {
        const { visible } = this.state;

        if (visible) this.setState({ visible: false, });
    }

    onModifyPatInfoRef = (ref) => {
        this.modifyPatInfoChild = ref
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

    // 过滤右键菜单数据
    handleFilterMenuList = () => {
        const { menuList, preSeparationBedFlag } = this.state;
        const filterMenuList = menuList && menuList.filter(item => item.code === 'presplittingBed' ? preSeparationBedFlag === 'wait' : true);
        this.setState({ filterMenuList });
    }

    render() {
        const { visible, isShowMedicalRecordModal, historyAdmID, filterMenuList } = this.state;
        return (
            <div>
                {visible || null ?
                    <div ref={ref => { this.root = ref }} className="contextMenu">
                        {filterMenuList.map((item, index) => {
                            return <div key={index} className="contextMenu--option" onClick={this.openWindowBySubTab.bind(this, item)}>{item.descripts}</div>
                        })}
                        {/* <div className="contextMenu--option" onClick={this.openWindowBySubTab}>医嘱录入</div>
                        <div className="contextMenu--option">诊断录入</div>
                        <div className="contextMenu--option">病历书写</div>
                        <div className="contextMenu--option">检查结果</div> */}
                    </div>
                    : ''
                }
                {/* 修改病人信息 */}
                <ModificationPatientInfo
                    OnChildref={this.onModifyPatInfoRef}
                    position="fixed"
                />
                {/* 查看病历 */}
                {isShowMedicalRecordModal ? <ShowMedicalRecordModal
                    admTypeCode="I"
                    isShow={isShowMedicalRecordModal}
                    historyAdmID={historyAdmID}
                    onHide={this.hideModal.bind(this, 'isShowMedicalRecordModal')}
                /> : ''}
            </div>
        )
    }
};

export default RightMenu;
