import React, { Component } from "react";
import style from "./index.less";
import printImg from '@common/images/icon_print_blue.png';
import slideDown from '@common/images/slideDown.png';
import preview from '@common/images/preview.png';
import saveHistory from '@common/images/saveHistory.png';
import cancelTag from '@common/images/icon_back.png';
import PrintPreviewContainer from '@containers/PrintPreviewContainer';
import PreviewContainer from '@containers/PreviewContainer';
import { ConfirmModal, Notify } from '@commonComp';
import Search from './Search';
import FolderName from '@components/FolderName';
import FolderOrder from '@components/FolderOrder';
import check_circle from './img/check-circle.png';
import check_right from './img/check-right.png';
import { getAllDataList, getAllDataStringList, isAllPartClear, isAllClear, filterDataArr, readyKeepHistory, checkDeptContent } from '@utils/tools';
import { embedPush } from '../../store/async-actions/pushMessage'
import pinyin from '@utils/Convert_Pinyin.js';
import { saveMessage, clearMessages } from  '@store/async-actions/print'
import {dragBox} from '@utils/drag';
import store from '@store';
import $ from 'jquery';

class Operation extends Component {
  constructor(props) {
    super(props)
    this.state = {
      title: '',
      fstName:'',//首拼
      okText: '',
      borderColor: '',
      okColor: '',
      oKBg: '',
      msg: '',
      type: '',   // type  1: 保存病历
      zIndex:40,
      sex:'3',
      le:'',
      deptId:'',//科室id
      value:'',//科室name
      folder:'',//文件夹
      folderName:'',
      folderNameVal:'未分类文件夹',//选中文件夹名称
      folderId:'',//选中文件夹名称
      folderListShow:false, //文件夹列表展示
      medicalName: '', //保存病历名称
      showValit: false, // 显示校验的文字
      saveVisible: false, //保存病历模态框
      clearVisible:false
    }
    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);
    this.setDeptId = this.setDeptId.bind(this);
    this.setFolderId = this.setFolderId.bind(this);
    this.handleChangeIpt = this.handleChangeIpt.bind(this);
    this.newFolder = this.newFolder.bind(this);
    this.saveNewFolder = this.saveNewFolder.bind(this);
    this.folderManage = this.folderManage.bind(this);
    this.changeTitle = this.changeTitle.bind(this);
    this.closeDiagBox = this.closeDiagBox.bind(this);
    this.spellFst = this.spellFst.bind(this);
    this.hideFolderList = this.hideFolderList.bind(this)
    this.handleMedicalChange = this.handleMedicalChange.bind(this)

    this.makeSureClear = this.makeSureClear.bind(this);
    this.makeSureSave = this.makeSureSave.bind(this);
    
    this.closeSave = this.closeSave.bind(this);
    this.closeClear = this.closeClear.bind(this);
    
    this.$inp = React.createRef()
  }

  // 保存病历  _lcq
  makeSureSave(){
    if (this.state.medicalName.trim() === '') {
      // Notify.info('请输入病历名称')
      this.setState({
        showValit: true
      })
      return
    }
    // // 清除store中 medicalName的值
    // const { clearmedicalName } = this.props
    // clearmedicalName && clearmedicalName()
    // diagShowTmp(false)
    // this.setState({ title: '' })
    // store.dispatch(embedPush({
    //   action: "patientia",
    //   mode: 1
    // }))
    store.dispatch(saveMessage()).then(res => {
      this.setState({
        medicalName: '',
        saveVisible: false,
      })
      store.dispatch(embedPush({
        action: "patientia",
        mode: 1
      }))
      // console.log('保存成功之后推送');
    
    }).catch(err => {
      if (err === '00020001'){

      }
    })
  }

  // 取消编辑病历
  closeSave() {
    this.setState({
      saveVisible: false,
      showValit:false,
      medicalName: ''
      // templateName: ''
    })
  }
  closeClear(){
    this.setState({
      clearVisible: false,
    })
  }
  showPrint() {
    this.setState({
      zIndex:240
    })
    this.props.showPrintPreview()
  }

  closePrint() {
    this.setState({
      zIndex:40
    })
    this.props.closePrintPreview()
    dragBox('previewPrintWrapper','previewPrintStatic','del')
  }

  showPreview() {
    this.setState({
      zIndex:240
    })
    this.props.showPreview()
  }
  
  closePreview() {
    this.setState({
      zIndex:40
    })
    this.props.closePreview()
    dragBox('previewWrapper','previewStatic','del')
  }

  saveAll(type) {
    let keepState = readyKeepHistory();
    // console.log(keepState, '====keepState');
    if(keepState == 1){
        Notify.info('主诉不能为空');
        return;
    }   
    if (keepState == 2) {
      Notify.info('姓名不能为空');
      return;
    }   
    if (keepState == 3) {
      Notify.info('年龄不能为空');
      return;
    }   
    if (keepState == 4) {
      Notify.info('卡号不能为空');
      return;
    }   
    if (keepState == 5) {
      Notify.info('科室不能为空');
      return;
    }   
    if (keepState == 6) {
      Notify.info('医生不能为空');
      return;
    }   
    if (keepState == 7) {
      Notify.info('门诊号不能为空');
      return;
    }   

    if (keepState == 8) {
      Notify.info('年龄不能超过200');
      return;
    }  

    // this.setState({            
    //   type: type,
    //   okText: '保存',
    //   borderColor: '#3B9ED0',
    //   okColor: '#fff',
    //   oKBg: '#3B9ED0',
    //   msg: <div className={style.outBox}><div><span>病历名称：</span><input type="text" placeholder="请输入病历名称" value={this.state.medicalName} onChange={this.handleMedicalChange} autocomplete="off" /> </div></div>
    // })
    // this.props.diagShowTmp(true)
    this.setState({
      saveVisible: true
    })
    this.props.hideAllSearch();
  }

  handleMedicalChange(e){
    if (e.target.value.length > 0) {
      this.setState({
        showValit: false
      })
    }
    const { setmedicalName} = this.props
    this.setState({
      medicalName: e.target.value
    },()=>{
      setmedicalName &&setmedicalName(this.state.medicalName)
    })
  }

  clearAll(type) {
    let baseList = store.getState();
    let jsonData = getAllDataList(baseList);
    let jsonStr = getAllDataStringList(baseList);
    let flg = isAllPartClear(jsonData,jsonStr,baseList);
    const tpVal = $("#templateSearch").val();   //模板是否有搜索条件未清空
    const mdVal = $("#medicalInfoSearch").val();    //知识是否有搜索条件未清空
    if(flg||tpVal||mdVal){
      this.setState({
        clearVisible: true,
      })
      
      // this.props.diagShowTmp(true)
      
    }else{
      Notify.info('当前页面数据已清空');
    }
    
  }
  makeSureClear(){
    this.setState({
      clearVisible: false,
    })
    clearMessages()
  }
  handleInput(e){
    let val = (e.target.value).substring(0,20)
    this.setState({
      title: val
    })
  }
  handleInputFst(e){
    let val = (e.target.value).substring(0,20).replace(/[^a-zA-Z]/g,'')
    $(e.target).val(val)
    this.setState({
      fstName: val
    })
  }
  keypress(event) {
    let e = event?event:window.event;
    if (e.keyCode == 13) {
      this.makeSure()
    }
  }
  newFolder(flg){
    this.props.folderModal(flg)
  }
  folderManage(flg) {
    this.props.folderOrder(flg)
  }
  saveHis(type) {
    const { diagShowTmp,getFloderList,admin } = this.props;
    let baseList = store.getState();
    let jsonStr = getAllDataStringList(baseList);
    let tmpLis = [];
    let flg = isAllClear(jsonStr);
    if(!flg){
      Notify.info('模板数据不能为空');
      return false;
    }
    if(!this.props.admin){
      tmpLis = baseList.tabTemplate.items;
      for(let i = 0;i <tmpLis.length;i++){
        let dataStr = tmpLis[i].preview;
        if(
          filterDataArr(JSON.parse(jsonStr.chief)) == filterDataArr(eval('('+JSON.parse(dataStr).chief+')')) && 
          filterDataArr(JSON.parse(jsonStr.present)) == filterDataArr(eval('('+JSON.parse(dataStr).present+')')) && 
          filterDataArr(JSON.parse(jsonStr.other)) == filterDataArr(eval('('+JSON.parse(dataStr).other+')')) && 
          filterDataArr(JSON.parse(jsonStr.vital)) == filterDataArr(eval('('+JSON.parse(dataStr).vital+')')) &&
          jsonStr.lis == JSON.parse(dataStr).lis &&
          jsonStr.pacs == JSON.parse(dataStr).pacs &&
          jsonStr.diag == JSON.parse(dataStr).diag &&
          jsonStr.advice == JSON.parse(dataStr).advice
        ){
          Notify.info('该模板已保存');
          return false;
        }
      }
    }
    
    this.setState({
      title: '',
      sex:'3',
      type: type,
      okText: '保存',
      borderColor: '#3B9ED0',
      okColor: '#fff',
      oKBg: '#3B9ED0',
      msg: this.changeTitle()
    })
    admin&&getFloderList()//获取文件夹列表
    diagShowTmp(true)
  }
  spellFst(){
    const {diagShowTmp} = this.props
    let tmpFst = pinyin.getCamelChars(this.state.title);
    // console.log(tmpFst.substr(0,1).toUpperCase())
    this.setState({fstName:tmpFst.toUpperCase()})
      // this.$inp.current.vaule = tmpFst
    document.getElementById ('FstInp').value=tmpFst.toUpperCase()
    
  }
  closeSaveModule() {
    const {diagShowTmp} = this.props
    const { type } = this.state;
    if (type == 3){
      diagShowTmp(false)
      this.setState({ title: '',deptId:"",value:"",folderListShow:false,folderNameVal:'未分类文件夹',folderId:'',fstName:'' })
    }
  }
  changeTitle() {
    return <div className={style['box']} onClick={()=>{this.props.handleClearValue(); this.hideFolderList()}}>
      <div className={style['iptWrap']}>
        <div className={style.name}>
          <span className={style.leftName}>模板名称：</span>
          <input className={style['ipt']}
            autocomplete="off"
            placeholder="请输入模板名称"
            type="text"
            maxLength='20'
            onInput={(e) => {
              this.handleInput(e)
            }}
            onPropertyChange={(e) => {  // 兼容ie
              this.handleInput(e)
            }}
            onKeyPress={e => this.keypress(e)}
          />
        </div>
        <div className={`${style.name} ${style.firstname}`}>
          <span className={style.leftName}>模板名首拼：</span>
          <input className={style['ipt']}
            autocomplete="off"
            ref = {this.$inp}
            // value={value}
            id='FstInp'
            placeholder='请输入模板名称首拼'
            type="text"
            maxLength='20'
            onFocus={() =>this.spellFst()}
            onInput={(e) => {
              this.handleInputFst(e)
            }}
            onPropertyChange={(e) => {  // 兼容ie
              this.handleInputFst(e)
            }}
            onKeyPress={e => this.keypress(e)}
          />
        </div>
        <div className={style.male}>
          <span className={style.leftName}>性别归属：</span>
          <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>
          <span style={{paddingRight:0,color:'#777777'}}>(注：错误引用，显示可能有误)</span>
        </div>
        {/* <p>请选择模板性别归属(错误引用，显示可能有误)</p> */}
      </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,saveDataAlls,diagShowTmp ,chronicMagItem,chronicDesease,admin,floderListAdmin} = this.props;
    const { type,deptId,sex,title,fstName,folderId,folderNameVal } = this.state;
    // console.log(type,'======type');
    if (type == 1) {     
      // if (this.state.medicalName === '') {
      //   Notify.info('请输入病历名称')
      //   this.setState({
      //     showValit: true
      //   },()=>{
      //       // console.log(this.state.showValit,'-=-=-=-');
      //   })
      //   return 
      // }
      // // 清除store中 medicalName的值
      // const { clearmedicalName } = this.props
      // clearmedicalName && clearmedicalName()
      // diagShowTmp(false)
      // this.setState({ title: '' })
      // if (type == 1) {
      //   this.setState({
      //     medicalName: ''
      //   })
      // }
      // save();
    } else if (type == 2) {
      // type === 2 清除数据
      diagShowTmp(false);
      this.setState({ title: '' })
      //更新滚动条
      const that = this;
      setTimeout(function(){
        that.context.scrollArea&&that.context.scrollArea.refresh();
      });
      // console.log(1111111111111);
    } else if (type == 3) {
      if (this.state.title.trim() == '') {
        Notify.error('请输入模板名称')
        return;
      }else if(this.state.fstName == ''){
        Notify.error('请输入模板名首拼')
        return;
      }else if(admin&&deptId == ''){
        Notify.error('请选择科室')
        return;
      }
      if(admin){
        let baseList = store.getState();
        let tmpFolder = baseList.tabTemplate.adminItems||[];
        let tmpLis = [];
        for(let k = 0;k < tmpFolder.length;k++){
          let tmpData = tmpFolder[k].templateInfo||[]
          tmpLis = tmpLis.concat(tmpData)
        }
        let jsonStr = getAllDataStringList(baseList);
        for(let i = 0;i <tmpLis.length;i++){
          let dataStr = tmpLis[i].preview;
          if(
            filterDataArr(JSON.parse(jsonStr.chief)) == filterDataArr(eval('('+JSON.parse(dataStr).chief+')')) && 
            filterDataArr(JSON.parse(jsonStr.present)) == filterDataArr(eval('('+JSON.parse(dataStr).present+')')) && 
            filterDataArr(JSON.parse(jsonStr.other)) == filterDataArr(eval('('+JSON.parse(dataStr).other+')')) && 
            filterDataArr(JSON.parse(jsonStr.vital)) == filterDataArr(eval('('+JSON.parse(dataStr).vital+')')) &&
            jsonStr.lis == JSON.parse(dataStr).lis &&
            jsonStr.pacs == JSON.parse(dataStr).pacs &&
            jsonStr.diag == JSON.parse(dataStr).diag &&
            jsonStr.advice == JSON.parse(dataStr).advice&&
            deptId == tmpLis[i].hospitalDeptId
          ){
            Notify.info('该模板已保存');
            return false;
          }
        }
        
        if(folderNameVal=="未分类文件夹") {
          let folderIdNull =  floderListAdmin.find(item =>item.name == "未分类文件夹").id
          saveDataAlls(title,sex,deptId,fstName,folderIdNull,folderNameVal);
        }else {
          saveDataAlls(title,sex,deptId,fstName,folderId,folderNameVal);
        }
        this.setState({
          folderNameVal:'未分类文件夹',
          folderId:'',
          fstName:'',
          deptId:''
        })
      }else{
        saveDataAll(title,sex,fstName);
      }
    }
  }
  closeDiagBox(){
    const { diagShowTmp } = this.props;
    const { type } = this.state;
    if (type == 3){
      this.setState({ title: '',deptId:"",value:"",folderListShow:false,folderNameVal:'未分类文件夹',folderId:'',fstName:''})
    }
    if(type==1){
      this.setState({
        medicalName: ''
      })
    }
    diagShowTmp(false)
  }
  setDeptId(id,name){
    this.props.handleClearValue()
    this.setState({
      deptId :id,
      value:name
    })
  }
  setFolderId(id,name){//文件夹
    this.props.handleClearValue()
    this.setState({
      folderId :id,
      folderNameVal:name,
      folderListShow:false
    })
  }
  hideFolderList(){
    this.setState({
      folderListShow:false
    })
  }
  componentWillReceiveProps(next){//监听滚动事件
    const that = this;
    if(next.winWidth <= 1024){
      $(window).scroll(function(){
        let scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
        let left = -(scrollLeft - 10) +'px';
        that.setState({
          le:left
        })
      })
    }
  }
  handleChangeIpt(val){//搜索科室
    if(val == ''){
      this.setState({
        deptId:'',
      })
      return
    }
    this.setState({
      value:val
    })
  }
  handleFolderShow(){
    const {folderListShow} = this.state
    this.setState({
      folderListShow:!folderListShow
    })
  }
  saveNewFolder(val){//保存文件夹
    const {newFloder} = this.props
    newFloder(val)
  }
  render() {
    const { showPrint, closePrint, showPreview, closePreview,handleChangeIpt,newFolder,folderManage } = this;
    const { visible, preVisible,diagShow } = this.props.print;
    const {winWidth,cancelDelTag,departLis,handleChangeValue,admin,floderListAdmin,folderModalShow,
      floderModal,folderOrderShow,folderOrder,adminItems,patInfo,saveOrderFolder,hideLabel} = this.props;
    const {zIndex,type,le,value,folder,folderListShow} = this.state;
    // console.log(this.state.showValit,this.state.msg,'====================');
    return <div className={style['container']}>
      {/*<span className={style['button']} onClick={showPrint}><img src={printImg} /> 打印病历</span>*/}
      {/* <span className={style['preButton']} onClick={showPreview}><img src={preview} /> 预览</span> */}
      {/* {hideLabel?"":<span className={style['preButton']} onClick={() => { this.saveHis(3) }}><img src={saveHistory} /> 保存病历模板</span>} */}
      {/* {hideLabel?"":<span className={style['preButton']} onClick={cancelDelTag}><img src={cancelTag} /> 还原标签</span>} */}
      <span className={winWidth<=1082?`${style['clearButton']} ${style['saveButton']} ${style['minstyle']}`:`${style['clearButton']} ${style['saveButton']}`} onClick={() => { this.clearAll(2) }}>清除</span>
      <span className={winWidth<=1082?`${style['saveButton']} ${style['minstyle']}`: style['saveButton']} onClick={() => { this.saveAll(1) }}>保存</span>
      {visible?<PrintPreviewContainer visible={visible} onClose={closePrint} />:null}
      {preVisible?<PreviewContainer visible={preVisible} onClose={closePreview} />:null}
      {<ConfirmModal
        visible={this.state.clearVisible}
        confirm={this.makeSureClear}
        close={this.closeClear}
        cancel={this.closeClear}
        okText={"清除"}
        okBorderColor={'red'}
        okColor={'red'}
        oKBg={'#fff'}
      >
        <div className={style.outBox}>
          <span>是否清空所有内容</span>
        </div>
      </ConfirmModal>}


      {<ConfirmModal
        visible={this.state.saveVisible}
        confirm={this.makeSureSave}
        close={this.closeSave}
        cancel={this.closeSave}
        okText={"保存"}
        okBorderColor={'#3B9ED0'}
        okColor={'#fff'}
        oKBg={'#3B9ED0'}
        title={'保存病历'}
        height={200}
      >
        <div className={style.outBox}>
          <div className={style.innerInp}>
            <span>病历名称：</span>
            <input type="text" className={style.innerInput} placeholder="请输入病历名称" value={this.state.medicalName} maxlength={30} onChange={this.handleMedicalChange} autocomplete="off" /> 
          </div>
          {this.state.showValit ? (<div className={style.valit}>请输入病历名称</div>) : null}
        </div>
      </ConfirmModal>}

      {<ConfirmModal
        visible={diagShow}        //改为全局控制
        confirm={() => { this.makeSure() }}
        close={() => { this.closeDiagBox()}}
        cancel={() => {this.closeDiagBox()}}
        okText={this.state.okText}
        height={type==3&admin?365:type==3&!admin?275:200}
        width={type==3?585:300}
        okBorderColor={this.state.borderColor}
        okColor={this.state.okColor}
        oKBg={this.state.oKBg}
        borderBtm={type==3?'1px solid #ccc':null}
        title={type==3?'保存病历模板':type==4?"新建文件夹":type==1?"保存病历":null}
      >
        {this.state.msg}
        {
          admin&&type==3?<div className={style.addList} onClick={()=>{this.props.handleClearValue()}}>
            <div className={style.department} onClick={()=>{this.hideFolderList()}}>
              <span className={style.leftName}>科室归属：</span>
                <Search handleChangeValue={handleChangeValue} handleChangeIpt={handleChangeIpt} handleClearValue={this.props.handleClearValue}  value={value} visible={true} zIndex={11}>
                {
                  departLis.length>0&&value&&<ul className={style.departLis}>
                    {
                      departLis.map((item,idx)=>{
                        return <li onClick={()=>this.setDeptId(item.id,item.conceptDeptName)}>
                          {item.conceptDeptName}
                        </li>
                      })
                    }
                  </ul>
                }
                </Search>
              <span style={{paddingRight:0,color:'#777777'}}>(支持汉字关键字搜索)</span>
          </div>
            <div className={style.department}>
              <span className={style.leftName}>存储为：</span>
                <div  className={style.selectFolder} onClick={(e) => {
                      this.handleFolderShow(e)
                    }}>
                  <input className={style.selectFolderIpt}
                    autocomplete="off"
                    type="text"
                    maxLength='20'
                    readOnly
                    value={this.state.folderNameVal}
                    
                  />
                  <img src={slideDown} alt=""/>
                </div>
                {
                  floderListAdmin.length>0&&folderListShow&&<ul className={`${style.departLis} ${style.departLisFolder}`}>
                    {
                      floderListAdmin.map((item,idx)=>{
                        return <li onClick={()=>this.setFolderId(item.id,item.name)}>
                          {item.name}
                        </li>
                      })
                    }
                  </ul>
                }
              <span className={style.newFolder} onClick={()=>newFolder(true)}>新建文件夹</span>
              <span className={style.mangerFolder} onClick={()=>folderManage(true)}>管理文件夹</span>
          </div>
          </div>:null
        }
      </ConfirmModal>
      }
      {/* 保存病历 */}



      <FolderName 
        folderModalShow={folderModalShow}
        floderModal={floderModal}
        newFolder={newFolder}
        saveNewFolder={this.saveNewFolder}
        title='新建文件夹'></FolderName>
        <FolderOrder
        folderOrderShow = {folderOrderShow}
        folderOrder = {folderOrder}
        folderManage={folderManage}
        adminItems = {adminItems}
        saveOrderFolder = {saveOrderFolder}
        patInfo={patInfo}
        title = '管理文件夹'>
        </FolderOrder>
    </div>;
  }
}

Operation.contextTypes = {
  scrollArea: React.PropTypes.object
};
export default Operation;