/*
 * Creator:     ML
 * CreatDate:   2020-06-01
 * descripts：  在线客服
 * */
import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Tabs,
    DatePicker, Button, Popconfirm, Icon, Divider, message, Modal,
} from 'antd';
import { Util, } from 'tools/index';
import { $http } from 'containers/config/https';
import store from 'store';
import './style/index.less';
import OnlineServiceChat from './component/OnlineServiceChat';
import TRTC from 'trtc-js-sdk';
import TIM from 'tim-js-sdk';
import COS from 'cos-js-sdk-v5';
import LibGenerateTestUserSig from '../../../public/lib-generate-test-usersig.min.js';
/**
 * 签名过期时间，建议不要设置的过短
 * <p>
 * 时间单位：秒
 * 默认时间：7 x 24 x 60 x 60 = 604800 = 7 天
 */
const EXPIRETIME = 604800;
const TabPane = Tabs.TabPane;
class OnlineService extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            userData: userData,
            activeKey: '1',
            info: {},
            listID: "",
            messageListData: [],
            typeID: "3",
            patID: "",
            admID: "",
        }
    }

    componentDidMount() {
        this.loadTencentCloud()
        this.handleGetList()
        this.loadUploadAddress()

    }
    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }
    //动态获取  SDKAPPID  SECRETKEY  登录
    /**
     * 计算签名用的加密密钥
     */
    loadTencentCloud() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03100143",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        tencentMsg: res.result,
                        imSecretKey: !Util.isEmpty(res.result) ? res.result.imSecret : '',
                        imAppID: !Util.isEmpty(res.result) ? Number(res.result.imAppID) : '',
                    }, () => {
                        this.loginTencent()
                    })
                }
            }
        });
    }
    //获取聊天咨询列表信息
    handleGetList = (name, listID, info) => {
        let data = {
            params: [{
                name: this.state.oneValue || "",
                type: this.state.typeID && this.state.typeID == "3" ? "" : this.state.typeID
            }]
        }
        $http.post("urlS", this, {
            code: "03100110",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        messageListData: res.result.data
                    }, () => {
                        if (res.result.data.length > 0) {
                            //默认列表第一个聊天窗口
                            if (!name) {
                                this.setState({
                                    listID: res.result.data[0].ID,
                                    info: res.result.data[0]
                                }, () => {
                                    this.onRefMsg.clearInput()
                                    this.handleReadMessage(res.result.data[0].sendValue, res.result.data[0].sendType, "name")
                                    this.getChatData("isScroll", "", "");
                                    this.onRefMsg.scrollToBottom()
                                })
                            }
                            //发送完消息 刷新列表
                            if (name && listID && info) {
                                this.setState({
                                    listID,
                                    info,
                                }, () => {
                                    this.handleReadMessage(this.state.info.sendValue, this.state.info.sendType, "name")
                                    this.getChatData("isScroll", "", "");
                                    this.onRefMsg.scrollToBottom()
                                })
                            }
                        } else {
                            this.setState({
                                listID: "",
                                info: {}
                            })
                        }

                    })
                } else {
                    message.error(res.errorMessage)
                }
            }
        })
    }

    // 保存IM通信用户
    saveCommunicationUser = () => {
        let data = {
            params: [{
                userType: 'P',
                userID: this.state.info.patID || '',
            }]
        }
        $http.post("urlS", this, {
            code: "03090002",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                } else {
                    // message.error(res.errorMessage)
                }
            }
        })
    }
    // 监听是否被踢下线
    monitorKickedOut = (event) => {
        let { isKickedOut } = this.state;
        this.setState({ isKickedOut: false });
        if (isKickedOut) {
            message.warn('您的账号在别处登录，请重新登录')
        }
    }

    // 监听接收消息
    onMessageReceived = (event) => {
        var that = this;
        // console.log("触发监听了", event)
        let { userData } = that.state;
        let info = event.data[0].payload.text;
        let infoForm  = event.data[0]
        let a = ""
        //接收患者消息
        if (infoForm.from.indexOf("patient")>-1) {
            let patID = JSON.parse(info).patID
            a = patID.slice(7)
        }
        // console.log("Number(JSON.parse(info).patID)",a,"this.state.info.sendValue",Number(that.state.info.sendValue),"---------",JSON.parse(info).patID,that.state.info.sendValue)
        //如果是当前的窗口用户发来消息  需要调一下消除消息tips的接口
        if ((JSON.parse(info).userID == that.state.info.sendValue) || (a == Number(that.state.info.sendValue))) {
            // console.log("okokokokokokoko")
            that.handleGetList("name", that.state.listID, that.state.info)
        } else {
            //刷新列表 并且保持当前窗口
            that.handleGetList("name")
            // this.getChatData("isScroll", "", "");
        }
    }
    //登录用户 .
    loginTencent() {
        let options = {
            SDKAppID: this.state.imAppID
        }
        this.tim = TIM.create(options); // SDK 实例通常用 tim 表示
        // 设置 SDK 日志输出级别，详细分级请参见 setLogLevel 接口的说明
        this.tim.setLogLevel(0); // 普通级别，日志量较多，接入时建议使用
        // tim.setLogLevel(1); // release 级别，SDK 输出关键信息，生产环境时建议使用
        // 注册 COS SDK 插件
        this.tim.registerPlugin({ 'cos-js-sdk': COS });
        const generator = new LibGenerateTestUserSig(this.state.imAppID, this.state.imSecretKey, EXPIRETIME);
        const userSig = generator.genTestUserSig("userKF001");
        let user = userSig;
        let promise = this.tim.login({ userID: "userKF001", userSig: user });
        promise.then((imResponse) => {
            // console.log(imResponse)
            if (imResponse.data.errorCode == '0') {
                this.setState({ isKickedOut: true }, () => {
                    this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived);
                    this.tim.on(TIM.EVENT.KICKED_OUT, this.monitorKickedOut);
                    // if (type == 'video') {
                    //     setTimeout(() => {
                    //         this.handleSendVideoMsg()
                    //     }, 500)
                    // }
                })
                // if (type === "user") {
                //     this.saveCommunicationUser();
                //     setTimeout(() => {
                //         this.signOut("user"); // 退出医生登录
                //     }, 300)
                // }
            }
        }).catch(function (imError) {
            console.warn('login error:', imError); // 登录失败的相关信息
        });
    }
    // 获取消息列表数据
    getChatData = (isScroll, isLoading, newMessage) => {
        let { doctorData, userData, lastMsgID } = this.state;
        // if (isLoading !== "isLoading") {
        //     this.setState({ refreshing: true });
        // }
        let data = {
            params: [{
                admID: this.state.info.admID, //病人admID
                frUser: "userKF001", // //自己
                toUser: this.state.info && this.state.info.sendType == "2" ? 'patient' + this.state.info.patID : "user" + this.state.info.sendValue,  //病人patID 接收方 user 医生  患者 "patient"
                // toUser: 'patient' + 23,  //病人patID
                lastMsgID
                // lastMsgID: chatData&&chatData.length > 0 ? chatData[0].megID : ""
            }]
        }
        $http.post("urlS", this, {
            code: "02090005",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    let chatData = res.result && res.result.msgData instanceof Array ? res.result.msgData : [];
                    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                    for (var i = 0; i < chatData.length; i++) {
                        let url = chatData[i].picture
                        chatData[i].picture = url.indexOf("http") !== -1 ? url : windowHost + url;
                    }
                    this.setState({ chatData, refreshing: false, moreMsgFlag: res.result.moreMsgFlag, newMessage: newMessage ? newMessage : "" }, () => {

                    });
                } else {
                    this.setState({ chatData: [], refreshing: false, moreMsgFlag: "Y", newMessage: newMessage ? newMessage : "" })
                }
            }
        });
    }
    //获取上传地址
    loadUploadAddress() {
        var params = {
            params: [{
                locID: this.state.userData && this.state.userData.locID || "",
                userID: this.state.userData && this.state.userData.userID || "",
                hospID: this.state.userData && this.state.userData.hospID || "",
                groupID: this.state.userData && this.state.userData.groupID || "",
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070115",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                    let url = res.result || "";
                    this.setState({
                        addressUrl: url.indexOf("http") !== -1 ? url : windowHost + url
                    })
                }
            }
        });
    }
    // 图片上传至服务器
    imageUpload = (fileList, success, error) => {
        var that = this;
        let { userData } = this.state;
        let data = new FormData();
        data.append('file', fileList);
        const option = {
            method: 'post',
            mode: 'cors',
            headers: {},
            body: data
        };
        fetch(this.state.addressUrl, option)
            .then(function (response) {
                if (response.ok) {
                    return response.text();
                } else {
                    console.log('网络错误，请稍后再试')
                    return;
                }
            }).then(function (data) {
                let dataS = JSON.parse(data);
                that.setState({
                    filePath: dataS.filePath
                }, () => {
                    that.uploadImg()
                })
            }).catch(function (e) {
                console.log("发送失败： ", e);
                error && error(e);
            })
    }
    uploadImg() {
        let { messageValue, doctorData, userData } = this.state;
        // this.fileToBase64(this.state.filePath).then(res => {
        let data = {
            params: [{
                admID: this.state.info.admID,
                frUser: "userKF001",
                toUser: this.state.info && this.state.info.sendType == "2" ? 'patient' + this.state.info.patID : "user" + this.state.info.sendValue,//对方
                consultText: "",
                picture: this.state.filePath,
            }]
        }
        $http.post("urlS", this, {
            code: "02090004",
            data: data,
            namespace: "HIS",
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        sendStatus: true
                    })
                    this.handleSendImage(res);
                    this.onRefMsg.scrollToBottom()
                    this.onRefMsg.clearInput()
                } else {
                    message.error(res.errorMessage)
                }
            }
        })
        // })
    }
    // 发送图片
    handleSendImage = (res) => {
        let { messageValue, doctorData, userData, titleData, patientData } = this.state;
        try {

            let messageContent = {};
            messageContent.userID = "KF001";
            messageContent.admID = this.state.info.admID || '';
            if (this.state.info && this.state.info.sendType == "2") {
                messageContent.patID = this.state.info.patID || '';
                messageContent.patName = this.state.info && this.state.info.name || '';
            } else {
                messageContent.docID = this.state.info.sendValue || '';
                messageContent.docName = this.state.info && this.state.info.name || '';
            }

            messageContent.userName = userData.userName;
            messageContent.type = 'H';
            messageContent.text = '';
            messageContent.image = 'Y';
            let message = this.tim.createTextMessage({
                to: this.state.info && this.state.info.sendType == "2" ? 'patient' + this.state.info.patID : "user" + this.state.info.sendValue,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent),
                }
            });
            // 2. 发送消息
            let promise = this.tim.sendMessage(message);
            if (promise) {
                promise.then((imResponse) => {
                    // 发送成功
                    if (imResponse && imResponse.code === 0) {
                        let chatData = JSON.parse(JSON.stringify(this.state.chatData));
                        // let imgPath = imResponse.data.message.payload.imageInfoArray[0].imageUrl;
                        let imgPath = 'https://chis.e24health.com/images/consult/' + this.state.filePath;
                        let obj = {
                            picture: imgPath,
                            direction: "right",
                            msgType: "1",
                        }
                        chatData.push(obj);
                        this.setState({ chatData }, () => {
                            // this.getChatData("isScroll", "", ""); // 获取消息
                            // this.messageWrapperScrollBottom();
                            // this.setState({})
                            this.onRefMsg.scrollToBottom()
                        })
                        // this.getChatData("isScroll", "", ""); // 获取消息
                        this.handleGetList("name", this.state.listID, this.state.info)
                    }
                }).catch((imError) => {
                    // 发送失败
                    message.error('发送失败：', imError);
                    this.deleteChatData(res.result.msgID)
                });
            }
        } catch (e) {
            message.error("发送失败: " + e.message)
        }
    }
    // input-onChange
    messageValueOnChange(e) {
        this.setState({ messageValue: e }, () => {
            // this.getSendHeight();
        });
    }
    // 发送文字
    handleSendText = (res) => {
        let { messageValue, doctorData, userData, titleData } = this.state;
        var patientData = JSON.parse(sessionStorage.getItem('patientData'));
        try {

            let messageContent = {};
            messageContent.userID = "KF001";
            messageContent.admID = this.state.info.admID || '';
            if (this.state.info && this.state.info.sendType == "2") {
                messageContent.patID = this.state.info.patID || '';
                messageContent.patName = this.state.info && this.state.info.name || '';
            } else {
                messageContent.docID = this.state.info.sendValue || '';
                messageContent.docName = this.state.info && this.state.info.name || '';
            }

            messageContent.userName = userData.userName;
            messageContent.type = 'H';
            messageContent.text = messageValue;
            let message = this.tim.createTextMessage({
                to: this.state.info && this.state.info.sendType == "2" ? 'patient' + this.state.info.patID : "user" + this.state.info.sendValue,
                conversationType: TIM.TYPES.CONV_C2C,
                payload: {
                    text: JSON.stringify(messageContent)
                }
            });
            // 2. 发送消息
            let promise = this.tim.sendMessage(message);
            if (promise) {
                promise.then((imResponse) => {
                    if (imResponse && imResponse.code === 0) {
                        let chatData = JSON.parse(JSON.stringify(this.state.chatData));
                        let text = imResponse.data.message.payload.text;
                        let obj = {
                            consultText: messageValue,
                            direction: "right",
                            msgType: "1",
                        }
                        chatData.push(obj)
                        this.setState({ messageValue: "", chatData }, () => {
                            // this.getChatData("isScroll", "", ""); // 获取消息
                            // this.messageWrapperScrollBottom();
                            // this.onRefMsg.scrollToBottom()
                            // this.setState({})
                            this.handleGetList("name", this.state.listID, this.state.info)
                        })
                    }
                }).catch((imError) => {
                    // 发送失败 --- 调接口改变消息状态
                    message.error('发送失败：', imError);
                    this.deleteChatData(res.result.msgID)
                });
            }
        } catch (error) {
            message.error(error.message);
        }
    }
    // 发送
    handleSend = (type, source) => {
        let { messageValue, doctorData, userData } = this.state;
        if (type === "img") {
            let imagePickerDom = document.getElementById("imagePicker");
            this.imageUpload(imagePickerDom.files[0])
        } else {
            let data = {
                params: [{
                    admID: this.state.info.admID,
                    frUser: "userKF001",//自己
                    toUser: this.state.info && this.state.info.sendType == "2" ? 'patient' + this.state.info.patID : "user" + this.state.info.sendValue,//对方
                    consultText: messageValue ? messageValue : source,
                    picture: "",
                }]
            }
            $http.post("urlS", this, {
                code: "02090004",
                data: data,
                namespace: "HIS",
                success: function (res) {
                    if (+res.errorCode === 0) {
                        this.setState({
                            messageValue: source,
                            sendStatus: true
                        }, () => {
                            // this.handleReceive()
                            this.handleSendText(res)
                            this.onRefMsg.scrollToBottom()
                            this.onRefMsg.clearInput()
                        })
                    } else {
                        message.error(res.errorMessage)
                    }
                }
            })
        }
    }
    onRefMessage = ref => {
        this.onRefMsg = ref
    }
    handleInput = (e, name) => {
        if (e.target) {
            this.setState({
                [name + "Value"]: e.target.value
            })
        }
    }

    //消除未读
    handleReadMessage = (sendValue, sendType, name) => {
        let data = {
            params: [{
                // userID: this.state.userData&&this.state.userData.userID||"",
                userID: "KF001",
                sendValue: sendValue || "",
                sendType: sendType || ""
            }]
        }
        $http.post("urlS", this, {
            code: "03100111",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    if (name) {
                        this.handleGetList("name")
                    }
                } else {
                    message.error(res.errorMessage)
                }
            }
        })
    }
    //点击咨询列表 行信息 
    handleInfo = (e, item) => {
        const { listID } = this.state
        //有未读消息 点击消失
        if (item.noReadCount != 0 && item.noReadCount > 0) {
            this.handleReadMessage(item.sendValue, item.sendType, "name")
        }
        this.setState(({
            info: item,
        }))
        if (listID == "") {
            this.setState({
                listID: item.ID,
            }, () => {
                this.getChatData("isScroll", "", "");
                this.onRefMsg.clearInput()
                this.onRefMsg.scrollToBottom()
            })
        } else if (listID != item.ID) {
            this.setState({
                listID: item.ID,
            }, () => {
                this.getChatData("isScroll", "", "");
                this.onRefMsg.clearInput()
                this.onRefMsg.scrollToBottom()
            })
        } else {

        }
    }
    //选择医生 搜索
    handleGetType = (e) => {
        this.setState({
            typeID: e.key
        }, () => {
            this.handleGetList()
        })
    }
    render() {
        const { info, listID, messageListData } = this.state
        const typeData = [
            {
                descripts: "医生",
                descriptsSPCode: "ys",
                id: "1"
            },
            {
                descripts: "患者",
                descriptsSPCode: "hz",
                id: "2"
            },
            {
                descripts: "全部",
                descriptsSPCode: "qb",
                id: "3"
            },

        ]
        // const messageListData = [
        //     {
        //         descripts: "杨意",
        //         date: "今天 09:22",
        //         key: "01",
        //         messageNumber: 100,
        //         message: "您大概是在什么时间段操作的：请问我在申请图文咨询，付费的时候，点击支付后，按钮没有反映，您大概是在什么时间段操作的",
        //         value: "1",
        //         type:"01",
        //         typeDesc:"患者",
        //         age:"19",
        //         sex:"女",
        //         no:"2020060404",
        //         phone:"15523237878" ,
        //         src:"https://bkimg.cdn.bcebos.com/pic/0df3d7ca7bcb0a46f21f81aa802be1246b600c330145?x-bce-process=image/resize,m_lfit,w_500,h_500,limit_1"
        //     },
        //     {
        //         descripts: "迪丽",
        //         key: "02",
        //         date: "今天 09:02",
        //         messageNumber: 3,
        //         message: "请问我在申请图文咨询，付费的时候，点击支付后，按钮没有反映。请问我在申请图文咨询，付费的时候，点击支付后，按钮没有反映。缴费不成功，不知道为什么原因",
        //         value: "2",
        //         type:"01",
        //         typeDesc:"患者",
        //         age:"29岁",
        //         sex:"女",
        //         no:"202001404",
        //         phone:"15523237871",
        //         src:"https://bkimg.cdn.bcebos.com/pic/fcfaaf51f3deb48f8f9616a7fd1f3a292cf578cf?x-bce-process=image/resize,m_lfit,w_500,h_500,limit_1"     
        //     },
        //     {
        //         descripts: "赵大富",
        //         key: "03",
        //         date: "06-01",
        //         messageNumber: 21,
        //         message: "请问您大概是在什么时间段操作的，在申请图文咨询，付费的时候，点击支付后，按钮没有反映。是在申请哪个医生的s时候出现的这种情况，麻烦您提供详细的情况？",
        //         value: "3",
        //         type:"03",
        //         typeDesc:"医生",
        //         age:"66岁",
        //         sex:"男",
        //         phone:"16666666666",
        //         hospDec:"宝安中医院",
        //         locDec:"消化内科",
        //         level:"副主任医师",
        //         no:2896,   
        //         src:"http://172.18.100.86:3009/photo/7cc6503b682758cc5ca1df55d444ee57.jpg"             
        //     },

        // ]
        //查询条件
        let typeOp = []
        typeData && typeData.length > 0 && typeData.map(item => {
            typeOp.push(
                <Option
                    // onClick={this.changeDefalut}
                    key={item.id}
                    name={item.descriptsSPCode}
                    title={item.descripts}
                    role={item.descripts + '^' + item.descriptsSPCode}
                    value={item.id}
                    onClick={this.handleGetType}

                >
                    {item.descripts}
                </Option>)
        })
        let messageOp = []
        messageListData && messageListData.map((item, i) => {
            messageOp.push(
                <div className="message-list" style={{ background: (item.ID == this.state.listID ? "rgba(24, 144, 255, 0.2)" : "#fff") }} onClick={(e) => this.handleInfo(e, item)}>
                    <span className={item.sendType == "1" ? "doctor-bg triangle-topleft" : "hosp-bg triangle-topleft"}></span>
                    <div className="ribbon-green">
                        {item.sendTypeDesc}
                    </div>
                    <div className="list-left">
                        <span
                        // className='splice-boy'
                        >
                            <img className="img"
                                src={item.personImage && item.personImage}
                            ></img>
                        </span>
                        {
                            item.noReadCount != 0 ? <span style={{ display: "flex" }}>{item.noReadCount && item.noReadCount > 99 ? "99+" : item.noReadCount}</span> : null
                        }
                    </div>
                    <div className="list-right">
                        <p className="list-right-top">
                            <span>{item.name}</span>
                            <span>{item.consultTime}</span>
                        </p>
                        <p className="list-right-bottom">
                            {item.consultText}
                        </p>
                    </div>
                </div>
            )
        })

        return <div className='online-service-dom'>
            <Row>
                <Col span={9} className="left">
                    <Card span={9} key="01" style={{ height: store.getState().tableHeight.y + 238 + 'px', overflow: "auto" }}>
                        <div className="left-top">
                            <Col span={14}>
                                <Input allowClear placeholder="请输入首拼/汉字,回车查询" onChange={(e) => this.handleInput(e, "one")} onPressEnter={this.handleGetList} value={this.state.oneValue}>
                                </Input>
                            </Col>

                            <Col span={8}>
                                <Select style={{ width: '100%' }}
                                    dropdownMatchSelectWidth={false}
                                    value={this.state.typeID || "3"}
                                    onChange={Util.handleSelectChange.bind(this, "typeID")}
                                    getPopupContainer={triggerNode => triggerNode.parentNode}
                                >
                                    {typeOp}

                                </Select></Col>
                        </div>
                        {
                            messageListData && messageListData.length > 0 ? <div className="left-content">
                                {messageOp}
                            </div> : <div>
                                    <p style={{ textAlgin: "center" }}>未检索到相关数据,请重新检索</p>
                                </div>
                        }


                    </Card>
                </Col>

                <Col span={15} className="right">
                    <Card span={15} key="02" style={{ height: store.getState().tableHeight.y + 238 + 'px', overflow: "auto" }}>
                        <div style={{ display: (listID && listID ? "block" : "none") }}>

                            <Row style={{ background: "#f5f4f4", height: "2px" }}></Row>
                            {
                                listID && listID ?
                                    <div className="content" id="message-send-box-wrapper">
                                        <OnlineServiceChat handleSend={this.handleSend.bind(this)}
                                            chatData={this.state.chatData}
                                            sendStatus={this.state.sendStatus}
                                            statusNote={this.state.statusNote}
                                            info={this.state.info}
                                            onRef={this.onRefMessage}
                                            messageValueOnChange={this.messageValueOnChange.bind(this)} /></div> : null
                            }
                        </div>

                    </Card>
                </Col>
            </Row>
        </div>
    }

}

export default OnlineService;