import React from 'react';
import PropTypes from 'prop-types';
import store from '@store';
import styles from './index.less';
import ReactDom from "react-dom";
import sort from "./img/sort.png"
import close from "./img/close.png";
import PreviewBody from '@components/PreviewBody';
import Empty from '@components/Empty'
import { pushAllDataList,didPushParamChange } from '@utils/tools';
// import { dragBox } from '@utils/drag';
import { initItemList, setInitHistory } from '@store/async-actions/historyTemplates';
import HistoryCases from '@containers/HistoryCases';
import $ from 'jquery';
import { ConfirmModal } from '@commonComp';
import {showHistory} from "@store/actions/historyTemplates";
import { SET_READ_MODE } from "@store/types/typeConfig";
import {billing} from '@store/async-actions/pushMessage';
import { getHistempDetail, asyncUpdateByIdUsNames, asyncCancelTemplateInfos} from '@store/async-actions/historyTemplates';
import edit from '../../../common/images/icon_edit_default@2x.png';
import editHover from '../../../common/images/icon_edit_hover@2x.png';
import del from '../../../common/images/icon_del_default@2x.png';
import delHover from '../../../common/images/icon_del_hover@2x.png';
import Notify from '@commonComp/Notify';
import ScrollArea from 'react-scrollbar';
class HistoryCaseContainer extends React.Component {
    constructor(props){
        super(props);
        this.state = {
          activeHis:{},//预览数据
          activeId:'0',
          dataStr:[],
          dataJson:{},
          visible:false,
          delVisible: false,
          editVisible: false,
          templateName: '', // 病历名称
          historyCase: [],
          currentIndex:-1,  // 显示编辑/删除图标
          delId: '', //删除病历id
          editId: '', //编辑病历id
          activeIndex: -1,  //字体显示蓝色高亮index
          showEditIcon: false,
          showDelIcon: false,
          desc: true // 正序/逆序
        }
        this.handleCaseClick=this.handleCaseClick.bind(this)
        this.handleQuoteClick=this.handleQuoteClick.bind(this)
        this.handleDelQuoteClick = this.handleDelQuoteClick.bind(this)
        this.handleEditQuoteClick = this.handleEditQuoteClick.bind(this)
        this.close = this.close.bind(this);
        this.closeDel = this.closeDel.bind(this);
        this.closeEdit = this.closeEdit.bind(this);
        this.makeSure = this.makeSure.bind(this);
        this.makeSureDel = this.makeSureDel.bind(this);
        this.makeSureEdit = this.makeSureEdit.bind(this);
        this.handleChange = this.handleChange.bind(this);
      this.handleSortClick = this.handleSortClick.bind(this);

      this.$scrollRef = React.createRef();
    }
    componentDidMount(){
      const {items} = this.props
      // dragBox('hisWrapMove','closeHis','add')
      setTimeout(() => {
        this.handleCaseClick(0, items[0])
      }, 50);      
      this.setState({
        visible:false,
      })
    }


    // 操作后获取获取列表数据
    getTemplatePageAlls(val) {
      return new Promise((resolve,reject)=>{
        initItemList(val).then(res => {
          const result = res.data
          if (result.code == 0 && result.data) {
            store.dispatch(setInitHistory(result.data));
            resolve('ok')
          }
        })       
      })
    }


    // 点击当前的历史病历
    handleCaseClick(idx,val) {
      const { items } = this.props;
      let tmpItems = []
      $("#hislistLeft li").eq(idx).css({
        background: '#fff'
      }).siblings().css({
        background: '#d2d1d1'
      })
      if (items.length == 0) {
        return
      } else {
        tmpItems = items[idx]
      }
      this.setState({
        activeId: idx,
        activeHis: tmpItems,
        dataStr: JSON.parse(tmpItems.preview)||[],
        activeIndex: idx
      })
    }
    // 确认引用选中病历
    makeSure(){
        const {activeHis} = this.state;
        // console.log(activeHis,'activeHis');
        this.setState({visible:false});
        store.dispatch(showHistory(false));
        //store.dispatch({type: CONFIRM_TYPE, confirmType: activeHis.sign});
        //store.dispatch({type: SET_READ_MODE, readMode: activeHis.sign});
        store.dispatch(getHistempDetail(activeHis));  // 获取引用数据
        const {handleQuoteClick} = this.props;
        handleQuoteClick && handleQuoteClick(activeHis);
        // dragBox('hisWrapMove','closeHis','del');
    }
    //确认删除病历
    makeSureDel(){
      const { delId } = this.state
      store.dispatch(asyncCancelTemplateInfos(delId)).then(res => {
        if (res.data.code === '0') {
          Notify.success('病历删除成功');
          this.setState({
            delVisible: false
          })
          // 重新渲染列表
          this.getTemplatePageAlls().then(res=>{
            if(res === 'ok'){
              const { items } = this.props;
              if(items.length ===0) {
                this.setState({
                  activeHis: {}
                })
                store.dispatch(showHistory(false));
                return
              }
              this.handleCaseClick(0, items[0])
              // this.$scrollRef.scrollArea.refresh();
              // this.context.scrollArea.scrollYTo(40);
              // console.log(this.$scrollRef,'this.$scrollRef');
              // console.log(this.context,'this.context');
              this.forceUpdate()
            }
          })
        }
      }).catch(err => {
        Notify.info(err.msg);
      })

    }

    // 取消删除病历
    closeDel(){
      this.setState({
        delVisible: false
      })
    }
    // 显示删除确认框
    handleDelQuoteClick(e, val, idx) {
      e.stopPropagation()
      this.setState({
        delVisible: true,
        delId: val.id
      })
    }

    // 确认编辑病历
    makeSureEdit(){
      const { editId, templateName} = this.state
      if (templateName === '') {
        Notify.info('请输入病历名称')
        return
      }
      store.dispatch(asyncUpdateByIdUsNames(editId, templateName)).then(res=>{
        if (res.data.code === '0'){
          Notify.success('病历修改成功');
          this.setState({
            editVisible : false
          })
          // 重新渲染列表
          this.getTemplatePageAlls()
        }
      }).catch(err =>{
        Notify.info(err.msg);
      })
    }

    // 取消编辑病历
    closeEdit() {
      this.setState({
        editVisible: false,
        templateName: ''
      })
    }
    // 显示编辑确认框
    handleEditQuoteClick(e, val, idx) {
      // console.log(val,'显示编辑确认框');
      e.stopPropagation()
      this.setState({
        editVisible: true,
        editId: val.id,
        templateName: val.name
      })
    }

    close(){
      this.setState({
        visible:false
      })
    }

    // 引用,右侧文本数据同步渲染
    handleQuoteClick(e,val,idx){
      this.setState({
        visible:true,
        activeId:idx,
        activeHis:val,
        dataStr: JSON.parse(val.preview) || [],
      })
      document.body.scrollTop = document.documentElement.scrollTop = 0
    }
    // 修改模板名称 input的值
    handleChange(e){
      this.setState({
        templateName: e.target.value
      })
    }

    // 处理鼠标移入
    handleMouseEnterLi(idx){
      // console.log('处理鼠标移入li');
      this.setState({
        currentIndex: idx
      })
    }

    // 处理鼠标移除
    handleMouseLeaveLi(idx){
      // console.log('处理鼠标移除li');
      this.setState({
        currentIndex : -1
      })
    }

      // 处理鼠标移入编辑按钮
    handleMouseEnterEdit(idx) {

        this.setState({
          showEditIcon: true
        })
      }

      // 处理鼠标移出编辑按钮
    handleMouseLeaveEdit(idx) {

      this.setState({
        showEditIcon: false
      })
    }

  // 处理鼠标移入删除按钮
  handleMouseEnterDel(idx) {

    this.setState({
      showDelIcon: true
    })
  }

  // 处理鼠标移出删除按钮
  handleMouseLeaveDel(idx) {
    this.setState({
      showDelIcon: false
    })
  }

    // 排序
  handleSortClick(){
    this.setState({
      desc: !this.state.desc
    },()=>{         
        let desc = this.state.desc ? 'up' : 'down'
        this.getTemplatePageAlls(desc).then(res => {
          if (res === 'ok') {
            const { items } = this.props;
            if (items.length === 0) {
              this.setState({
                activeHis: {}
              })
              store.dispatch(showHistory(false));
              return
            }
            this.handleCaseClick(0, items[0])
          }
        })
    })
  }

  componentDidUpdate() {  // 刷新组件
    // console.log(this.$scrollRef.current.scrollTop);
    // console.log(this.$scrollRef);
    // this.$scrollRef.current.scrollTop = this.$scrollRef.current.scrollHeight;

  }

    render(){
        const { items,handleSortClick,showHistoryBox,preInfo } = this.props;
        const { activeHis, visible, dataJson, dataStr, delVisible, editVisible, historyCase, currentIndex, activeIndex } = this.state;     
        const getAllDataStringList = (dataStr) =>{           //获取所有模块文本的数据
            let jsonDataString = {};
            jsonDataString.lis = {};
            jsonDataString.chief = dataStr[0] && dataStr[0].content || '';      //主诉
            jsonDataString.present = dataStr[1] &&dataStr[1].content || '';     //现病史
            jsonDataString.pastHistory = dataStr[2] &&dataStr[2].content || '';     
            jsonDataString.personalHistory = dataStr[3] &&dataStr[3].content || '';    
            jsonDataString.familyHistory = dataStr[4] &&dataStr[4].content || '';  
            jsonDataString.marriageHistory = dataStr[5] &&dataStr[5].content || '';   
            jsonDataString.menstruationHistory = dataStr[6] && dataStr[6].content || '';      
            jsonDataString.vital = dataStr[7] && dataStr[7].content || '';    //查体
            jsonDataString.lis = dataStr[8] && dataStr[8].content || '';      //检验导入填写
            jsonDataString.pacs = dataStr[9] && dataStr[9].content || '';     //检查
            jsonDataString.diag = dataStr[10] &&dataStr[10].content || '';      //诊断
            jsonDataString.advice = dataStr[11] && dataStr[11].content || '';       //医嘱
            return jsonDataString;
        }
      const contStyle = {
        opacity: '0.4',
        right: '0',
        top: '1px',
        zIndex: '15',
        width: '14px',
        background: '#f1f1f1'
      };
      const barStyle = { background: '#777', width: '100%' };
        return (
            <div className={styles.mainHistory} id="hisWrapMove">
                <div className={styles.mainTop}>
                  <div className={`${styles.closeHis} drag-title`} id="closeHis"></div>
                  <img className={styles.close} src={close} alt="关闭历史病历" onClick={showHistoryBox} />
                </div>
                <div className={styles.mainHistoryLeft}>
                    <div className={styles.title}>
                        <span className={styles.his}>历史病历</span>
                        <span className={styles.sort} onClick={this.handleSortClick}>排序 <img src={sort} alt="排序"/></span>
                    </div>
                    <div className={styles.lists}>
                        <ul id="hislistLeft" style={{ overflow:'auto' }} >
                            {(items && items.length > 0) ? items.map((val,idx)=>{                                    
                              return <li key={val.id} onClick={() => { this.handleCaseClick(idx, val) }} onMouseEnter={() => this.handleMouseEnterLi(idx)} onMouseLeave={() => this.handleMouseLeaveLi(idx)}>
                                         <div className={styles.itemLeft}>
                                           <div className={styles.historyTop}>
                                           <span title={val.name} className={activeIndex === idx ? styles.itemNameActive :styles.itemName}>{val.name}</span>
                                           {currentIndex === idx && (
                                              <div className={styles.edit} onClick={(e) => { this.handleEditQuoteClick(e, val, idx) }} onMouseEnter={() => this.handleMouseEnterEdit(idx)} onMouseLeave={() => this.handleMouseLeaveEdit(idx)}>
                                               <img src={ this.state.showEditIcon ? editHover :edit} />
                                              </div>)}
                                         </div>
                                         <div className={activeIndex === idx ? styles.timeActive : styles.time}>{val.inquiryDate}</div>
                                          
                                         </div>
                                         <div className={styles.itemRight}>
                                                                                   
                                          <button className={styles.quote} onClick={(e) => { this.handleQuoteClick(e, val, idx) }}>引 用</button>

                                          {currentIndex === idx && (
                                            <div className={styles.del} onClick={(e) => { this.handleDelQuoteClick(e, val, idx) }} onMouseEnter={() => this.handleMouseEnterDel(idx)} onMouseLeave={() => this.handleMouseLeaveDel(idx)}>
                                              <img src={this.state.showDelIcon?delHover :del} />
                                            </div>
                                          )} 
                                        </div>
                                    </li>
                                }):<Empty message={'无历史病历'}></Empty>
                            }
                        </ul>
                    </div>
                </div>
                <div className={styles.mainHistoryRight}>
                    {
                        activeHis == undefined || JSON.stringify(activeHis) == "{}" ? null :
                        <PreviewBody
                            preInfo={preInfo}
                            showHistoryCases={this.props.showHistoryCases}
                            dataJson={dataJson}
                            baseObj={activeHis}
                            dataStr={dataStr.length > 0 ? getAllDataStringList(dataStr) : []}
                            show={false}
                            flg={true}
                            showAssessBtn={true}
                        ></PreviewBody>
                    }
                </div>
                
                <ConfirmModal
                    visible={visible}
                    confirm={this.makeSure}
                    close={this.close}
                    cancel={this.close}
                    okText={"引用"}
                    okBorderColor={'#3B9ED0'}
                    okColor={'#fff'}
                    oKBg={'#3B9ED0'}
                >
                    <p className={styles['center']}>确认引用该病历？</p>
                </ConfirmModal>

                <ConfirmModal
                  visible={delVisible}
                  confirm={this.makeSureDel}
                  close={this.closeDel}
                  cancel={this.closeDel}
                  okText={"删除"}
                  okBorderColor={'#3B9ED0'}
                  okColor={'#fff'}
                  oKBg={'#3B9ED0'}
                    
                >
                    <p className={styles['center']}>确定删除病历？</p>
                </ConfirmModal>

                <ConfirmModal
                  visible={editVisible}
                  confirm={this.makeSureEdit}
                  close={this.closeEdit}
                  cancel={this.closeEdit}
                  okText={"保存"}
                  okBorderColor={'#3B9ED0'}
                  okColor={'#fff'}
                  oKBg={'#3B9ED0'}
                  title={'编辑病历名称'}
                  height={200}
                >                  
                    <div className={styles.outBox}>
                      <span>病历名称：</span>
                      <input type="text" placeholder="请输入病历名称" value={this.state.templateName} onChange={this.handleChange} autocomplete="off"/>
                    </div>
                </ConfirmModal>
            </div>
        )
    }
}

export default HistoryCaseContainer;