/**
 * 语音、图文聊天
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal,
    DatePicker, Button, Tabs, Icon, Divider, message, List, Tooltip,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import moment from 'moment';
import store from 'store';
import '../style/index.less';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const TabPane = Tabs.TabPane;
const { TextArea } = Input;
const logo = require('../image/doctor.png');
const patinet = require('../image/patName.png');
const modules = require('../image/module.png');
const pictureText = require('../image/pictureText.png');

class ShowCommonVoiceChatPage extends React.Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var titleData = JSON.parse(sessionStorage.getItem('titleData'))
        var recordData = JSON.parse(sessionStorage.getItem('patientData'));
        if (!recordData) {
            recordData = JSON.parse(sessionStorage.getItem('recordData'));
        }
        var newDate = date.setMonth(date.getMonth() - 1);
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            recordData: recordData,
            userData: userData,
            titleData: titleData,
            activeKey: '1',
            rotaRight: 0,
            SS: 1,
            i: 0,
            S: 1,
        }
        this.textOnRef = React.createRef();
    }

    componentDidMount() {
        this.props.onRef(this)
        this.textOnRef.current.focus()
    }

    handleSend(type, e) {
        var { handleSend } = this.props;
        handleSend && handleSend(type, this.state.messageValue);
        if (e && e.target) {
            e.target.value = '';
        }
    }

    onKeyDownSendMessage(e) {
        if (e.ctrlKey && e.keyCode == '13') {
            this.state.messageValue = this.state.messageValue + '\n'
            this.setState({})
        } else if (e.keyCode == '13') {
            this.handleSend('text')
        }
    }

    messageValueOnChange(e) {
        this.setState({
            messageValue: e.target.value
        }, () => {
            var { messageValueOnChange } = this.props;
            messageValueOnChange && messageValueOnChange(this.state.messageValue)
        })
    }

    handleShowModal = (imgPath) => {
        this.setState({ visible: true, imgPath })
    }

    handleClose = () => {
        this.setState({
            visible: false, rotaRight: 0, SS: 1,
            i: 0,
            S: 1,
        })
    }

    clearInput() {
        this.setState({
            messageValue: undefined
        })
    }

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

    //获取聊天模板
    showChatModuleModal() {
        if (this.state.isShowChatModuleModal == true) {
            this.setState({
                isShowChatModuleModal: false
            }, () => {
                this.textOnRef.current.focus()
            })
        } else {
            this.setState({
                isShowChatModuleModal: true
            }, () => {
                this.loadChatModuleMsg()
            })
        }
    }

    //查询模板信息
    loadChatModuleMsg() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100028",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var moduleMsg = res.result.data
                    var moduleOption = []
                    if (!Util.isEmpty(moduleMsg)) {
                        for (var i = 0; i < moduleMsg.length; i++) {
                            moduleOption.push(moduleMsg[i].templet)
                        }
                    }
                    this.setState({
                        moduleMsg: moduleOption
                    })
                }
            }
        });
    }

    //将模板数据渲染到输入框中
    handleSetModuleMsg(e) {
        this.setState({
            messageValue: e.target.textContent,
            isShowChatModuleModal: false
        }, () => [
            this.textOnRef.current.focus()
        ])
    }

    handleOpenSelectImage = () => {
        // e.preventDefault();
        let imgDom = document.getElementById('imagePicker');
        imgDom.click();
    }

    //顺时针旋转
    rotateright = () => {
        this.setState({ rotaRight: this.state.rotaRight + 90 })
        this.refs.imgstyle.style.transform = "translate(-50% ,0%) rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")"
    }

    //放大
    showbig = () => {
        if (this.state.i >= 0) {
            this.setState({ S: this.state.S + 1, i: this.state.i + 1, SS: 1 * (this.state.S + 1) })
        } else {
            this.setState({ S: this.state.S - 1, i: this.state.i + 1, SS: 1 / (this.state.S - 1) })
        }
        this.refs.imgstyle.style.transform = "translate(-50% ,0%) rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")"
    }

    //缩小
    showmin = () => {
        if (this.state.i <= 0) {
            this.setState({ S: this.state.S + 1, i: this.state.i - 1, SS: 1 / (this.state.S + 1) })
        } else {
            this.setState({ S: this.state.S - 1, i: this.state.i - 1, SS: 1 * (this.state.S - 1) })
        }
        this.refs.imgstyle.style.transform = "translate(-50% ,0%) rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")"
    }

    render() {

        return <div className='common-chat-body' style={{ height: '100%' }}>
            <Card style={{ height: '8.5%' }}>
                {/* 王梦涵 / 男 / 67岁/2020015478 已接诊患者，距离问诊结束时长：12:10:28 */}
                <span>{!Util.isEmpty(this.state.titleData) ? this.state.titleData.patName : '--'}</span><Divider type='vertical' />
                <span>{!Util.isEmpty(this.state.titleData) ? this.state.titleData.patSexDesc : '--'}</span><Divider type='vertical' />
                <span>{!Util.isEmpty(this.state.titleData) ? this.state.titleData.patAge : '--'}</span><Divider type='vertical' />
                <span>{!Util.isEmpty(this.state.titleData) ? this.state.titleData.patNo : '--'}</span><Divider type='vertical' />
                {/* <span>您已接诊，距离结束剩余时间：12:12:12</span><Divider type='vertical' /> */}
                {/* <Button style={{ background: 'rgb(250, 140, 22)', color: 'white' }} size='small'>{this.props.statusNote}</Button> */}
                <Button style={{ background: 'rgb(250, 140, 22)', color: 'white' }} size='small'>
                    {/* {this.props.sendStatus == true ? '接诊中' : (!Util.isEmpty(this.state.titleData) ? this.state.titleData.status : '')} */}
                    {(!Util.isEmpty(this.state.titleData) ? this.state.titleData.status : '')}
                </Button>
            </Card>

            <Card style={{ marginTop: 5, height: '90.7%' }} bodyStyle={{ height: '100%' }}>
                <Card style={{ height: '70%', overflow: 'auto' }} className='Row-content'>
                    {this.props.chatData && this.props.chatData.map((item, index) => {
                        return (
                            <div key={index} className={item.msgType === "1" && item.direction === "right" ? "mw-content mw-content-right mw-message" : (item.msgType === "1" && item.direction === "left" ? "mw-content mw-message" : "mw-message mw-content-content")}>
                                <div className="col-1" style={{ display: item.msgType === "1" ? "block" : "none" }}>
                                    {/* 头像 */}
                                    {item.direction === "left" ? <img src={patinet} alt="" /> : <img src={logo} alt="" />}
                                </div>
                                {/* msgType === 1 正常消息， 2为撤回 ，3 为时间 */}
                                <div className="col-2" style={{ display: item.msgType === "1" ? "block" : "none" }}>
                                    {/* 主题消息 */}
                                    <i className={item.direction === "left" && item.picture ? "iconfont icon-juxingbeifen icon-color-fff icon-left" : (item.direction === "right" && item.picture ? "iconfont icon-juxingbeifen icon-color-fff" : (item.direction === "left" ? "iconfont icon-juxingbeifen icon-color-fff icon-left" : "iconfont icon-juxingbeifen"))}></i>
                                    <span className={item.direction === "left" && item.picture ? "message-content message-received background-color-fff" : (item.direction === "right" && item.picture ? "message-content message-send background-color-fff" : (item.direction === "left" ? "message-content message-received" : "message-content message-send"))}>
                                        {item.consultText ? (item.consultText) : (item.picture ? <img src={item.picture} onClick={() => this.handleShowModal(item.picture)} alt="" /> : "")}
                                    </span>
                                </div>
                                <div className="col-3" style={{ display: item.msgType === "2" || item.msgType === "3" ? "block" : "none" }}>
                                    {/* 消息状态 */}
                                    {item.msgType === "2" ? <span>{item.direction === "left" ? "对方撤回了一条消息" : "你撤回了一条消息"}</span> : (item.msgType === "3" ? <span>{item.sendTime}</span> : "")}
                                </div>
                            </div>
                        )
                    })}
                </Card>
                <Card style={{ height: '29.9%' }}>
                    <div style={{ height: 20, lineHeight: '15px', marginLeft: 10 }}>
                        <img src={modules} title='模板' style={{ cursor: 'pointer' }} onClick={this.showChatModuleModal.bind(this)} />

                        <input accept="image/gif, image/jpeg,image/png,image/bmp" type="file" id="imagePicker" style={{ display: 'none' }} onChange={(e) => this.handleSend("img", e)} placeholder="截图后粘贴到输入框中" />
                        {!Util.isEmpty(this.state.titleData) &&
                            (this.state.titleData.statusCode == 'RR' || this.state.titleData.statusCode == 'F') ? null :
                            <img src={pictureText} title='发送图片' style={{ marginLeft: 10, cursor: 'pointer' }} onClick={this.handleOpenSelectImage} />}
                    </div>
                    <TextArea rows={5} onChange={this.messageValueOnChange.bind(this)} value={this.state.messageValue}
                        ref={this.textOnRef} disabled={!Util.isEmpty(this.state.titleData) &&
                            (this.state.titleData.statusCode == 'RR' || this.state.titleData.statusCode == 'F') ? true : false}
                        onKeyDown={this.onKeyDownSendMessage.bind(this)} />
                    <div style={{ height: 30, textAlign: 'right', lineHeight: '30px' }}>

                        <span>Enter发送,Ctrl+Enter换行</span>
                        <Button type='primary' size='small' style={{ marginLeft: 10 }}
                            disabled={!Util.isEmpty(this.state.titleData) &&
                                (this.state.titleData.statusCode == 'RR' || this.state.titleData.statusCode == 'F') ? true : false}
                            className="send-btn" onClick={() => this.handleSend("text")}>发送</Button>
                    </div>
                </Card>
            </Card>
            <Modal
                visible={this.state.visible}
                title='图片预览' maskClosable={false}
                onCancel={this.handleClose}
                bodyStyle={{ padding: 5, overflow: 'auto', maxHeight: '700px', maxWidth: '700px' }}
                footer={<div>
                    <Icon type="zoom-in" style={{ fontSize: '24px', cursor: 'pointer' }} onClick={this.showbig} title='放大' />
                    <Icon type="zoom-out" style={{ marginLeft: 10, fontSize: '24px', cursor: 'pointer' }} onClick={this.showmin} title='缩小' />
                    <Icon type='reload' style={{ marginLeft: 10, fontSize: '24px', cursor: 'pointer' }} onClick={this.rotateright} title='旋转' />
                    <a style={{ color: 'inherit' }} href={this.state.imgPath} target="_blank"><Icon type='download' style={{ marginLeft: 10, fontSize: '24px', cursor: 'pointer' }} title='下载' /></a>
                </div>}
                className="crc-modal"
            >
                <div className="crc-m-content" onClick={this.handleClose}>
                    <img src={this.state.imgPath} alt="" style={{
                        width: '100%', cursor: 'pointer',
                        transform: "translate(-50% ,0%) rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")"
                    }}
                        className='imgstyle' ref='imgstyle' />
                </div>
            </Modal>
            {/**展示聊天模板 */}
            {this.state.isShowChatModuleModal == true ?
                <div className='chat-module-body'>
                    <List
                        size="small"
                        bordered
                        header={<span style={{ color: 'black', fontWeight: 'bold', fontSize: '16px' }}>聊天模板</span>}
                        dataSource={this.state.moduleMsg}
                        renderItem={item => <List.Item style={{ cursor: 'pointer' }} onDoubleClick={this.handleSetModuleMsg.bind(this)}>{item}</List.Item>}
                    />
                </div> : null}
        </div>
    }
}

export default Form.create()(ShowCommonVoiceChatPage);