/*
 * Creator:     ML
 * CreatDate:   2020-06-02
 * descripts：  在线客服 聊天界面
 * */

import React from 'react';
import {
    Card, Input, Form, Row, Col, Modal,
    Button, Icon, Divider, List,
} from 'antd';
import { Util, } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import '../../workstation/style/index.less';
const { TextArea } = Input;
const logo = require('../../workstation/image/doctor.png');
const modules = require('../../workstation/image/module.png');
const pictureText = require('../../workstation/image/pictureText.png');

class OnlineServiceChat extends React.Component {
    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        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: {},
            activeKey: '1',
            rotaRight: 0,
            SS: 1,
            i: 0,
            S: 1,
            firstIndex: 0,
            f: 0,
            x: 0,
            y: 0,
            modulesInput: ""
        }
        this.textOnRef = React.createRef();
    }

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

    handleSend(type) {
        var { handleSend } = this.props;
        handleSend && handleSend(type, this.state.messageValue)
    }

    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 = (imageSource) => {
        this.setState({ visible: true, imageSource, firstIndex: 0, f: 0 }, () => {
            setTimeout(() => {
                if (this.refs.imgstyle) {
                    this.refs.imgstyle.style.transform = "translate(0) rotate(" + 0 + "deg) scale(1)"
                    this.refs.imgstyle.style.left = "0"
                    this.refs.imgstyle.style.top = "0"
                    this.refs.imgstyle.style.right = "0"
                    this.refs.imgstyle.style.bottom = "0"
                    this.refs.imgstyle.style.margin = "auto"
                }
            }, 100)
        })
    }
    handleClose = () => {
        this.setState({
            visible: false,
            rotaRight: 0,
            SS: 1,
            i: 0,
            S: 1,
            firstIndex: 0,
            f: 0,
            x: 0,
            y: 0,
        })
    }

    clearInput = () => {
        this.setState({
            messageValue: undefined,
            isShowChatModuleModal: false
        })
    }

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

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

    //查询模板信息
    loadChatModuleMsg = () => {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                content: this.state.modulesInput
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100024",
            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();
    }
    onWheel = () => {
        this.state.SS += event.wheelDelta / 1200;
        if (this.state.SS >= 0.2) {
            this.refs.imgstyle.style.transform = "scale(" + this.state.SS + ")";
        } else {
            this.state.SS = 0.2;
            this.refs.imgstyle.style.transform = "scale(" + this.state.SS + ")";
            return false;
        }
    }
    moveImg = (ev) => {

        const { x, y } = this.state

        ev.preventDefault()

        var disx = ev.pageX - x

        var disy = ev.pageY - y

        document.onmousemove = (ev) => {

            // this.setState({

            //     x: ev.pageX - disx,

            //     y: ev.pageY - disy

            // })
            this.state.x = ev.pageX - disx
            this.state.y = ev.pageY - disy
            this.refs.imgstyle.style.left = ev.pageX - disx + 'px'
            this.refs.imgstyle.style.top = ev.pageY - disy + 'px'

        }

        document.onmouseup = () => {

            document.onmousemove = null

            document.onmousedown = null

        }

    }
    //顺时针旋转
    rotateright = () => {
        this.setState({ rotaRight: this.state.rotaRight + 90 })
        this.refs.imgstyle.style.transform = "translate(-50% ,-50%) 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% ,-50%) 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% ,-50%) rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")"
    }
    //回车检索模板内容
    handleEnter = () => {

    }
    render() {
        // console.log("this.props.info",this.props.info)
        return <div className='common-chat-body' style={{ height: '100%' }}>
            <Card style={{ height: "52px", lineHeight: "52px" }}>
                <Row style={{ height: "52px", lineHeight: "52px", paddingLeft: "12px", }}>
                    <Col span={21} style={{ display: (this.props.info && this.props.info.sendType == "2" ? "block" : "none"), color: "#333" }}>
                        {this.props.info.name || "--"} <Divider type="vertical" />
                        {this.props.info.sexDesc || "--"} <Divider type="vertical" />
                        {this.props.info.age || "--"} <Divider type="vertical" />
                        {this.props.info.patNo || "--"} <Divider type="vertical" />
                        {this.props.info.mobile || "--"} <Divider type="vertical" />
                    </Col>
                    <Col span={21} style={{ display: (this.props.info && this.props.info.sendType == "1" ? "block" : "none"), color: "#333" }}>
                        {this.props.info.hospDesc || "--"} <Divider type="vertical" />
                        {this.props.info.locDesc || "--"} <Divider type="vertical" />
                        {this.props.info.titleDesc || "--"} <Divider type="vertical" />
                        {this.props.info.patNo || "--"} <Divider type="vertical" />
                        {this.props.info.name || "--"} <Divider type="vertical" />
                        {this.props.info.sexDesc || "--"} <Divider type="vertical" />
                        {this.props.info.age || "--"} <Divider type="vertical" />
                        {this.props.info.mobile || "--"} <Divider type="vertical" />
                    </Col>
                    {/* <Col span={3} style={{padding:"0 12px 0 0 ",textAlign:"right"}}>
                            <span style={{color:"#cccc",fontSize:"26px",cursor:"pointer"}}>x</span>
                        </Col> */}
                </Row>
            </Card>

            <Card style={{ marginTop: 5, height: '90.7%' }} bodyStyle={{ height: '100%' }}>
                <Card style={{ height: store.getState().tableHeight.y - 35 + 'px', position: "relative", overflow: "auto" }} className='Row-content'>
                    {this.props.chatData && 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={this.props.info.personImage} 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>
                        )
                    }) :
                        <div style={{ height: store.getState().tableHeight.y - 35 + 'px', position: "relative" }}>

                        </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/*" type="file" id="imagePicker" style={{ display: 'none' }} onChange={() => this.handleSend("img")} 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}
                imageSource={this.state.imageSource}
                firstIndex={this.state.firstIndex}
                bodyStyle={{ padding: 5, overflow: 'hidden', maxHeight: '700px', maxWidth: '700px', minHeight: 500 }}
                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.imageSource} target="_blank"><Icon type='download' style={{ marginLeft: 10, fontSize: '24px', cursor: 'pointer' }} title='下载' /></a>
                </div>}
                className="crc-modal"
            >
                <div className="crc-m-content" style={{ height: 680, position: "relative" }}>
                    <img
                        onMouseDown={this.moveImg}
                        onWheel={this.onWheel}
                        src={this.state.imageSource}
                        className="imgstyle"
                        alt=""
                        style={{
                            position: "absolute", width: 'auto', cursor: 'pointer', height: 'auto', maxHeight: '100%', maxWidth: '100%',
                            transform: " rotate(" + this.state.rotaRight + "deg) scale(" + this.state.SS + "," + this.state.SS + ")",
                            left: this.state.x + 'px', top: this.state.y + 'px'
                        }}
                        ref='imgstyle' />
                </div>
            </Modal>
            {/**展示聊天模板 */}
            {this.state.isShowChatModuleModal == true ?
                <div className='chat-module-body' style={{ top: "32%", left: "3%", width: "400px" }}>
                    <p style={{ margin: "12px" }}>
                        <span style={{ color: 'black', fontWeight: 'bold', fontSize: '16px' }}>聊天模板<span style={{ float: "right", cursor: "pointer" }} onClick={() => this.setState({ isShowChatModuleModal: false })}>X</span></span>
                    </p>
                    <Input style={{ width: "98%", margin: "0 0 10px 4px", }} clearInput placeholder="输入模板关键字,回车检索"
                        onPressEnter={() => this.loadChatModuleMsg()} onChange={(e) => {
                            this.setState({
                                modulesInput: e.target.value
                            })
                        }} />
                    <List
                        size="large"
                        bordered
                        header={null}
                        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()(OnlineServiceChat);