/**
 *健康管理记录--咨询记录(查询条件没添加，参数需要动态设置)

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

const { RangePicker } = DatePicker;
var timer = null;
class ConsultingRecords extends React.Component {
    constructor(props) {
        super(props)
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        var patID = JSON.parse(sessionStorage.getItem('patID'))
        this.state = {
            data: [],
            activeKey: '1',
            records: [],
            userData: userData,
            inputValue: '',
            dateFrom: '',
            dateTo: '',
            patID: patID,
            contractID: '',//签约id
            iconImg: '',
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            fileList: [],
            actionUrl: "",
            imgPicture: '',
        }
    }

    componentDidMount() {
        this.props.onRef(this);
        this.signContractID();
        this.getIconUrl()
        // this.startTime();
    }
    componentWillUnmount() {
        this.clearTime();
    }
    startTime = (e) => {
        timer = setInterval(() => {
            this.communicationRecords();
        }, 10000)
    };

    clearTime = () => {
        clearInterval(timer)
    };
    getIconUrl = () => {
        let { userData } = this.state;
        let aSelect = {
            params: [{
                userID: userData.userID,
                locID: userData.locID,
                groupID: userData.groupID,
                hospID: userData.hospID
            }]
        };
        // 获取下拉数据
        $http.post('urlS', this, {
            code: "03070115",
            data: aSelect,
            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({ iconImg: url.indexOf("http") !== -1 ? url : windowHost + url })
                }
            }
        })
    }
    ///获取签约id
    signContractID = () => {
        var params = {
            params: [{
                patID: this.state.patID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070019",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        contractID: res.result[0].personInfo ? res.result[0].personInfo.signRecordID : '',
                    }, () => {
                        this.communicationRecords();
                    })
                }
            }
        });
    };
    ///查询咨询记录
    communicationRecords = () => {
        var params = {
            params: [{
                dateFrom: this.state.dateFrom ? moment(this.state.dateFrom).format('YYYY-MM-DD') : '',
                dateTo: this.state.dateTo ? moment(this.state.dateTo).format('YYYY-MM-DD') : '',
                consultText: this.state.inputValue,
                signRecordID: this.state.contractID,   //签约记录ID
                type: 1,                                     //类型，医生
                value: this.state.userData.userID            //医生ID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070011",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        records: res.result.data,
                    }, () => {
                        this.scrollToBottom();
                    })
                }
            }
        });
    };
    ///发送咨询记录
    sendCommunicationRecord = () => {
        var params = {
            params: [{
                ID: '',
                signRecordID: this.state.contractID,   //签约记录ID
                receiveValue: [this.state.patID],          //接收方ID
                receiveType: 2,           //接收方类型 1：医生 2：患者
                sendValue: this.state.userData.userID,   //发送方ID
                sendType: 1,             //发送方类型
                consultText: this.state.communicateData, //消息内容
                picture: this.getImgStr(),
                sound: "",
                video: "",
                createUserID: this.state.userData.userID        ///创建人员ID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03070010",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({ communicateData: '', fileList: [] });
                    this.communicationRecords();
                }
            }
        });
    };
    ///消息内容
    communicateChange = (v) => {
        this.setState({
            communicateData: v.target.value
        })
    };
    inputonChange = (v) => {
        this.setState({ inputValue: v.target.value })
    };
    timeData = (v) => {
        this.setState({ dateFrom: v[0], dateTo: v[1] })
    };

    scrollToBottom = () => {
        let mesageScrollDom = document.querySelector(".Row-content");
        mesageScrollDom.scrollTop = mesageScrollDom.scrollHeight;
    };
    onChange = (info) => {
        if (this.state.iconImg !== "") {
            if (info.file.status == "removed") {
                let a = this.state.fileList.filter(data => {
                    if (data.status !== "removed") {
                        return data;
                    }
                });
                this.setState({ fileList: a });
            } else {
                let formData = new FormData();
                formData.append("file", info.file);
                const option = {
                    method: 'post',
                    mode: 'cors',
                    headers: {},
                    body: formData
                };
                // http://218.17.212.34:53774/uploadFile?fileType=health
                // let url  = "http://172.18.100.86:3008/uploadFile?fileType=health";
                fetch(this.state.iconImg, option).then(response => {
                    if (response.ok) {
                        console.log('suc')
                        return response.text();
                    } else {
                        console.log('网络错误，请稍后再试');
                        return;
                    }
                }).then(data => {
                    let dataS = JSON.parse(data);
                    let str = this.state.iconImg.match(/(\S*)\/uploadFile/)[1];
                    let obj = { uid: this.state.fileList.length + 1, name: "health", status: 'done', url: str + "/images/health/" + dataS.filePath }
                    // console.log('121212313',obj);
                    this.state.fileList.push(obj);
                    this.sendCommunicationRecord();
                })

            }
        }
    };
    beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传JPG/PNG文件!');
        }
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //     message.error('图片大小不能超过2MB!');
        // }
        return false;
    };
    getImgStr = () => {
        let newList = this.state.fileList.map(data => {
            let myUrl = data.url.split("/");
            let hh = myUrl[myUrl.length - 1]
            return hh;
        });
        // console.log('图片',newList)
        let str = newList[0];
        if (str) {
            return str;
        } else {
            return ''
        }

    }
    render() {
        const { previewVisible, previewImage, fileList, previewTitle } = this.state;
        const uploadButton = (
            <div>
                <div className="ant-upload-text">图片</div>
            </div>
        );
        return <div className='ConsultingRecords'>
            <Row style={{ background: '#fff', padding: '10px 0' }}>
                <Col span={8}>
                    日期 <span><RangePicker onChange={this.timeData} style={{ width: '40%' }} />
                        <Input style={{ width: '40%' }} placeholder='输入关键字查询' onChange={this.inputonChange} /></span>
                </Col>
                <Col span={2}>
                    <Button onClick={() => this.communicationRecords()}>查询</Button>
                </Col>
            </Row>
            <div style={{ height: (store.getState().tableHeight.y) - 113 + 'px' }} className='Row-content' >
                <div style={{ height: this.state.records.length * 100 }} id='bottomAll'>
                    {this.state.records.length > 0 && this.state.records.map((item, key) => {
                        return <div style={{ width: '100%', minHeight: '100px' }} className={item.flag == "right" ? 'rightList' : ''} key={key}>
                            <div style={{ width: '50%', float: item.flag == "right" ? 'right' : 'left' }}>
                                <p style={{ textAlign: 'center', marginBottom: '5px' }}>{item.createDate} {item.createTime}</p>
                                {item.flag == "right" ?
                                    <p>
                                        <span className={false ? 'name' : 'rightName name'}>{item.sendTypeDesc}</span>
                                        {item.picture ?
                                            <img src={item.picture} style={{ width: "100px", height: "100px" }} />
                                            :
                                            <span className={false ? 'content' : 'rightContent content'}>{item.consultText}</span>
                                        }
                                    </p>
                                    :
                                    <p>

                                        <span className={true ? 'name' : 'rightName'}>{item.sendTypeDesc}</span>
                                        {item.picture ?
                                            <img src={item.picture} style={{ width: "100px", height: "100px" }} />
                                            :
                                            <span className={true ? 'content' : 'rightContent'}>{item.consultText}</span>
                                        }
                                    </p>
                                }
                            </div>
                        </div>
                    })}
                </div>
                <div style={{ clear: 'both', display: 'none' }}></div>
            </div>
            <Row className='sendModule'>

                <div className="clearfix">
                    <Upload
                        accept="image/jpeg,image/png"
                        listType="picture-card"
                        beforeUpload={this.beforeUpload}
                        onChange={this.onChange}
                    >
                        {uploadButton}
                    </Upload>
                </div>
                <div>
                    <span>
                        <Input style={{ width: '93%', height: '75px' }} value={this.state.communicateData} onChange={this.communicateChange} />
                    </span>
                    <span>
                        <a className='send' onClick={() => this.sendCommunicationRecord()}>发送</a>
                    </span>
                </div>
            </Row>
        </div>
    }

}

export default ConsultingRecords;
