import React from 'react';
import { SearchOption, Calendar, ConfirmModal, Notify, Add ,DelToast} from '@commonComp';
import styles from './index.less';
import $ from 'jquery';
import Textarea from './Textarea';
import { getPageCoordinate,getCurrentDate,setPosition } from '@utils/tools';
import ScrollArea from 'react-scrollbar';

class AddAssistCheck extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      date: false,
      dateTime: "",
      active: '',
      visible: false,
      pageTop:'',
      id: null,
      activeName:''
    }
    this.handleShowDate = this.handleShowDate.bind(this)
    this.getSearchList = this.getSearchList.bind(this)
    this.getAssistLabel = this.getAssistLabel.bind(this)
    this.handleDelClick = this.handleDelClick.bind(this)
    this.delConfirm = this.delConfirm.bind(this)
    this.handleCancel = this.handleCancel.bind(this)
    this.timeSure = this.timeSure.bind(this)
  }
  
  componentDidMount() {
    $(document).click((event) => {
      let _con = $('#searchWrapAssist');   // 设置目标区域
      let _cons = $('#datePick');   // 设置目标区域
      // let _conClick = $('#assistCheck');   // 点击的按钮
      let _del = document.getElementById("delBox");   // 删除弹窗
      let _close = document.getElementById("assiClose");   // 删除icon
      let _closeTil = $('#delTit')[0];   // 弹窗标题
      if(!this.isBar) {//onMousedown的目标为滚动条时，子项弹窗不关闭)
        if (_con && searchWrapAssist != event.target && !_con.is(event.target) && _con.has(event.target).length === 0) { // Mark 1
          if (this.state.show) {
            this.props.setHighter(48)
          }
          this.setState({show: false});
        }
        if (!_cons.is(event.target) && _cons.has(event.target).length === 0 || event.target.isEqualNode(_close)) { // Mark 1
          this.setState({date: false});
        }
        if($(event.target).attr("contenteditable")||event.target.textContent == '报告描述或意见'){
          this.setState({date: false});
        }
      if(_del){
        if($(event.target).attr('id') != 'assiClose' &&!event.target.isEqualNode(_close) && !event.target.isEqualNode(_del)  && event.target.parentNode != _del && !event.target.isEqualNode(_closeTil)){
          this.setState({
            visible: false,
            id: null,
            activeName:''
          })
        }
      }
    }
    });
    const that = this;
    document.addEventListener('mousedown',function(e){
      //onMousedown的目标为滚动条时，标签填写单不关闭
      if(e.target.className=='scrollbar'){
        that.isBar = true;
      }else{
        that.isBar = false;
      }
    });
    getCurrentDate(1);
  }

  handleDelClick(id,item) {
    this.setState({
      visible: true,
      id: id,
      activeName:item.name
    })
  }

  delConfirm(type) {
    const { handleDelAssist, handlePush } = this.props;
    const { id,activeName } = this.state;
    handleDelAssist && handleDelAssist(id,activeName,type);
    handlePush && handlePush();           //右侧推送
    this.setState({
      visible: false,
      id: null,
      activeName:''
    })
    Notify.success("删除成功");
  }

  handleCancel() {
    this.setState({
      visible: false,
      id: null,
      activeName:''
    })
  }

  handleSearchShow(e) {
    let tmpShow = this.state.show;
    this.setState({ show: !tmpShow,pageTop:getPageCoordinate(e).boxTop })
    // e.stopPropagation(); 
    if(tmpShow){
      this.props.setHighter(48)
    }else{
      setPosition(e,"#searchOption",this.props.setHighter)
    }
  }
  handleShowDate(idx) {
    this.setState({
      date: !this.state.date,
      active: idx
    })
  }

  getSearchList(list) {      //搜索列表
    const { handleSign } = this.props;
    const contStyle={
      opacity:'0.4',
      right:'0',
      top:'1px',
      zIndex:'15',
      width:'14px',
      background:'#f1f1f1'};
    const barStyle={background:'#777',width:'100%'};
    return <ScrollArea speed={0.8}
                       horizontal={false}
                       stopScrollPropagation={list.length>6?true:false}
                       style={{height:'225px'}}
                       className={styles["area"]}
                       verticalContainerStyle={contStyle}
                       verticalScrollbarStyle={barStyle}
                       contentClassName="content">
      <ul className={styles.searchLiUl}>
      {
        list && list.map((item, idx) => {
          return <li key={item.id}
            className={styles.searchLi}
            title={(item.name == item.retrievalName || !item.retrievalName) ? null : '(' + item.retrievalName + ')'}
            onClick={() => {
              this.props.setHighter(48)
              handleSign(item.conceptId,idx,'search');
              this.setState({ show: false })
            }}
          >
            {item.name}{(item.name == item.retrievalName || !item.retrievalName) ? null : '(' + item.retrievalName + ')'}
          </li>
        })
      }
      </ul></ScrollArea>;
  }
  getCommonList() {      //常用列表
    const { handleSign,assistList } = this.props;
    return <ul className={styles.searchLiUl}>
      {
        assistList && assistList.map((item, idx) => {
          return <li key={item.id}
            className={styles.searchLi}
            title={item.name}
            onClick={() => {
              this.props.setHighter(48)
              handleSign(item.conceptId, idx,'common');
              this.setState({ show: false })
            }}
          >
            {item.name}
          </li>
        })
      }
    </ul>
  }
  handleChangeDate(){}
  timeSure(date,idx){
    this.props.handleChangeDate(date,idx)
    this.setState({ date: false })
  }

  getAssistLabel() {
    const { assistLabel,checkedListImport, handleChangeAssistValue, handleChangeDate, isRead, handlePush, winWidth,getInfomation,assistList } = this.props;
    const { visible,activeName,id,date } = this.state;
    //出现滚动条时阻止滚动冒泡，未出现时不阻止，否则外部滚动条滚不动
    const showedBar = $("#datePick .scrollbar-container").length===1;
    const contStyle={
      opacity:'0.4',
      right:'0',
      top:'1px',
      zIndex:'1',
      width:'8px',
      background:'#f1f1f1'};
    const barStyle={background:'#777',width:'100%'};
    return <React.Fragment>
      {
        checkedListImport.map((part,index)=>{
          return <ul className={`${styles.labelWrap} ${styles.labelWrapSpec} ${styles.labelWrapSpecs}`}>
            {
              part.map((item, idx) => {
                return (<li className={`${styles.assistLists} ${styles.clearfix}`}>
                  <span className={styles.assistName} style={{ width: winWidth < 1200 ? '120px' : 'auto' }}>
                    <span className={styles.tagSpan}>
                      {item.name}：
                      <span className={styles.imgInfo} title='点击i图标可查看详细说明' onClick={()=>getInfomation({name: item.name, position: 1, type: 6})}></span>
                    </span>
                  </span>
                  <div className={styles.textareaWrap}>
                    <ScrollArea speed={0.8}
                                horizontal={false}
                                stopScrollPropagation={showedBar?true:false}
                                style={{maxHeight:'100px'}}
                                className={styles["area"]}
                                verticalContainerStyle={contStyle}
                                verticalScrollbarStyle={barStyle}
                                contentClassName="content">
                      <Textarea value={item.value} disabled={item.disabled} handlePush={handlePush} isRead={isRead} handleChangeAssistValue={handleChangeAssistValue} idx={idx}></Textarea>
                    </ScrollArea>
                  </div>
                  <div className={styles.pointerFinger}>
                    <p>报告日期：<span>{item.time || this.state.dateTime}</span></p>
                  </div>
                </li>)
              })
            }
            <DelToast show={index==id&&part.name==activeName?visible:false}
                      name="该导入项"
                      right={'-34px'}
                      top={'22px'}
                      cancel={this.handleCancel}
                      confirm={()=>this.delConfirm(0)}/>
            <span className={`${styles.closeIcon} ${styles.closeIcons}`} id="assiClose" onClick={()=>{ this.handleDelClick(index,part)}}></span>
          </ul>
        })
      }

      <ul className={styles.labelWrap} id="datePick">
        {
          assistLabel.map((item, idx) => {
            let staticTime = {}
            if(item.time){
              let tmp1 = (item.time).split(' ')[0].split('-')
              let tmp2 = (item.time).split(' ').length>1&&(item.time).split(' ')[1].split(':')
              staticTime = {
                year: tmp1[0]-0,
                month: tmp1[1]-0,
                day: tmp1[2]-0,
                hour: tmp2[0],
                minute: tmp2[1],
                second: tmp2[2]
              }
            }
            return (item.disabled?null:<li className={`${styles.assistLists} ${styles.clearfix}`}>
              <span className={styles.assistName} style={{ width: winWidth < 1200 ? '120px' : 'auto' }}>
                <span className={styles.tagSpan}>
                  {item.name}：
                  <span className={styles.imgInfo} title='点击i图标可查看详细说明' onClick={()=>getInfomation({name: item.name, position: 1, type: 6})}></span>
                </span>
              </span>
              <div className={styles.textareaWrap}>
                <ScrollArea speed={0.8}
                            horizontal={false}
                            stopScrollPropagation={showedBar?true:false}
                            style={{maxHeight:'100px'}}
                            className={styles["area"]}
                            verticalContainerStyle={contStyle}
                            verticalScrollbarStyle={barStyle}
                            contentClassName="content">
                <Textarea value={item.value} disabled={item.disabled} handlePush={handlePush} isRead={isRead} handleChangeAssistValue={handleChangeAssistValue} idx={idx}></Textarea>
                </ScrollArea>
              </div>
              <div className={styles.pointerFinger}>
                <p onClick={() => this.handleShowDate(idx)}>报告日期：<span>{item.time || this.state.dateTime}</span></p>
                <i onClick={() => this.handleShowDate(idx)}></i>
                {/*<a href="javascript:void(0);" onClick={() => { this.handleDelClick(idx,item) }}><img src={close} alt="" /></a>*/}
                <span className={styles.closeIcon} id="assiClose" onClick={() => { this.handleDelClick(idx,item) }}></span>
                {
                  this.state.date && idx == this.state.active ?<Calendar timeLis={staticTime} isShow={true} timeSure={(date)=>this.timeSure(date,idx)} needTime={true} sure={true} handleChange={(info) => { this.handleChangeDate(info, idx) }} top={30}></Calendar>:null
                }
              </div>
              <DelToast show={idx==id&&item.name==activeName?visible:false}
                  name={activeName}
                  right={'-34px'}
                  top={'40px'}
                  cancel={this.handleCancel}
                  confirm={()=>this.delConfirm(1)}/>
              {/* {
                id == null?null:<DelToast show={idx==id&&item.name==activeName?visible:false}
                  name={activeName}
                  cancel={this.handleCancel}
                  confirm={this.delConfirm}/>
              } */}
            </li>)
          })
        }
      </ul>
    </React.Fragment> 
  }
  render() {
    const { handleChangeValue, list,assistVal,windowHeight,assistList, refreshScroller } = this.props;
    const { visible,pageTop } = this.state;
    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.wrapper}>
        {this.getAssistLabel()}
        <div id="searchWrapAssist" style={{ position: "relative", clear: 'both' }}>
          <Add showText="添加辅检项" handleClick={(e) => this.handleSearchShow(e)} id="assistCheck" />
          {this.state.show ? <SearchOption windowHeight={windowHeight} refreshScroller={refreshScroller }  pageTop={pageTop} height={280} handleChangeValue={handleChangeValue} visible={true}>
            {list && list.length>0?this.getSearchList(list):(assistVal == ''?'':<p style={{padding:'5px 30px',color:'#bfbfbf'}}>暂无筛选项</p>)}
            {
              (list && list.length>0) || (assistVal != '') || (assistList&&assistList.length==0)?'':<div>
                <p style={{padding:'5px 30px',color:'#bfbfbf'}}>常用辅检项</p>
                <ScrollArea speed={0.8}
                            horizontal={false}
                            stopScrollPropagation={assistList.length>6?true:false}
                            style={{height:'225px'}}
                            className={styles["area"]}
                            verticalContainerStyle={contStyle}
                            verticalScrollbarStyle={barStyle}
                            contentClassName="content">
                {
                  this.getCommonList()
                }
                </ScrollArea>
              </div>
            }
          </SearchOption> : ''}
        </div>
      </div>
    )
  }
}

export default AddAssistCheck;