/**
 * JYW
 * 消息列表
 */
import React, { Component } from 'react';
import { Modal, message, Input, Button, Select, Radio, Table, Col } from 'antd';
import fetchJsonp from 'fetch-jsonp';
import { $http } from '../../containers/config/https';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import ColumnAuthoritysModel from '../columnAuthority/ColumnAuthoritysModel'
import moment from 'moment';
// import { Util, dayFormat } from 'tools/index';
// import { MessageSocket } from 'tools/MessageSocket.js';
import ExecuteMessage from './ExecuteMessage.jsx'
import './CSS/message.less';

let user;
// const { Search } = Input;
const { Option } = Select;
const confirm = Modal.confirm;
const { TextArea } = Input;
// let messageServer;

class Message extends Component {
  constructor(props) {
    // messageServer = window.sessionStorage.messageServer ? JSON.parse(window.sessionStorage.messageServer) : {}
    user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    super(props);
    this.state = {
      admDateFrom: '',
      admDateTo: '',
      keywords: '',
      visible: false,
      size: 'small',
      messageList: [],
      messageDetail: {},
      newMsg: [],
      readFinish: true,
      readMessageIndex: -1,
      RecordColums: [],
      dataSource: [],
      columns: [],
      search: 'search',
      page: 1,
      pageSize: 20,
      total: 0,
      patientInfo: {},
      messageImportanceArr: [],
      messageEventArr: [],
      messageStatusArr: [],
      messageEventCode: 'ALL',
      eventImportCode: 'ALL',
      messageStatusCode: 'U',
      clickRow: {},
      activeKey: '',
      ENObj: {},
      CNObj: {},
      languageObj: {},
      totalWidth: '',
    };
    this.sendMessage = this.sendMessage.bind(this);
    this.handlerKeywords = this.handlerKeywords.bind(this);
  }

  componentDidMount() {
    this.props.onRef(this);
    // this.recordData()    //changeBy: DYK
    this.loadColumn()
    this.getBaseData()
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  //获取信息页面基本消息
  getBaseData = () => {
    let data = {
      params: [{}],
    }
    $http.post('urlDeault', this, {
      code: "04180008",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          let defaultDate = res.result && 'data' in res.result ? res.result.data : {};
          this.setState({
            messageImportanceArr: res.result.MessageImportanceArr,
            messageEventArr: res.result.MessageEventArr,
            messageStatusArr: res.result.MessageStatusArr,
            admDateFrom: defaultDate?.startDate || moment().subtract(1, 'months').format('YYYY-MM-DD'),
            admDateTo: defaultDate?.endDate || moment().format('YYYY-MM-DD'),
          })
        }
      }
    })
  }

  /**过去消息信息方法
   * @author changeBy:DYK
   * @param status
   */
  recordData = (status) => {
    let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    if (!(userData && userData.sessionID) || this.messageQuerying) {
      return;
    }
    this.messageQuerying = true;
    let data = {
      params: [{
        userID: userData.userID,
        messageEventCode: this.state.messageEventCode,
        eventImportCode: this.state.eventImportCode,
        messageStatusCode: this.state.messageStatusCode,
        admDateFrom: this.state.admDateFrom,
        admDateTo: this.state.admDateTo,
      }],
      pagination: [{
        pageSize: this.state.pageSize,
        currentPage: this.state.page,
      }]
    };
    $http.post('urlDeault', this, {
      code: "04180005",
      data: data,
      success: (res) => {
        this.messageQuerying = false;
        if (+res.errorCode !== 0) {
          return;
        }
        const result = res.result || {};
        const dataSource = result.MessageRecordArr || [];
        const total = Number(result.total) || 0;
        if (this.state.visible) {
          this.setState({
            dataSource,
            total,
          });
        } else {
          this.props.handlerThis.setState({
            messageCount: total,
            dataSource,
            visible: true
          });
        }
      },
      error: () => {
        this.messageQuerying = false;
      }
    });
  }

  //查询列头数据
  loadColumn = () => {
    let data = {
      params: [{
        compontName: 'messageList',
        type: "C",
        reactCode: ['messageList'],
      }]
    }
    $http.post('urlDeault', this, {
      code: "01040073",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          let column = res.result.C;
          if (user.language == 'EN') {
            for (let i = 0; i < column.length; i++) {
              column[i].title = column[i].enDescripts
            }
          }
          this.setState({
            columns: column,
            tableWidth: res.totalWidth,
            ENObj: res.result.language.EN,
            CNObj: res.result.language.CN,

          }, () => {
            this.recordData();
          })
        }
      }
    })
  }

  //响应服务器消息
  responseMessge = (msg) => {
    let that = this;
    let messageObj = JSON.parse(msg);
    if (that.state.visible) {
      confirm({
        title: '提示',
        content: "您有新的消息，是否查收!",
        onOk() {
          that.recordData();
        }
      });
    } else {
      that.setState({
        messageStatusCode: 'U',
      }, () => {
        that.recordData();
      })
    }
    that.setState({
      keywords: messageObj.content,
    })
    if (messageObj.readFlag == "1") {
      let newMsg = that.state.newMsg;
      newMsg.push(messageObj);
      if (that.state.readFinish) {
        that.setState({
          newMsg: newMsg,
          readFinish: false,
          readMessageIndex: 0,
        }, () => {
          that.readMsg();
        })
      } else {
        that.setState({
          newMsg: newMsg,
        });
      }
    }
  }

  //将消息转换为语音消息，并播放
  readMsg = () => {
    let msg = this.state.newMsg[this.state.readMessageIndex];
    if (msg) {
      let dllInput = {};
      dllInput.text = msg.content;
      dllInput.playTimes = msg.playTimes;
      let data = 'input={"inputDir":"SpeechSynthesisServer/SpeechSynthesisServer.dll","clsName":"SpeechSynthesisServer.SpeechSynthesisServer","funcName":"TextToVoice","dllInput":' + JSON.stringify(dllInput) + '}'
      let that = this
      fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
        jsonpCallback: 'JsonCallback',
        timeout: 30000,
      })
        .then(function (response) {
          return response.json()
        }).then(function (json) {
          json = JSON.parse(json);
          if ((json) && (json.errorCode == "0")) {
            that.state.newMsg.splice(that.state.readMessageIndex, 1);
            that.setState({
              readFinish: true,
              readMessageIndex: 0,
            }, () => {
              if (that.state.newMsg.length > 0) {
                that.readMsg();
              }
            })
          } else {
            that.setState({
              readFinish: true,
              readMessageIndex: 0,
            });
          }
        }).catch(function (ex) {
          that.state.newMsg.splice(that.state.readMessageIndex, 1);
          that.setState({
            readFinish: true,
            readMessageIndex: 0,
          }, () => {
            if (that.state.newMsg.length > 0) {
              that.readMsg();
            }
          })
        })
    }
  }

  /** 发送消息 */
  sendMessage = () => {
    this.readMsg(this.state.keywords, 1);
  }

  handlerKeywords = (e) => {
    this.setState({
      keywords: e.target.value,
    })
  }

  //打开消息框
  show = () => {
    let { visible } = this.state;
    if (!visible) {
      this.setState({
        visible: true,
        messageStatusCode: 'ALL',
      }, () => {
        this.recordData();
      })
    }
  }

  //关闭消息框
  hide = (event) => {
    event.stopPropagation();
    this.setState({
      visible: false,
      messageStatusCode: 'U',
    })
  }

  startChange(date) {
    this.setState({
      admDateFrom: date,
    })
  }

  endChange(date) {
    this.setState({
      admDateTo: date,
    })
  }

  handleSizeChange = e => {
    this.setState({ messageStatusCode: e.target.value }, () => {
      this.recordData()
    });

  };

  onChange(e, pageSize) {
    this.setState({ page: e, pageSize: pageSize }, () => {
      this.recordData();
    });
  }

  //分页切换
  changePageSize(page, pageSize) {
    this.setState({ pageSize: pageSize, page: page }, () => {
      this.recordData();
    });
  }

  /**
     *  获取患者基本信息
    */
  getPatientInfo(record) {
    if (((record.patID === "") || (record.patID === undefined)) && ((record.admID === "") || (record.admID === undefined))) {
      return;
    }
    let data = {
      params: [{
        admID: record.admID,
        patId: record.patID,
        hospID: user.hospID,
        findAdmFlag: '0',
      }]
    }
    $http.post('urlDeault', this, {
      code: "04020007",
      data: data,
      success: (res) => {
        if (+res.errorCode === 0) {
          this.setState({
            patientInfo: res.result
          });
        } else {
          message.error('获取病人基本信息失败!:' + res.errorMessage);
        }
      }
    })
  }

  onRow = (record) => {
    var that = this
    return {
      onClick: () => {
        if (!that.state.isDoubelClickTab) {
          that.setState({
            isDoubelClickTab: true,
            clickRow: record,
          }
            , () => {
              that.getPatientInfo(record);
              if (record.receiverStatusCode == "U") {
                this.readMessage(record);
              }
            });
        } else {
          if (that.state.clickRow == record) {
            that.setState({ isDoubelClickTab: false, clickRow: {} })
          } else {
            that.setState({
              isDoubelClickTab: true,
              clickRow: record,
              newData: [],
            }
              , () => {
                that.getPatientInfo(record);
                if (record.receiverStatusCode == "U") {
                  this.readMessage(record);
                }
              });
          }
        }
      },
      onChange: () => {
        this.setState({ isDoubelClickTab: false })
      }
    };
  }

  //用户读取消息 - 点击消息即读取消息
  readMessage = (record) => {
    let data = {
      params: [{
        receiveID: record.receiveID,
      }]
    }
    $http.post('urlDeault', this, {
      code: "04180007",
      data: data,
      success: (res) => {
        this.recordData();
      }
    })
  }

  //消息类型
  cardTypeChange = (value) => {
    this.setState({
      messageEventCode: value,
      page: 1,
      pageSize: 20,
      total: 0,
    }, () => {
      this.recordData()
    })

  }

  changeEventImport = (name, e) => {
    this.setState({
      [name]: e.target.value,
      page: 1,
      pageSize: 20,
      total: 0,
    }, () => {
      this.recordData()
    });
  }

  solutionMessage() {
    if (this.state.clickRow.handleComponent == "") {
      let data = {
        params: [{
          receiveID: this.state.clickRow.receiveID,
          handlerIdea: this.state.clickRow.handlerIdea || '',
          status: "H"
        }]
      }
      $http.post('urlDeault', this, {
        code: "04180007",
        data: data,
        success: (res) => {
          this.recordData();
        }
      })
    } else {
      this.childConsume.showModal(this.state.clickRow.handleComponent, this.state.clickRow);
    }
  }

  onConsumeRef = (ref) => {
    this.childConsume = ref;
  };

  ///行背景色
  setRowClassName = (record) => {
    if (this.state.clickRow.id != record.id) {
      if (record.receiverStatusCode == "U") return "unRead";
      if (record.receiverStatusCode == "R") return "unHandle";
      if (record.receiverStatusCode == "H") return "unReply";
      if (record.receiverStatusCode == "A") return "Replied";
    } else {
      return 'clickRowStyle';
    }
  }

  //组件权限编辑器
  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  render() {
    var language = user.language
    var languageObj = {}
    if (language == "EN") {
      languageObj = this.state.ENObj
    } else {
      languageObj = this.state.CNObj
    }
    const { size } = this.state;

    let MessageEventArr = [];
    this.state.messageEventArr.map((item) => {
      MessageEventArr.push(
        <Option key={item.code} value={item.code} >
          {item.descripts}
        </Option>
      )
    })
    let MessageImportanceArr = [];
    this.state.messageImportanceArr.map((item) => {
      MessageImportanceArr.push(
        <Radio.Button value={item.code} key={item.code}>
          {item.descripts}
        </Radio.Button>
      )
    })
    let MessageStatusArr = [];
    this.state.messageStatusArr.map((item) => {
      MessageStatusArr.push(
        <Radio.Button value={item.code} key={item.code}>
          {item.descripts}
        </Radio.Button>
      )
    })
    return (
      <Modal
        className="message"
        title={languageObj.messageListeventList != null ? languageObj.messageListeventList.descripts : ""}
        visible={this.state.visible}
        destroyOnClose
        maskClosable={false}
        onCancel={this.hide}
        footer={null}
      >
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName="messageList"
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.loadColumn}
        />
        <div className="msgsearch">
          <div style={{ width: '100%', height: '35px' }}>
            <Col span={1} style={{ width: '240px' }}>
              {languageObj.messageListeventType != null ? languageObj.messageListeventType.descripts : ""}<Select value={this.state.messageEventCode}
                onChange={this.cardTypeChange}
                style={{ width: '120px' }}>
                {MessageEventArr}
              </Select>
            </Col>
            <Col span={1} style={{ width: '380px' }}>
              <RangeDatePicker format='YYYY-MM-DD' label={languageObj.messageListSendDate != null ? languageObj.messageListSendDate.descripts : ""} labelwidth="73px" totalwidth="350" width="300px"
                startDate={this.state.admDateFrom} endDate={this.state.admDateTo}
                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
            </Col>
            <Col span={1} style={{ width: '470px' }}>
              <Radio.Group key="import" value={this.state.eventImportCode} onChange={this.changeEventImport.bind(this, 'eventImportCode')} style={{ padding: '0 10px' }}>
                {MessageImportanceArr}
              </Radio.Group>
            </Col>
          </div>
          <div style={{ width: '100%', height: '35px', lineHeight: '35px' }}>
            <Radio.Group key="status" value={this.state.messageStatusCode} onChange={this.changeEventImport.bind(this, 'messageStatusCode')}>
              {MessageStatusArr}
            </Radio.Group>
          </div>
        </div>
        <div className="msgbody">
          <div className="msglist">
            <Table
              pagination={false}
              style={{ height: 'calc(100% - 38px)', padding: '0 5px' }}
              scroll={{ y: 'calc(100% - 60px)' }}
              bordered
              onRow={this.onRow}
              columns={this.state.columns}
              rowClassName={this.setRowClassName}
              dataSource={this.state.dataSource}
              rowKey={(row) => {
                return row.id;
              }}
              onHeaderRow={column => {
                return {
                  onDoubleClick: () => {
                    this.columnRef.onOpenModel();
                  }
                };
              }
              }
            >
            </Table>
            <CommonPagination pageSize={this.state.pageSize} size={this.state.size} current={this.state.page} total={this.state.total} search={this.state.search}
              onShowSizeChange={this.changePageSize.bind(this)} complete={false} dataSource={this.state.dataSource}
              onChange={this.onChange.bind(this)} />
          </div>
          <div className="msgdetail">
            {this.state.isDoubelClickTab ? (
              <div className="detail">
                <div className="patInfo">
                  <div className="title">病人信息</div>
                  <div className="info">
                    <Col span={8}>{languageObj.messageListpatNo != null ? languageObj.messageListpatNo.descripts : ""}  {this.state.patientInfo.basicInfo ? this.state.patientInfo.basicInfo.patNo : ""}</Col>
                    <Col span={8}>{languageObj.messageListpatName != null ? languageObj.messageListpatName.descripts : ""}  {this.state.patientInfo.basicInfo ? this.state.patientInfo.basicInfo.patName : ""}</Col>
                    <Col span={8}>{languageObj.messageListpatAge != null ? languageObj.messageListpatAge.descripts : ""}  {this.state.patientInfo.basicInfo ? this.state.patientInfo.basicInfo.patAge : ""}</Col>
                  </div>
                  <div className="info">
                    <Col span={8}>{languageObj.messageListadmLocDesc != null ? languageObj.messageListadmLocDesc.descripts : ""}  {this.state.patientInfo.admInfo ? this.state.patientInfo.admInfo.admLocDesc : ""}</Col>
                    <Col span={8}>{languageObj.messageListadmDocDesc != null ? languageObj.messageListadmDocDesc.descripts : ""}  {this.state.patientInfo.admInfo ? this.state.patientInfo.admInfo.admDocDesc : ""}</Col>
                    <Col span={8}>{languageObj.messageListmrDesc != null ? languageObj.messageListmrDesc.descripts : ""}  {this.state.patientInfo.admInfo ?
                      this.state.patientInfo.admInfo.admDiagInfo.map((item, index) => {
                        if (item.mainFlag == "Y") {
                          return (<span key={index}>{item.mrDesc} </span>)
                        }
                      }) : ""
                    }</Col>
                  </div>
                  <div>

                  </div>
                </div>
                <div className="messageDetail">
                  <div className="title">{this.state.clickRow.eventDesc}</div>
                  <div className="sendInfo">
                    <span style={{ color: "darkgray" }}>
                      {languageObj.messageListSend != null ? languageObj.messageListSend.descripts : ""}：{this.state.clickRow.sendUserName}</span>&nbsp;&nbsp;&nbsp;&nbsp;
                    <span style={{ color: "darkgray" }}>
                      {languageObj.messageListTime != null ? languageObj.messageListTime.descripts : ""}：{this.state.clickRow.sendDate + " " + this.state.clickRow.sendTime}
                    </span>
                  </div>
                  <div style={{ width: "100%", padding: '3px 5px', height: "calc(100% - 304px)", borderBottom: '2px solid #dddddd' }}>
                    <span>{this.state.clickRow.message}</span>
                  </div>
                  <div className="dealwith">
                    <Col span={21}>
                      <TextArea
                        disabled={this.state.clickRow.handleComponent != ""}
                        maxLength={1000}
                        placeholder={languageObj.messageListHandOpinion != null ? languageObj.messageListHandOpinion.descripts : ""}
                        autoSize={{ minRows: 5, maxRows: 5 }}
                        value={this.state.clickRow.handlerIdea}
                        onChange={(e) => {
                          let clickRow = this.state.clickRow;
                          clickRow.handlerIdea = e.target.value;
                          this.setState({
                            clickRow: clickRow,
                          })
                        }}
                      ></TextArea>
                    </Col>
                    <Col span={3} style={{ lineHeight: '110px', verticalAlign: 'bottom' }}>
                      <Button style={{ height: '32px', margin: '5px' }} type="primary" onClick={this.solutionMessage.bind(this)}>{languageObj.messageListHandle != null ? languageObj.messageListHandle.descripts : ""}</Button>
                    </Col>
                  </div>
                  {/* <div className="Send">
                    <Col span={21}>
                      <TextArea
                        maxLength={1000}
                        placeholder="回复内容"
                        autosize={{ minRows: 5, maxRows: 5 }}
                      ></TextArea>
                    </Col>
                    <Col span={3} style={{ lineHeight: '110px', verticalAlign: 'bottom' }}>
                      <Button style={{ height: '32px', margin: '5px' }} type="primary" onClick={this.solutionMessage.bind(this)}>回复</Button>
                    </Col>
                  </div> */}
                </div>
              </div>
            ) : <span> {languageObj.messageListPleaseSelectMessageListRecord != null ? languageObj.messageListPleaseSelectMessageListRecord.descripts : ""}</span>
            }
          </div>

          <ExecuteMessage
            activeKey="ExecuteMessage"
            onRef={this.onConsumeRef}
          />
        </div>
      </Modal>
    );
  }
}

export default Message
