import React from 'react';
import { SearchOption, Calendar, ConfirmModal, Notify, Add ,DelToast} from '@commonComp';
import styles from './index.less';
import config from '@config/index';
import $ from 'jquery';
import Textarea from './Textarea';
import AssistName from './AssistName';
import { getPageCoordinate,getCurrentDate,setPosition, setFontColorSize } 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,
      stimer: 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 ($(event.target).attr('id')=='searchWrapAssist'||_con && _con != 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)&&!_conClick && _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;
    $(".TextareaRsize").css({marginTop:0});
    handleDelAssist && handleDelAssist(id,activeName,type);
    handlePush && handlePush({mode:9});           //右侧推送
    this.setState({
      visible: false,
      id: null,
      activeName:''
    })
    Notify.success("删除成功");
  }

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

  handleSearchShow(e) {
    const { handlePush } = this.props;
    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)
      handlePush && handlePush({mode:9});           //右侧推送
    }
  }
  handleShowDate(idx) {
    this.setState({
      date: !this.state.date,
      active: idx
    })
  }
  handleSign(item,idx){
    const { handleSign,handlePush } = this.props;
    handleSign(item,idx)
    handlePush && handlePush({mode:8});       //右侧推送
  }

  getSearchList(list) {      //搜索列表
    const contStyle={
      opacity:'0.4',
      right:'0',
      top:'1px',
      zIndex:'15',
      width:'14px',
      background:'#f1f1f1'};
    const barStyle={background:'#777',width:'100%'};
    return <ul className={`${styles.searchLiUl} ${styles.assistListUl}`} style={{height:'205px',width:'412px',overflow:'auto'}}>
      {
        list && list.map((item, idx) => {
          return <li key={item.id}
            className={styles.searchLi}
            title={item.name}
            onClick={() => {
              this.props.setHighter(96)
              this.handleSign(item,'search');
              this.setState({ show: false })
            }}
          >
            {item.name}
          </li>
        })
      }
      </ul>;
  }
  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)
              this.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 })
  }
  setEdit(e){
    // $('.canEdit').blur().attr('disabled','disabled')
    $(e.target).removeAttr('disabled').focus()
  }
  handleBlur(){
    // const {handlePush} = this.props;
    $('.canEdit').attr('disabled','disabled')
    // handlePush && handlePush({mode:8});       //右侧推送
  }
  handleInput(e,item,idx){
    const {setTipValue,handlePush} = this.props
    setTipValue(item,e.target.value,idx)
    //右侧推送--延时推送
    const stimer = this.state.timer;
    clearTimeout(stimer);
    let timer = setTimeout(function(){
      handlePush&&handlePush({mode:9});
      clearTimeout(stimer);
    },config.delayPushTime);
    this.setState({timer})
  }
  handleFocus(){
    const {handlePush} = this.props;
    handlePush&&handlePush({mode:9});
  }
  getAssistLabel() {
    const { assistLabel,checkedListImport, handleChangeAssistValue,checkOnOff, 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>
      <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':(winWidth-987)+'px' }}> */}
              {/* <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> */}
              <AssistName item={item} idx={idx} checkOnOff={checkOnOff} name={item.name} winWidth={winWidth} handlePush={handlePush} getInfomation={getInfomation}></AssistName>
              <div className={`${styles.textareaWrap} ${setFontColorSize(2,1)}`}>
                <ScrollArea speed={0.8}
                            horizontal={false}
                            stopScrollPropagation={showedBar?true:false}
                            style={{maxHeight:'100px'}}
                            className={styles["area"]}
                            verticalContainerStyle={contStyle}
                            verticalScrollbarStyle={barStyle}
                            contentClassName="content TextareaRsize">
                <Textarea value={item.value} disabled={item.disabled} handlePush={handlePush} isRead={isRead} handleChangeAssistValue={handleChangeAssistValue} idx={idx}></Textarea>
                </ScrollArea>
              </div>
              <div className={`${styles.pointerFinger} ${setFontColorSize(2,2)}`}>
                {/* <p>报告日期： */}
                <p>
                  <span>
                  <input type="text" 
                      class="canEdit"
                      // onDoubleClick={(e)=>this.setEdit(e)}
                      style={'#333'}
                      placeholder='时间'
                      autoComplete="off"
                      value={item.time}
                      onFocus={()=>{this.handleFocus()}}
                      onInput={(e)=>{this.handleInput(e,item,idx)}}
                      // onBlur={()=>{this.handleBlur()}}
                      />
                </span>
                </p>
                <span className={styles.closeIcon} id="assiClose" onClick={() => { this.handleDelClick(idx,item) }}></span>
              </div>
              <DelToast show={idx==id&&item.name==activeName?visible:false}
                  name={activeName}
                  right={'-40px'}
                  top={'50px'}
                  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:'42px 30px',color:'#bfbfbf'}}>暂无筛选项</p>)}
            {/* {
              (list && list.length>0) || (assistVal != '') || (assistList&&assistList.length==0)?'':<div>
                <p style={{padding:'5px 30px',color:'#bfbfbf'}}>常用检查项</p>
                {assistList.length>6?<ScrollArea speed={0.8}
                            horizontal={false}
                            stopScrollPropagation={true}
                            style={{height:'225px'}}
                            className={styles["area"]}
                            verticalContainerStyle={contStyle}
                            verticalScrollbarStyle={barStyle}
                            contentClassName="content">
                {
                  this.getCommonList()
                }
                </ScrollArea>:this.getCommonList()}
              </div>
            } */}
          </SearchOption> : ''}
        </div>
      </div>
    )
  }
}

export default AddAssistCheck;