//医生交班切换
import React, { Fragment, PureComponent } from 'react';
import { Tabs, Select, Card, Col, Row, Button, Tag, Divider, Table, message } from 'antd';
import { $http } from 'containers/config/https';
import store from 'store';
import moment from 'moment';
const { Option } = Select;
import { Util } from 'tools/index';
import DoctorShiftTabsModel from './DoctorShiftTabsModel'
import './style/style.less';
import { $loopPrint } from 'pages/lodop/Common/Print';

let user;
const { TabPane } = Tabs;
const columns = [
    {
        title: '原患者总数',
        dataIndex: 'shiftPatTotalOld',
        key: '1',
    },
    {
        title: '现患者总数',
        dataIndex: 'shiftPatTotal',
        key: '2',
    },
    {
        title: '出院',
        dataIndex: 'shiftDischarge',
        key: '3',
    },
    {
        title: '入院',
        dataIndex: 'shiftInhosp',
        key: '4',
    },
    {
        title: '危重',
        dataIndex: 'shiftCritically',
        key: '5',
    },
    {
        title: '死亡',
        dataIndex: 'shiftDeath',
        key: '6',
    },
    {
        title: '手术',
        dataIndex: 'shiftOperation',
        key: '7',
    },
    {
        title: '请假外出',
        dataIndex: 'shiftLeave',
        key: '8',
    },
    {
        title: '转出',
        dataIndex: 'shiftTransOut',
        key: '9',
    },
    {
        title: '转入',
        dataIndex: 'shiftTransIn',
        key: '10',
    },
    {
        title: '特级护理',
        dataIndex: 'shiftNurseLevel',
        key: '11',
    },
    {
        title: '二级护理',
        dataIndex: '',
        key: '12',
    },
];
var newArr = []
class DoctorShiftTabs extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            column: [],
            columns: [],
            tableData: [],
            DataList: [],
            shiftPatient: [],//卡片的基本数据
            LeftiData: {},
            rowIndex: '-1',
            tagIndex: '-1',
            index: '-1',
            openFlag: false,
            classIndex: 0,
            selectData: [],//下拉框数据
            selectID: '',
        }
        user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
        this.openModelByValue = this.openModelByValue.bind(this);
        this.deleteSuccessionByadmId = this.deleteSuccessionByadmId.bind(this);
        this.submitSuccessionList = this.submitSuccessionList.bind(this);

    }
    componentDidMount() {
        this.loadColumn();
        this.handleList();
        this.getSelectData();
    }
    callback = (key) => {
        // console.log(key);
    }
    // 获取下拉框数据
    getSelectData() {
        let data = {
            params: [
                {
                    locID: user.locID,
                    locDocFlag: '1',
                }
            ]
        }
        $http.post('urlS', this, {
            code: "01040022",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        selectData: res.locDoc,
                    })
                }
            }

        })
    }
    onChangeselectID = (index, value) => {
        // console.log(index, "=======>",value);
        let DataList = [...this.state.DataList]
        DataList[index].shiftTakeUser = value
        this.setState({ DataList });
        // console.log('DataList',DataList)
    }
    //查询列头数据
    loadColumn = () => {
        let data = {
            params: [{
                hospID: user.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04070003",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    let resData = res.result.Data;
                    this.setState({
                        column: resData,
                        tableWidth: res.totalWidth
                    }
                        , () => {
                            this.handleQuery();
                        })
                }
            }
        })
    }
    //查询表头数据
    handleQuery = () => {
        let data = {
            params: [{
                hospID: user.hospID
            }]
        };
        $http.post('urlS', this, {
            code: '04070005',
            data: data,
            success: (res) => {
                if (res.errorCode === "0") {
                    this.setState({
                        tableData: res.result,
                    });
                } else {
                    this.setState({
                        tableData: []
                    })
                }
            }
        })
    }

    closeModal() {
        this.setState({
            visible: false
        })
    }
    //添加
    handleSubmit = (val) => {
        const { DataList } = this.state;
        DataList[this.state.index] = val;
        this.setState({
            DataList: DataList
        }, () => {
            this.closeModal()
        })

    }
    /**删除交班人员 */
    deleteSuccessionByadmId = (admId) => {
        this.setState({ DataList: this.state.DataList.filter((v) => v.admID !== admId) })
    }

    //保存交班
    handleAdd = (val, desc) => {
        const { DataList } = this.state;
        const { shiftReportID, shiftTypeID, shiftPatTotalOld, shiftPatTotal, shiftNurseLevel, shiftLeave, shiftInhosp, shiftDischarge, shiftTransIn, shiftTransOut, shiftDeath, shiftCritically, shiftSeriously, shiftOperation, shiftShiftUser, shiftTakeUser } = DataList.length > 0 && desc;
        var newData = desc.shiftedPatient;
        // console.log("newData======",newData)        
        var temp = []
        for (var i = 0; i < newData.length; i++) {
            // if(newData[i].updateID){
            let shiftPatType = newData[i]['shiftPatType'];
            // let tempArr = [];
            // for (let j = 0; j < shiftPatType.length; j++) {
            //     tempArr.push(shiftPatType[j]['code'])
            // }
            // console.log('tempArr',tempArr)
            temp.push({
                shiftPatID: newData[i].shiftPatID,
                admID: newData[i].admID,
                admHBBedID: newData[i].admHBBedID,
                shiftPatTCMDiagnosis: newData[i].shiftPatTCMDiagnosis,
                shiftPatWesternDiagnosis: newData[i].shiftPatWesternDiagnosis,
                shiftPatType: shiftPatType,
                shiftPatSituation: newData[i].shiftPatSituation,
                shiftPatBackground: newData[i].shiftPatBackground,
                shiftPatAssessment: newData[i].shiftPatAssessment,
                shiftPatRecommendation: newData[i].shiftPatRecommendation,
                shiftPatAssexam: newData[i].shiftPatAssexam,
                shiftPatTreat: newData[i].shiftPatTreat
            })
            // }
        }
        let removeData = desc.shiftPatient;
        let removeArr = []
        for (var i = 0; i < removeData.length; i++) {
            removeArr.push({
                shiftPatID: removeData[i].shiftPatID
            })
        }
        if ((shiftTakeUser == "") || (shiftTakeUser === undefined)) {
            message.error('请输入接班人')
            return;
        }
        let data = {
            params: [{
                shiftReportID: shiftReportID ? shiftReportID : '',
                locID: user.locID,
                shiftDate: moment().format("YYYY-MM-DD"),
                shiftTime: moment().format("HH:mm:ss"),
                shiftTypeID: shiftTypeID,
                shiftPatTotalOld: (shiftPatTotalOld !== '') ? shiftPatTotalOld : "",
                shiftPatTotal: shiftPatTotal ? shiftPatTotal : "",
                shiftNurseLevel: (shiftNurseLevel !== '') ? shiftNurseLevel : "",
                shiftLeave: (shiftLeave !== '') ? shiftLeave : "",
                shiftInhosp: shiftInhosp ? shiftInhosp : "",
                shiftDischarge: (shiftDischarge !== '') ? shiftDischarge : "",
                shiftTransIn: (shiftTransIn !== '') ? shiftTransIn : "",
                shiftTransOut: (shiftTransOut !== '') ? shiftTransOut : "",
                shiftDeath: (shiftDeath !== '') ? shiftDeath : "",
                shiftCritically: (shiftCritically !== '') ? shiftCritically : "",
                shiftSeriously: (shiftSeriously !== '') ? shiftSeriously : "",
                shiftOperation: (shiftOperation !== '') ? shiftOperation : "",
                shiftShiftUser: shiftShiftUser ? shiftShiftUser : "",
                shiftTakeUser: shiftTakeUser,
                shiftNurContent: desc.shiftNurContent,
                shiftPatient: temp,
                removePatient: removeArr
            }
            ]
        }
        $http.post('urlS', this, {
            code: '04070007',
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    message.success('保存成功');
                    this.handleList()
                }
            }
        })
    }
    //查询
    handleList = () => {
        let data = {
            params: [{
                userType: "D"
            }]
        };
        $http.post('urlS', this, {
            code: '04070006',
            data: data,
            success: (res) => {
                if (res.errorCode === "0") {

                    this.setState({
                        DataList: res.result.Data.filter((v) => !Util.isEmpty(v)),
                    });
                } else {
                    this.setState({
                        DataList: []
                    })
                }
            }
        })
    }
    custom = (list = []) => {
        return columns.map(item => {
            return (
                <div className="wrapter">
                    <span className="title">{item.title}</span>
                    <span className="key">{list[item.dataIndex]}</span>
                </div>
            );
        });
    };

    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.onRefChild = ref
    }

    customCard = (data = [], index, val) => {
        const { DataList } = this.state;
        let objData = val.shiftNurContent;
        return data.length > 0 && data.map((item, k) => {
            return (
                <div className="cardWarp">
                    <div className="title">{item.descripts}</div>
                    <div className="key">{objData && objData[item.code] && objData[item.code].length > 0 && val.shiftNurContent[item.code].map((it, k) => {
                        if (!Util.isEmpty(it)) {
                            return (<span key={k}>{it.patName + " " + it.admBedCode}</span>)
                        }
                    })}</div>
                </div>
            );
        });
    };

    printShiftReport = (shiftReportID) => {
        let data = {
            params: [{
                shiftReportID
            }]
        }
        $http.post('urlS', this, {
            code: "04070009",
            data: data,
            success: function (res) {
                // console.log(res)
                if (+res.errorCode === 0) {
                    $loopPrint('', res.result);
                } else {
                    message.error(res.errorMessage);
                }
            }
        })
    }

    openModelByValue = (listData, patIndex, index, e) => {
        // console.log(listData, patIndex, e);
        this.setState({ LeftiData: listData, tagIndex: patIndex, classIndex: index, openFlag: true, visible: true });
    }

    leftContent = (tableData, list, index) => {
        const nurContentInfo = list && list.nurContentInfo
        const { DataList } = this.state;
        const { currentShiftInterval, nextShiftInterval, shiftShiftUserDesc, shiftTakeUser, shiftDateTime } = list
        const desc = DataList.length > 0 && DataList[index];
        const shiftedPatient = desc && desc.shiftedPatient
        const shiftTakeUser2 = desc && desc.shiftTakeUser
        const { shiftReportID } = desc
        return (
            <Card
                title={(
                    <div>
                        <div style={{ marginTop: '-14px' }}>交班：{shiftShiftUserDesc}  {currentShiftInterval}  | 接班： <Select allowClear value={shiftTakeUser2 ? shiftTakeUser2 : ''} onChange={this.onChangeselectID.bind(this, index)} style={{ width: '120px' }} placeholder="请输入接班人">
                            {
                                this.state.selectData && this.state.selectData.map(
                                    (item) => {
                                        return <Option key={item.id} value={item.id} title={item.descripts + "^" + item.descriptsSPCode.toLowerCase()}>{item.descripts}</Option>
                                    }
                                )

                            }
                        </Select> {nextShiftInterval}</div>
                        <div> <span style={{ color: '#CCCCCC' }}>交班时间：{shiftDateTime}</span> <div style={{ position: 'absolute', top: '30px', right: '30px' }}>
                             <Button type="primary" shape="round" onClick={() => { this.handleAdd(shiftedPatient, desc, list) }}>交班</Button>
                             {desc.shiftReportID ? <Button type="primary" shape="round" onClick={() => this.printShiftReport(desc.shiftReportID)}>打印</Button> : ''}
                        </div></div>
                    </div>)}
                bordered={false}
                // extra={
                //     <div>
                //         <Button type="primary" shape="round" onClick={() => { this.handleAdd(shiftedPatient, desc, list) }}>交班</Button>
                //         {desc.shiftReportID ? <Button type="primary" shape="round" onClick={() => this.printShiftReport(desc.shiftReportID)}>打印</Button> : ''}
                //     </div>
                // }

            >
                <div className="custom">
                    {this.custom(list)}
                    <div className="line" />
                    {/* {this.customCard(tableData, index, list)} */}
                    <div style={{display:'flex',width:'100%',justifyContent:'space-between'}}>
                        <div>
                            交班备注
                        </div>
                        <div>
                        <Button  onClick={() => { this.setState({ LeftiData: list, visible: true, openFlag: true, classIndex: index }) }} style={{color: '#2db7f5'}}>添加</Button>
                        </div>
                    </div>
                    <div className="line" />
                    {/* <p style={{ marginLeft: '15px', marginTop: '15px' }}>交班备注</p>
                    <Button onClick={() => { this.setState({ LeftiData: list, visible: true, openFlag: true, classIndex: index }) }} style={{ marginLeft: '92%', color: '#2db7f5', marginTop: '15px' }}>添加</Button> */}
                    <Row style={{ width: '100%', height: '643px', overflowY: 'auto' }}>
                        {shiftedPatient && shiftedPatient.map((item, indexPat) => {
                            const { patBaseInfo, temperature } = item
                            const { admInfo } = item;
                            if (item.temperature) {
                                return (
                                    <Card className='mancard' style={{ width: '100%', marginBottom: '10px' }} disabled={shiftReportID} key={item.id} onDoubleClick={this.openModelByValue.bind(this, list, indexPat, index)}>
                                        <div className="desc">
                                            <span>{patBaseInfo.patName}{admInfo.admBedCode}</span>
                                            <span className='name'>{patBaseInfo.patSexDesc}{patBaseInfo.patAge}</span>
                                            <span className='idnum'>{patBaseInfo.patNo}</span>
                                            <span className='duty'>责医:</span>
                                            <span className='dcName'>{admInfo.admDocDesc}</span>
                                            <span className='hehu'>责护:</span>
                                            <span className='dname'>{admInfo.admNurDesc}</span>
                                            {item.shiftPatType.map(it => {
                                                return <Tag color="#f50">{it}</Tag>
                                            })}
                                            {/* <Tag color="#f50">手术</Tag><Tag color="red">禁食</Tag> */}
                                        </div>
                                        <div className="desc">诊断：{admInfo.admDiag}</div>
                                        <div className="desc">
                                            <div className="detiale">
                                                <div className="ietm">
                                                    <span>收缩压 {temperature && temperature.SBP}</span>
                                                    <Divider type="vertical" />
                                                    <span>舒张压 {temperature && temperature.DBP}</span>
                                                    <Divider type="vertical" /><span>SPO2 {temperature && temperature.SpO2}</span>
                                                    <Divider type="vertical" />
                                                    <span>呼吸{temperature && temperature.breathe}</span>
                                                    <Divider type="vertical" />
                                                    <span>体温 {temperature && temperature.temperature}</span>
                                                    <Divider type="vertical" />
                                                    <span>心率 {temperature && temperature.heartRate}</span>
                                                    <Divider type="vertical" />
                                                    <span>脉搏 {temperature && temperature.pulse}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div className="temp">
                                            <div className="desc">主诉：{item.shiftPatSituation}</div>
                                            <div className="desc">主要病史：{item.shiftPatBackground}</div>
                                            <div className="desc">主要查体：{item.shiftPatAssessment}</div>
                                            <div className="desc">主要辅助检查：{item.shiftPatRecommendation}</div>
                                            <div className="desc">治疗：{item.shiftPatTreat}</div>
                                            <div className="desc">交班要点：{item.shiftPatRecommendation}</div>
                                        </div>

                                    </Card>
                                )
                            } else {
                                return ''
                            }
                        })}
                    </Row>
                </div>
            </Card>
        );
    };


    rightContent = (tableData, list = {}) => {
        const nurContentInfo = list && list.nurContentInfo
        const { DataList } = this.state;
        const { currentShiftInterval, nextShiftInterval, shiftShiftUserDesc, shiftTakeUserDesc, shiftDateTime } = list
        const desc = DataList.length > 0 && DataList[2];
        const shiftPatient = desc && desc.shiftPatient
        const { shiftReportID } = desc
        return (
            <Card
                title={<div>
                    <div>交班：{shiftShiftUserDesc}  {currentShiftInterval}  | 接班：{nextShiftInterval} {shiftTakeUserDesc}</div>
                </div>}
                bordered={false}
                extra={<Button type={shiftReportID ? "danger" : 'primary'} disabled={shiftReportID} shape="round" onClick={() => { this.handleAdd(shiftedPatient, desc, list) }}>{shiftReportID ? '已交班' : '交班'}</Button>}
            >
                <div style={{ color: 'red', textAlign: 'center', fontSize: '15px' }}><div>未到交班时间!</div></div>
            </Card>
        );
    };
    changeOpen = () => {
        this.setState({
            openFlag: false,
        })
    }
    /**
     * 添加交班人员信息
     */
    submitSuccessionList = (dataList, classIndex, shiftPatientData) => {
        let tempDataList = this.state.DataList;
        tempDataList[classIndex].shiftedPatient = dataList;
        tempDataList[classIndex].shiftPatient = shiftPatientData;
        this.setState({
            DataList: tempDataList,
            visible: false,
            LeftiData: {},
        });
    }
    render() {
        const { tableData, DataList, shiftPatient } = this.state
        // console.log(this.state.DataList,'11111111111')
        return (
            <Fragment>

                <Tabs defaultActiveKey="1" onChange={this.callback}>
                    {this.state.DataList.length > 0 && this.state.DataList.map((item, index) => {
                        return <TabPane tab={item.shiftTypeDesc} key={index}>
                            {/* <Row gutter={16}>
                                    <Col span={24}>{this.leftContent(tableData)}</Col>
                                </Row> */}
                            {!Util.isEmpty(item) && (<Col span={24}>{this.leftContent(tableData, item, index)}</Col>)}
                        </TabPane>
                    })}
                </Tabs>


                {/* <Row gutter={16}>
                    {this.state.DataList.map((item, index) => {
                        return (Util.isEmpty(item) ? (
                            <Col span={24} key={index}>{this.rightContent(tableData, item)}</Col>
                        ) : (<Col span={24}>{this.leftContent(tableData, item, index)}</Col>))
                    })}
                </Row> */}
                <DoctorShiftTabsModel
                    visible={this.state.visible}
                    classIndex={this.state.classIndex}
                    submitSuccessionList={this.submitSuccessionList}
                    handthis={this}
                    data={this.state.LeftiData}
                    // onClose={this.onClose.bind(this)}
                    handleOk={() => this.setState({ visible: false })}
                    handleSubmit={this.handleSubmit.bind(this)}
                    deleteSuccessionByadmId={this.deleteSuccessionByadmId}
                    rowIndex={this.state.rowIndex}
                    tagIndex={this.state.tagIndex}
                    onRef={this.onRef}
                    openFlag={this.state.openFlag}
                    changeOpen={this.changeOpen}
                />
            </Fragment>
        );
    }
}

export default DoctorShiftTabs;

