/*
* 待处理咨询
* */

import React, { Component } from 'react';
import {
    Input, Form, Select, Modal, Button, Progress, Upload, message, Divider, Table,
    Card, Row, Col, DatePicker, Popconfirm, Checkbox, Radio
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import RangeDatePicker from 'components/rangePicker/index';
import ShowHealthChartModal from './ShowHealthChartModal';
import ShowCommonInformationPage from './ShowCommonInformationPage';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const Search = Input.Search;
const FormItem = Form.Item;
const { TextArea } = Input;
var timer=null;

class ShowConsultationModal extends Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            leftData: [],
            rightData: [],
            userData: userData,
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.loadData()
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        // this.loadChatMessage()
        this.initData()

    }

    initData() {
        this.leftColumns = [
            {
                title: '内容',
                dataIndex: 'title',
                width: 200,
                align: 'left',
                render: (text, data) => {
                    return <div>
                        <div>
                            <span>{data.patName || '--'}</span><Divider type="vertical" />
                            <span>{data.dateTime}</span>
                        </div>
                        <div style={{ marginTop: 5 }}>
                            <span>{data.consultText || '--'}</span>
                        </div>
                    </div>
                }
            }
        ]
    }

    loadData() {
        var params = {
            params: [{
                doctorID: this.state.userData.userID,
                hospID: this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070069",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        patID: !Util.isEmpty(res.result.data) ? res.result.data[0].patID : '',
                        recordIndex: !Util.isEmpty(res.result.data) ? res.result.data[0].index : '',
                        signRecordID: !Util.isEmpty(res.result.data) ? res.result.data[0].signRecordID : '',
                    }, () => {
                        this.loadChatMessage()
                        this.startTime()
                    })
                }
            }
        });
    }

    startTime=(e)=>{
        timer= setInterval(()=>{
            this.loadChatMessage();
        },10000)
    };

    clearTime=()=>{
        clearInterval(timer)
    }

    handleChatMessage(e) {
        if (e.keyCode == '13') {
            this.loadChatMessage()
        }
    }

    //聊天记录
    loadChatMessage() {
        var params = {
            params: [{
                signRecordID: this.state.signRecordID,
                type: '1',
                value: this.state.userData.userID,
                consultText: this.state.consultText
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070011",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        chatMsg: res.result.data
                    },()=>{
                        this.scrollToBottom();
                    })
                }
            }
        });
    }

    scrollToBottom=() => {
        let mesageScrollDom = document.querySelector(".Row-content");
        console.log(mesageScrollDom.scrollHeight)
        mesageScrollDom.scrollTop = mesageScrollDom.scrollHeight;
    }

    closeModal(name) {
        let { onHide } = this.props;
        onHide && onHide();
        this.clearTime()
        this.cleanInput();
    }

    //清空输入框
    cleanInput() {
        this.props.form.resetFields();
        this.setState({
            consultText: undefined,
            textContent: undefined,
            patID: undefined
        })
    }

    //提交
    onSubmit() {
        let { onSubmit } = this.props;
        onSubmit && onSubmit(this.state.data, this.state.newCode);
    }

    showCommonChartModal() {
        this.setState({
            isShowCommonChartModal: true
        })
    }

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

    loadChatMessageList() {
        var { chatMsg } = this.state;
        var chatMsgOption = []
        chatMsg && chatMsg.map((item, index) => {
            if (item.flag == 'right') {
                chatMsgOption.push(
                    <div style={{ textAlign: 'left', display: 'flex' }} key={index}>
                        <div className='chat-list-right'><span style={{ marginLeft: 10 }}>{item.consultText}</span></div>
                        <div className='chat-imformation'>{item.createUserDesc}</div>
                    </div>
                )
            } else if (item.flag == 'left') {
                chatMsgOption.push(
                    <div style={{ textAlign: 'left', display: 'flex' }} key={index}>
                        <div className='chat-imformation'>{item.createUserDesc}</div>
                        <div className='chat-list-left'><span style={{ marginLeft: 10 }}>{item.consultText}</span></div>
                    </div>
                )
            }
        })
        return chatMsgOption
    }

    changeInput(name, e) {
        this.setState({
            [name]: e.target.value
        })
    }

    handleSendMessage(e) {
        if (e.keyCode == '13') {
            this.sendMessage()
        }
    }

    //发送消息
    sendMessage() {
        var params = {
            params: [{
                signRecordID: this.state.signRecordID,
                consultText: this.state.textContent,
                createUserID: this.state.userData.userID,
                receiveValue: [this.state.patID],
                receiveType: '2',
                sendType: '1',
                sendValue: this.state.userData.userID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070010",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.loadData()
                    this.setState({
                        textContent: undefined
                    })
                }
            }
        });
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.patID === this.state.patID ? 'clickRowStyle' : '';
    }


    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    recordID: record.patID,
                    recordIndex: record.index,
                    patID: record.patID,
                    signRecordID: record.signRecordID
                }, () => {
                    this.loadChatMessage()
                })
            },
        };
    }

    onRefs = ref => {
        this.onRefresh = ref
    }


    render() {
        return <div>
            {/**公共图表弹框 */}
            <ShowHealthChartModal isShow={this.state.isShowCommonChartModal}
                patID={this.state.patID}
                onHide={this.hideModal.bind(this, 'isShowCommonChartModal')}>
            </ShowHealthChartModal>
            <Modal className='show-information-modal'
                title={'待处理咨询'}
                maskClosable={false}
                visible={this.props.isShow}
                footer={null}
                onCancel={this.closeModal.bind(this)}
                onOk={this.onSubmit.bind(this)}>
                <Card style={{ width: '25%', float: 'left', height: '70vh', overflow: 'auto' }}>
                    <Table columns={this.leftColumns} style={{ background: 'white' }}
                        dataSource={this.state.dataSource}
                        onRow={this.onClickRow} bordered
                        rowClassName={this.setRowClassName}
                        showHeader={false}
                        rowKey={(data) => {
                            return data.patID
                        }}
                        scroll={{ y: '70vh' }}
                        pagination={false}></Table>
                </Card>
                <Card style={{ width: '74.8%', float: 'right', height: '70vh', overflow: 'auto', background: '#F0F2F5' }}>
                    <Card style={{ height: '10vh' }}>
                        {/* 个人信息，等有数据了，再单独封装吧 */}
                        {this.state.patID ? <ShowCommonInformationPage patID={this.state.patID} onRef={this.onRefs}/> : null}
                    </Card>
                    <Card style={{ height: '5vh', marginTop: 5 }}>
                        <Input style={{ width: '40%' }} placeholder='请输入内容' onKeyDown={this.handleChatMessage.bind(this)}
                            onChange={Util.commonInputChange.bind(this, 'consultText')} value={this.state.consultText} />
                        <span style={{ marginLeft: 10, color: '#0099FF', cursor: 'pointer' }} onClick={this.showCommonChartModal.bind(this)}>生命体征监测情况</span>
                    </Card>
                    <Card style={{ marginTop: 5, height: '43vh', overflow: 'auto' }} className='Row-content'>
                        {this.loadChatMessageList()}
                    </Card>

                    <Card style={{ marginTop: 5 }} className='con-btn-style'>
                        <TextArea rows={3} style={{ width: '90%', float: 'left' }} onChange={this.changeInput.bind(this, 'textContent')}
                            onKeyDown={this.handleSendMessage.bind(this)}
                            value={this.state.textContent} />
                        <Button style={{ float: 'right', background: '#1890ff', color: 'white' }} size='large'
                            onClick={this.sendMessage.bind(this)}>发送</Button>
                    </Card>
                </Card>
            </Modal></div>
    }
}

export default Form.create()(ShowConsultationModal);