import React, { Component } from "react";
import style from "./index.less";
import printImg from '@common/images/icon_print_blue.png';
import preview from '@common/images/preview.png';
import saveHistory from '@common/images/saveHistory.png';
import PrintPreviewContainer from '@containers/PrintPreviewContainer';
import PreviewContainer from '@containers/PreviewContainer';
import { ConfirmModal, Notify } from '@commonComp';
import check_circle from './img/check-circle.png';
import check_right from './img/check-right.png';
import {getAllDataList,getAllDataStringList,isAllClear,filterDataArr,readyKeepHistory} from '@utils/tools';
import store from '@store';
import $ from 'jquery';

class Operation extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      okText: '',
      borderColor: '',
      okColor: '',
      oKBg: '',
      msg: '',
      type: '',
      zIndex:40,
      sex:'3',
      le:'',
    }
    this.showPrint = this.showPrint.bind(this);
    this.closePrint = this.closePrint.bind(this);
    this.showPreview = this.showPreview.bind(this);
    this.closePreview = this.closePreview.bind(this);
    this.saveAll = this.saveAll.bind(this);
    this.clearAll = this.clearAll.bind(this);
    this.saveHis = this.saveHis.bind(this);
    this.keypress = this.keypress.bind(this);
  }

  showPrint() {
    this.setState({
      zIndex:240
    })
    this.props.showPrintPreview()
  }

  closePrint() {
    this.setState({
      zIndex:40
    })
    this.props.closePrintPreview()
  }


  showPreview() {
    this.setState({
      zIndex:240
    })
    this.props.showPreview()
  }

  closePreview() {
    this.setState({
      zIndex:40
    })
    this.props.closePreview()
  }

  saveAll(type) {
    let keepState = readyKeepHistory();
    if(keepState == 1){
        Notify.info('主诉不能为空');
        return;
    }else if(keepState == 2){
        Notify.info('诊断不能为空');
        return;
    }else{
      this.setState({
        type: type,
        okText: '保存',
        borderColor: '#3B9ED0',
        okColor: '#fff',
        oKBg: '#3B9ED0',
        msg: <p className={style['msg']}>是否保存该病历？</p>
      })
      
      this.props.diagShowTmp(true)
    }
  }
  clearAll(type) {
    let baseList = store.getState();
    let jsonData = getAllDataList(baseList);
    let jsonStr = getAllDataStringList(baseList);
    let flg = isAllClear(jsonData,jsonStr,baseList);
    if(flg){
      this.setState({
        type: type,
        okText: '清除',
        borderColor: 'red',
        okColor: 'red',
        oKBg: '#fff',
        msg: <p className={style['msg']}>是否清空所有内容？</p>
      })
      
      this.props.diagShowTmp(true)
    }else{
      Notify.info('当前页面数据已清空');
    }
  }
  
  onchange(val) {
    this.setState({
      title: val
    })
  }
  handleInput(e){
    let val = e.target.value
    if(e.target.value.length > 30){
        e.target.value = val.substring(0,30)
        this.onchange(val.substring(0,30))
    }else{
        this.onchange(e.target.value)
    }
  }
  keypress(event) {
    let e = event?event:window.event;
    if (e.keyCode == 13) {
      this.makeSure()
    }
  }
  saveHis(type) {
    const { diagShowTmp } = this.props;
    let flg = this.getAllData();
    if(flg){
      this.setState({
        title: '',
        sex:'3',
        type: type,
        okText: '保存',
        borderColor: '#3B9ED0',
        okColor: '#fff',
        oKBg: '#3B9ED0',
        msg: this.changeTitle()
      })
      diagShowTmp(true)
    }
  }
  getAllData(){
    let baseList = store.getState();
    let jsonData = getAllDataList(baseList);
    let jsonStr = getAllDataStringList(baseList);
    let whichSign = baseList.typeConfig.typeConfig;
    let tmpLis = baseList.tabTemplate.items;
    
    let flg = isAllClear(jsonData,jsonStr,baseList)
    if(!flg){
      Notify.info('模板数据不能为空')
      return false
    }
    console.log(jsonStr,'文本')
    console.log(jsonData,'结构')       //测试需要用到，不要删了
    for(let i = 0;i <tmpLis.length;i++){
      let dataStr = tmpLis[i].preview;
      let dataJson = tmpLis[i].dataJson;
      // console.log(jsonStr.chief , JSON.stringify(eval('('+JSON.parse(dataStr).chief+')')))
      // console.log(jsonData.chief , JSON.parse(dataJson).chief)
      if(whichSign == 0){
        if(
          jsonStr.chief == JSON.stringify(eval('('+JSON.parse(dataStr).chief+')')) && 
          jsonStr.present == JSON.stringify(eval('('+JSON.parse(dataStr).present+')')) && 
          jsonStr.other == JSON.stringify(eval('('+JSON.parse(dataStr).other+')')) && 
          jsonStr.vital == JSON.stringify(eval('('+JSON.parse(dataStr).vital+')'))  &&
          JSON.stringify(jsonData.chief) == JSON.stringify(JSON.parse(dataJson).chief) &&    
          JSON.stringify(jsonData.present) == JSON.stringify(JSON.parse(dataJson).present)  &&     
          JSON.stringify(jsonData.other) == JSON.stringify(JSON.parse(dataJson).other) &&
          JSON.stringify(jsonData.vital) == JSON.stringify(JSON.parse(dataJson).vital) && 
          JSON.stringify(jsonData.lis) == JSON.stringify(JSON.parse(dataJson).lis) &&  
          JSON.stringify(jsonData.pacs) == JSON.stringify(JSON.parse(dataJson).pacs) &&     
          JSON.stringify(jsonData.diag) == JSON.stringify(JSON.parse(dataJson).diag) &&    
          JSON.stringify(jsonData.advice) == JSON.stringify(JSON.parse(dataJson).advice) &&    
          JSON.stringify(jsonData.mainSuitSelecteds) == JSON.stringify(JSON.parse(dataJson).mainSuitSelecteds) &&      
          JSON.stringify(jsonData.currentIllSelecteds) == JSON.stringify(JSON.parse(dataJson).currentIllSelecteds) &&     
          JSON.stringify(jsonData.otherHistorySelecteds) == JSON.stringify(JSON.parse(dataJson).otherHistorySelecteds) && 
          JSON.stringify(jsonData.checkBodySelecteds) == JSON.stringify(JSON.parse(dataJson).checkBodySelecteds) &&     
          JSON.stringify(jsonData.addItems) == JSON.stringify(JSON.parse(dataJson).addItems)
        ){
          Notify.info('该模板已保存');
          return false;
        }

      }else if(whichSign == 1){
        if(
          jsonStr.chief == JSON.stringify(eval('('+JSON.parse(dataStr).chief+')')) && 
          jsonStr.present == JSON.stringify(eval('('+JSON.parse(dataStr).present+')')) && 
          jsonStr.other == JSON.stringify(eval('('+JSON.parse(dataStr).other+')')) && 
          jsonStr.vital == JSON.stringify(eval('('+JSON.parse(dataStr).vital+')'))  &&
          JSON.stringify(jsonData.vital) == JSON.stringify(JSON.parse(dataJson).vital) && 
          JSON.stringify(jsonData.lis) == JSON.stringify(JSON.parse(dataJson).lis) &&  
          JSON.stringify(jsonData.pacs) == JSON.stringify(JSON.parse(dataJson).pacs) &&     
          JSON.stringify(jsonData.diag) == JSON.stringify(JSON.parse(dataJson).diag) &&    
          JSON.stringify(jsonData.advice) == JSON.stringify(JSON.parse(dataJson).advice) &&        
          JSON.stringify(jsonData.addItems) == JSON.stringify(JSON.parse(dataJson).addItems)
        ){
          Notify.info('该模板已保存');
          return false;
        }
      }
    }
    return true;
  }
  changeTitle() {
    return <div className={style['box']}>
      <input className={style['ipt']}
        placeholder="请输入模板名称"
        type="text"
        maxLength='30'
        onInput={(e) => {
          this.handleInput(e)
        }}
        onPropertyChange={(e) => {  // 兼容ie
          this.handleInput(e)
        }}
        onKeyPress={e => this.keypress(e)}
      />
      <div className={style['line']}></div>
      <div className={style['iptWrap']}>
        <p>请选择模板性别归属(错误引用，显示可能有误)</p>
        <span className={style['commonSex']} id="commonSex" onClick={this.changeRadio.bind(this,1)}><img src={check_right} alt=""/><i style={{color:'#000'}}>通用</i></span>
        <span id="maleSex" onClick={this.changeRadio.bind(this,2)}><img src={check_circle} alt=""/><i>男</i></span>
        <span id="femaleSex" onClick={this.changeRadio.bind(this,3)}><img src={check_circle} alt=""/><i>女</i></span>
      </div>
    </div>
  }
  changeRadio(sex){
    if(sex == 1){
      $('#commonSex img').attr('src',check_right)
      $('#maleSex img').attr('src',check_circle)
      $('#femaleSex img').attr('src',check_circle)
      $('#commonSex i').css('color','#000')
      $('#maleSex i').css('color','#6b6969')
      $('#femaleSex i').css('color','#6b6969')
      this.setState({sex:'3'})
    }else if(sex == 2){
      $('#commonSex img').attr('src',check_circle)
      $('#maleSex img').attr('src',check_right)
      $('#femaleSex img').attr('src',check_circle)
      $('#commonSex i').css('color','#6b6969')
      $('#maleSex i').css('color','#000')
      $('#femaleSex i').css('color','#6b6969')
      this.setState({sex:'1'})
    }else if(sex == 3){
      $('#commonSex img').attr('src',check_circle)
      $('#maleSex img').attr('src',check_circle)
      $('#femaleSex img').attr('src',check_right)
      $('#commonSex i').css('color','#6b6969')
      $('#maleSex i').css('color','#6b6969')
      $('#femaleSex i').css('color','#000')
      this.setState({sex:'2'})
    }
  }
  makeSure() {
    const { save, clear, saveDataAll,diagShowTmp ,chronicMagItem,chronicDesease} = this.props;
    const { type } = this.state;
    if (type == 1) {
      diagShowTmp(false)
      this.setState({ title: '' })
      save();
    } else if (type == 2) {
      diagShowTmp(false)
      this.setState({ title: '' })
      // 慢病标识
      const chronicFlag = chronicMagItem&&chronicMagItem.name || chronicDesease&&chronicDesease.name?true:false;
      clear(chronicFlag);
    } else if (type == 3) {
      if (this.state.title.trim() == '') {
        Notify.error('请输入模板名称')
        return;
      }
      saveDataAll(this.state.title,this.state.sex);
    }
  }
  closeDiagBox(){
    const { diagShowTmp } = this.props;
    const { type } = this.state;
    if (type == 3){
      diagShowTmp(false)
      this.setState({ title: '' })
    }else{
      diagShowTmp(false)
      this.setState({ title: '' }) 
    }
  }
  componentWillReceiveProps(next){//监听滚动事件
    const that = this;
    if(next.winWidth <= 1024){
      /*$(document).on('scroll',function(){
        let left = -($(document).scrollLeft() - 10) + 'px';
        that.setState({
          le:left
        })
      })*/
      $(window).scroll(function(){
        let scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
        let left = -(scrollLeft - 10) +'px';
        that.setState({
          le:left
        })
      })
    }
  }

  render() {
    const { showPrint, closePrint, showPreview, closePreview } = this;
    const { visible, preVisible,diagShow } = this.props.print;
    const {winWidth} = this.props;
    const {zIndex,type,le} = this.state;
    return <div className={style['container']} style={{zIndex:zIndex,left:le}}>
      <span className={style['button']} onClick={showPrint}><img src={printImg} /> 打印病历</span>
      <span className={style['preButton']} onClick={showPreview}><img src={preview} /> 预览</span>
      <span className={style['preButton']} onClick={() => { this.saveHis(3) }}><img src={saveHistory} /> 保存病历模板</span>
      <span className={winWidth<=1082?`${style['saveButton']} ${style['minstyle']}`: style['saveButton']} onClick={() => { this.saveAll(1) }}>保存</span>
      <span className={winWidth<=1082?`${style['clearButton']} ${style['saveButton']} ${style['minstyle']}`:`${style['clearButton']} ${style['saveButton']}`} onClick={() => { this.clearAll(2) }}>清除</span>
      <PrintPreviewContainer visible={visible} onClose={closePrint} />
      <PreviewContainer visible={preVisible} onClose={closePreview} />
      <ConfirmModal
        visible={diagShow}        //改为全局控制
        confirm={() => { this.makeSure() }}
        close={() => { this.closeDiagBox()}}
        cancel={() => {this.closeDiagBox()}}
        okText={this.state.okText}
        height={type==3?228:200}
        width={type==3?400:300}
        okBorderColor={this.state.borderColor}
        okColor={this.state.okColor}
        oKBg={this.state.oKBg}
      >
        {this.state.msg}
      </ConfirmModal>
    </div>;
  }
}

export default Operation;