import React from 'react';
import { Form, Button, Card, Tag, Select, Col, Row, Divider, Input, message, Modal, Table } from 'antd';
import { $http } from 'containers/config/https';
import './style/index.less';
import store from 'store';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';
const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;
var newArr = [];
var arr = []

let user;
const DoctorShiftModel = Form.create()(
    class extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                rowId: '', // 选中处方列行id
                visible1: false,//弹框显示状态
                visible: true,
                tableData: [],
                columns: [],
                rowIndex: -1,
                tagIndex: -1,
                selectedPat: props.shiftedPatient ? props.shiftedPatient : [],
                checked: true,
                shiftPatientData: [],
                searchPat: [],
                searchValue: '',
                attr: {},
                searchResult: [],/** 搜索结果集存放 */
                ENObj: {},
                CNObj: {},
                languageObj: {},
                columnsWidth: '',
                status: false,
            };
            user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
            this.searchShiftPatient = this.searchShiftPatient.bind();
           

            // 弹窗数据
            ModalData: []
        }


        componentWillReceiveProps(nextProps) {
            // 当修改选择的数据后刷新数据

            let data = JSON.parse(JSON.stringify(nextProps.data))
            if ((nextProps.data !== this.props.data) && (nextProps.openFlag)) {
                // console.log(nextProps.data)
                nextProps.changeOpen();
                this.setState({
                    ModalData: nextProps.data,
                    rowIndex: nextProps.rowIndex,
                    tagIndex: nextProps.tagIndex,
                    shiftPatientData: data.shiftPatient,
                    selectedPat: data.shiftedPatient,
                }, () => {
                    // console.log('...ModalData', this.state.ModalData)
                })
            }

        }
        componentDidMount() {
            // 数据异步请求，请求成功之后setState
            this.props.onRef(this);
            this.setState({
                showLoading: false
            })
            this.getTableColumns();
        }
         //获取列表头数据
         getTableColumns = () => {
            let data = {
                params: [{
                    reactCode: ['Succession'],
                    compontName: 'Succession',
                    type: 'C',
                }]
            }
            $http.post('urlS', this, {
                code: '01040073',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        let column = res.result.C;
                        if (user.language == 'EN') {
                            for (let i = 0; i < column.length; i++) {
                                column[i].title = column[i].enDescripts
                            }
                        }
                        this.setState({
                            columns: column,
                            columnsWidth: res.totalWidth,
                            ENObj: res.result.language.EN,
                            CNObj: res.result.language.CN,
                        }
                        )
                    }
                }
            });
        };
        // 显示弹框
        showModal = () => {
            this.setState({
                visible1: true,
            });
        }


        //点击患者
        onRowClick = (index, event) => {
            // console.log('onRowClick', index, event)
            let { selectedPat, shiftPatientData, attr } = this.state;
            let shiftData = [];
            let newArr = [];
            shiftPatientData.map((item) => {
                if (item.admID !== event.admID) {
                    shiftData.push(item);
                } else {
                    newArr.push(item);
                }

            });
            newArr = [...selectedPat, ...newArr];
            // this.state.selectedPat.push(event)
            event.index = newArr.length;
            let tagIndex = newArr.length;
            //newArr = this.unique5(newArr);
            //newArr.push(event);
            this.setState({ selectedPat: newArr, rowIndex: index, admID: event.admID, shiftPatientData: shiftData, attr: event, tagIndex: tagIndex, rowIndex: -1 });
        }

        /**
         * 搜索
         * 患者ID：patBaseInfo.patNo
         * 床号：admInfo.admBedCode
         * 姓名：patBaseInfo.patName
         */
        searchShiftPatient = (e) => {
            let searchPat = [];
            let searchResult = this.state.shiftPatientData.filter((obj, i) => {
                if (obj.patBaseInfo.patNo.includes(e.target.value) ||
                    obj.admInfo.admBedCode.includes(e.target.value) ||
                    obj.patBaseInfo.patName.includes(e.target.value)) {
                    searchPat.push(obj);
                }
            });
            if (!e.target.value) {
                searchPat = [];
            }
            this.setState({
                searchPat: searchPat,
                searchValue: e.target.value
            });
        }

        /** 去重*/
        unique5(arr) {
            var x = new Set(arr);
            return [...x];
        }

        handleChangeTab = (index, e) => {
            if(this.state.selectedPat.length>0){
                for(var i=0; i<this.state.selectedPat.length;i++){
                    if(i == index){
                        this.state.selectedPat[i].state = true;
                    }else{
                        this.state.selectedPat[i].state = false;
                    }
                }
               
            }
           
            this.props.form.resetFields(); //清空所有
            this.setState({
                tagIndex: index,
                rowIndex: -1,
            })
        };
        onColumnRef = (ref) => {
            this.columnRef = ref;
        }

        handleOk = () => {
            let { validateFields } = this.props.form;
            let that = this;
            validateFields({ force: true }, (err, params) => {
                if (err) {
                    return;
                }
                params.admID = that.state.admID;
                let { handleSubmit } = that.props;
                handleSubmit && handleSubmit(this.state.selectedPat)
                this.resetFields();
                that.props.submitSuccessionList(this.state.selectedPat, this.props.classIndex, this.state.shiftPatientData);/***添加交班人员信息 */
            });
        }
        // 重置表单
        resetFields() {
            // console.log("触发了")
            this.props.form.resetFields(); //清空所有
        }
        //点击右边
        onClose(item) {
            let delArr = [];
            let rightArr = [];
            this.state.selectedPat.map((v, index) => {
                if(item.admID== v.admID){
                    delArr.push(v);//删除
                } else {
                    rightArr.push(v);//除了删除剩余的
                }
            })
            let leftArr = [...this.state.shiftPatientData,...delArr];//左边追加
            this.setState({ shiftPatientData: leftArr, selectedPat: rightArr });
        }

        // 操作行
        onClickRowPublic = (record) => {
            return {
                // 单击行选中
                onClick: () => {
                    if (this.state.rowId === '') {
                        // 保存行数据以及ID
                        this.setState({ rowId: record.admID }, () => {
                        });
                    } else {
                        if (this.state.rowId !== record.admID) {
                            this.setState({ rowId: record.admID }, () => {
                            });
                        }
                    }
                }
            }
        }

        // 选中行操作
        setRowClassNamePublic = (record) => {
            return record.admID === this.state.rowId ? 'clickRowStyle' : '';
        }
        onSituationChange = (flag, e) => {
            let { selectedPat } = this.state;
            selectedPat[this.state.tagIndex][flag] = e.target.value;
            this.setState({ selectedPat })
        }
        render() {
            var language = user.language
            var languageObj = {}
            if (language == "EN") {
                languageObj = this.state.ENObj
            } else {
                languageObj = this.state.CNObj
            }
            let { columns, columnsWidth } = this.state;
            const { getFieldDecorator } = this.props.form;
            const { data = {} } = this.props;
            let { rowIndex, tagIndex } = this.state
            let { shiftPatient } = this.state.shiftPatientData || [];
            if (tagIndex != -1) {
                shiftPatient = this.state.selectedPat;
                rowIndex = tagIndex;
            }
            const clickPat = shiftPatient && shiftPatient[rowIndex];
            const patBaseInfo = shiftPatient && shiftPatient[rowIndex] && shiftPatient[rowIndex].patBaseInfo
            const admInfo = shiftPatient && shiftPatient[rowIndex] && shiftPatient[rowIndex].admInfo
            const temperature = shiftPatient && shiftPatient[rowIndex] && shiftPatient[rowIndex].temperature
            const cardContent = { temperature, admInfo, patBaseInfo }
            const shiftPatType = shiftPatient && shiftPatient[rowIndex] && shiftPatient[rowIndex].shiftPatType
            // console.log(shiftPatType,"----->", shiftPatType)
            return (
                <Modal
                    width='63%'
                    title="交班备注"
                    visible={this.props.visible}
                    onOk={this.handleOk}
                    onCancel={this.props.handleOk}

                >
                    <div className="operations">
                        <div id="left">
                            <Row>
                                <Col span={24}>
                                    <Input onChange={this.searchShiftPatient} value={this.state.searchValue} placeholder="姓名/病人ID/床号(回车查询)" style={{ width: '410px', marginRight: '20px' }} />
                                    {/* <Button onClick={this.handleQuery}>查询</Button> */}
                                </Col>
                            </Row>
                            <br />
                            <Row>
                                <Col span={12}>
                                <ColumnAuthoritysModel
                                    clientWidth='800px'
                                    compontName="Succession"
                                    configType="C"
                                    onRef={this.onColumnRef}
                                    reloadData={this.getTableColumns}
                                />
                                    <Table
                                        onHeaderRow={column => {
                                            return {
                                                onDoubleClick: () => {
                                                    this.columnRef.onOpenModel();
                                                },
                                            };
                                        }}
                                        style={{ width: '417px',height: '640px', maxHeight: '640px', overflow: 'scroll'}}
                                        dataSource={this.state.searchValue != "" ? this.state.searchPat : this.state.shiftPatientData}
                                        columns={columns.length > 0 ? columns : this.columns}
                                        pagination={false}
                                        onClickRowPublic={this.onClickRowPublic}
                                        setRowClassNamePublic={this.setRowClassNamePublic}
                                        onRow={(record, index) => {
                                            return {
                                                // 点击
                                                onClick: this.onRowClick.bind(this, index, record)
                                            };
                                        }}
                                        bordered
                                    />
                                </Col>
                            </Row>
                        </div>

                        <div id="opter"  style={{height: '650px', maxHeight: '650px', overflowY: 'scroll'}}>
                            <div>
                                {
                                    this.state.selectedPat && this.state.selectedPat.length > 0 && this.state.selectedPat.map((item, index) => {
                                        // console.dir(item)
                                        // console.dir(shiftPatient[item])
                                        return (
                                            <Tag
                                                onClick={this.handleChangeTab.bind(this, index)}
                                                key={index}
                                                style={{color:item.state ? '#FFF' :'#108ee9',padding:'2px 2px ', marginLeft: '10px', marginTop: '5px',backgroundColor: item.state ? '#108ee9' :'#FFF' }}
                                                visible={true}
                                                closable
                                                onClose={this.onClose.bind(this, item)}
                                            >
                                                {/* {shiftPatient && shiftPatient[item] ? (shiftPatient[item].patBaseInfo.patName + '' + shiftPatient[item].admInfo.admBedCode) : ''} */}
                                                {item.patBaseInfo.patName + '' + item.admInfo.admBedCode}
                                            </Tag>
                                        )
                                    })
                                }

                                <br />

                            </div >

                            <div className="card-right" style={{ width: '679px', marginTop: '20px' }}>
                                <Form onSubmit={this.handleOk}>
                                    <FormItem label="">
                                        {getFieldDecorator('huaxiangqingnzhe', {
                                            initialValue: cardContent,
                                            rules: [{ required: false, message: '请填写备注' }]
                                        })(
                                            <Card style={{ width: '100%', height: '168px', marginBottom: '10px', padding: '0 5px' }} >
                                                <div className="desc">
                                                    <span>{patBaseInfo && patBaseInfo.patName} {admInfo && admInfo.admBedCode} </span>
                                                    <span>{patBaseInfo && patBaseInfo.patSexDesc}</span>
                                                    <span>{patBaseInfo && patBaseInfo.patAge}</span>
                                                    <span>{patBaseInfo && patBaseInfo.patNo}</span>
                                                    {shiftPatType && shiftPatType.map(it => <Tag color="#f50">{it}</Tag>)}
                                                </div>
                                                <div className="desc" id="lineEllipsis">{languageObj.SuccessionadmDiag!= null ? languageObj.SuccessionadmDiag.descripts : ""}：{admInfo && admInfo.admDiag}</div>
                                                <div className="desc">
                                                    <div className="detiale">
                                                        <div className="ietm">
                                                            <span>{languageObj.SuccessionSBP!= null ? languageObj.SuccessionSBP.descripts : ""} {temperature && temperature.SBP} </span>
                                                            <Divider type="vertical" />
                                                            <span>{languageObj.SuccessionDBP!= null ? languageObj.SuccessionDBP.descripts : ""} {temperature && temperature.DBP}</span>
                                                            <Divider type="vertical" />
                                                            <span>{languageObj.SuccessionSPO2!= null ? languageObj.SuccessionSPO2.descripts : ""}  {temperature && temperature.SpO2}</span>
                                                        </div>
                                                        <div className="ietm">
                                                            <span>{languageObj.Successionbreathe!= null ? languageObj.Successionbreathe.descripts : ""} {temperature && temperature.breathe} </span>
                                                            <Divider type="vertical" />
                                                            <span>{languageObj.Successiontemperature!= null ? languageObj.Successiontemperature.descripts : ""} {temperature && temperature.temperature}</span>
                                                            <Divider type="vertical" />
                                                            <span>{languageObj.SuccessionheartRate!= null ? languageObj.SuccessionheartRate.descripts : ""} {temperature && temperature.heartRate}</span>
                                                            <Divider type="vertical" />
                                                            <span>{languageObj.Successionpulse!= null ? languageObj.Successionpulse.descripts : ""} {temperature && temperature.pulse}</span>
                                                        </div>
                                                    </div>
                                                    <div>
                                                        <div>{languageObj.SuccessionadmDocDesc!= null ? languageObj.SuccessionadmDocDesc.descripts : ""}：{admInfo && admInfo.admDocDesc}</div>
                                                        <div>{languageObj.SuccessionadmNurDesc!= null ? languageObj.SuccessionadmNurDesc.descripts : ""}：{admInfo && admInfo.admNurDesc}</div>
                                                    </div>
                                                </div>

                                            </Card>
                                        )}
                                    </FormItem>

                                    <Row style={{ marginTop: '-10px' }}>
                                        <Col span={24}>
                                            <FormItem label={languageObj.SuccessionPatientStatus!= null ? languageObj.SuccessionPatientStatus.descripts : ""}>
                                                {getFieldDecorator('shiftPatSituation', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatSituation : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(

                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatSituation")} />

                                                )}
                                            </FormItem>
                                            <FormItem label={languageObj.Successionbackground!= null ? languageObj.Successionbackground.descripts : ""}>
                                                {getFieldDecorator('shiftPatBackground', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatBackground : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(

                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatBackground")} />

                                                )}
                                            </FormItem>
                                            <FormItem label={languageObj.Successionassexam!= null ? languageObj.Successionassexam.descripts : ""}>
                                                {getFieldDecorator('shiftPatAssessment', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatAssessment : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(

                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatAssessment")} />

                                                )}
                                            </FormItem>
                                            <FormItem label={languageObj.Successionassexament!= null ? languageObj.Successionassexament.descripts : ""}>
                                                {getFieldDecorator('shiftPatAssexam', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatAssexam : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(

                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatAssexam")} />

                                                )}
                                            </FormItem>

                                            <FormItem label={languageObj.Successiontreatment!= null ? languageObj.Successiontreatment.descripts : ""}>
                                                {getFieldDecorator('shiftPatTreat', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatTreat : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(
                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatTreat")} />

                                                )}
                                            </FormItem>
                                            
                                            <FormItem label={languageObj.Successionproposal!= null ? languageObj.Successionproposal.descripts : ""}>
                                                {getFieldDecorator('shiftPatRecommendation', {
                                                    initialValue: clickPat != undefined ? clickPat.shiftPatRecommendation : '',
                                                    rules: [{ required: false, message: '请填写' }]
                                                })(
                                                    <TextArea rows={2} onChange={this.onSituationChange.bind(this, "shiftPatRecommendation")} />
                                                )}
                                            </FormItem>
                                        </Col>
                                    </Row>
                                </Form>




                            </div>

                        </div>
                    </div>

                </Modal>
            )
        }

    }
)
export default DoctorShiftModel;
