import PropTypes from "prop-types"
import React from "react"
import style from "./index.less"
import TemplateItem from './TemplateItem'
import check_circle from './TemplateItem/img/check-circle.png';
import delIcon from '@common/images/del_nor.png';
import check_right from './TemplateItem/img/check-right.png';
import tempTip from './TemplateItem/img/tempTip.png';
import tempTrd from './TemplateItem/img/tempTrd.png';
import tmpAllCircle from './TemplateItem/img/tmpAllCircle.png';
import tmpAllRight from './TemplateItem/img/tmpAllRight.png';
import floderR from './TemplateItem/img/floderR.png';
import floderD from './TemplateItem/img/floderD.png';
import Empty from '@components/Empty';
import $ from 'jquery';
import store from '@store';
import { initCommonItemList,findTemplateNorms,getFloderListAll } from '@store/async-actions/tabTemplate';
import { windowEventHandler,getWindowInnerHeight } from '@utils/tools'

class TemplateItems extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            msg:'还没有保存模板',
            val:'',
            height:'',
            showTipContent:false,
            hasSearch: false,
            showIndex: 0
        }
        this.$cont = React.createRef();
        this.$conts = React.createRef();
        this.$search = React.createRef();
        this.genItems = this.genItems.bind(this);
        this.templateSearch = this.templateSearch.bind(this);
        this.handleEnter = this.handleEnter.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.clear = this.clear.bind(this);
        this.showTipContent = this.showTipContent.bind(this);
        this.getFloderLis = this.getFloderLis.bind(this);
        this.whichTemp = this.whichTemp.bind(this);
    }  
    componentDidMount(){
        const height = getWindowInnerHeight()-195;
        this.setState({
            height:height
        })
        windowEventHandler('resize', ()=>{
            if(this.$conts.current){
                const height = getWindowInnerHeight()-195;
                this.setState({
                    height:height
                })
            }
        });
        $(document).click((event) => {
            let _del = $('#floderAction')[0];       // 弹窗  
            let _dels = $(event.target).attr("id");       // 触发弹窗列表  
            if (_del) {//onMousedown的目标为滚动条时，删除弹窗不关闭
                if (!event.target.isEqualNode(_del) && event.target.parentNode != _del &&_dels != 'floderActionBtn') {
                  this.floderAction(false,'none')
                }
              }
        })
        
    }
    showTipContent(){
        let show = this.state.showTipContent
        this.setState({
            showTipContent:!show
        })
    }
    floderSlide(e,item,i){
        e.stopPropagation()
        const {floderSlide,admin,clearReset,selectTemp} = this.props
        const {showIndex} = this.state
        if(!item.templateInfo){
            return;
        }
        $(e.target).next().slideToggle()
        let domLis = $(e.target).parent().siblings()
        for(let i = 0;i < domLis.length;i++){
            let tmpD = domLis[i]
            $(tmpD).children().eq(1).slideUp()
        }
        // floderSlide(item.id)
        clearReset&&clearReset()
        if(admin ||!admin&&selectTemp) {
            if(showIndex === i) {
                this.setState({
                    showIndex: -1
                })
            } else {
                this.setState({
                    showIndex: i
                })
            }
        }
    }
    floderAction(e,id){
        e&&e.stopPropagation()
        const {floderAction} = this.props;
        floderAction(id)
    }
    genItems(items,flg) {
        const Items = [];
        const {admin,checkItems,allCheckShow,handleContentClick,handleTemplateDel,handleTitleChange,checkItemsAdmin,allCheckShowAdmin} = this.props;
        items.forEach((v,idx) => {
            Items.push(
                <TemplateItem
                    {...v}
                    key={v.id}
                    idx={idx}
                    checkItems={checkItems}
                    allCheckShow={allCheckShow}
                    handleContentClick={handleContentClick}
                    handleTemplateDel={handleTemplateDel}
                    handleTitleChange={handleTitleChange}

                    admin={admin}
                    adminflg={flg}
                    checkItemsAdmin={checkItemsAdmin}
                    allCheckShowAdmin={allCheckShowAdmin}
                />
            );
        });
        return Items;
    }
    floderRename(e,name,id){
        e.stopPropagation()
        this.props.floderAction(false,'none')
        this.props.floderRename(name,id)
    }
    floderDelete(e,id){
        e.stopPropagation()
        this.props.floderAction(false,'none')
        this.props.floderDelete(id)
    }
    genAdminItems(items,flg) {
        const Floder=[],Items = [];
        const {admin,checkItemsAdmin} = this.props;
        let {showIndex}=this.state
        if(items.length>0&&!items[0].templateInfo){
            showIndex = -1
        }
        for(let i = 0;i < items.length;i++){
            let tmpItm = items[i]
            Floder.push(
                <div className={style.floderPart}>
                    <div className={`${style.floderPartFl} floderSlideLis`} onClick={(e)=>this.floderSlide(e,tmpItm,i)}>
                        {admin&&<img src={showIndex== i?floderD:floderR} className={style.floderRD}/>}
                        {/* {!admin&&<img src={tmpItm.slide == 1?floderD:floderR} className={style.floderRD}/>} */}
                        {tmpItm.name}（{tmpItm.templateInfoCount}）
                        {admin&&tmpItm.name!='未分类文件夹'&&<span className={`${style.floderPartAction}`} id="floderActionBtn" onClick={(e)=>{this.floderAction(e,tmpItm.id)}}>...</span>}
                        {tmpItm.action == 1&&tmpItm.name!='未分类文件夹'&&<div className={style.floderAction} id="floderAction">
                            <p onClick={(e)=>{this.floderRename(e,tmpItm.name,tmpItm.id)}}>重命名文件夹</p>
                            <p onClick={(e)=>{this.floderDelete(e,tmpItm.id)}}>删除文件夹</p>
                        </div>}
                    </div>
                    {
                        tmpItm.templateInfo&&tmpItm.templateInfo.length>0&&<div className={style.floderPartFr}>
                            {
                                this.getFloderLis(tmpItm.templateInfo,flg,tmpItm.name,tmpItm.id)
                            }
                        </div>
                    }
                </div>
            )
        }
        return Floder
    }
    getFloderLis(items,flg,folderName){//文件夹内的模板明细
        const Items = [];
        const {admin,checkItemsAdmin,allCheckShowAdmin} = this.props;
        items.forEach((v,idx) => {
            Items.push(
                <TemplateItem
                    {...v}
                    key={v.id}
                    idx={idx}
                    folderName={folderName}
                    checkItems={this.props.checkItems}
                    allCheckShow={this.props.allCheckShow}
                    handleContentClick={this.props.handleContentClick}
                    handleTemplateDel={this.props.handleTemplateDel}
                    handleTitleChange={this.props.handleTitleChange}

                    admin={this.props.admin}
                    adminflg={flg}
                    checkItemsAdmin={checkItemsAdmin}
                    allCheckShowAdmin={allCheckShowAdmin}
                />
            );
        });
        return Items;
    }
    getCheckIcon() {
        const {admin,checkItems,items,checkItemsAdmin,adminItems,folderListContentArr} = this.props;
        if(admin){
            if (folderListContentArr.length == checkItemsAdmin.length && checkItemsAdmin.length != 0) {
                return check_right;
            } else {
                return check_circle;
            }
        }
        if (items.length == checkItems.length && checkItems.length != 0) {
            return tmpAllRight;
        } else {
            return tmpAllCircle;
        }
    }
    templateSearch(){
        const {templateSearch,selectTemp,admin} = this.props
        if(!(this.$search.current.value).trim()) {
            return
        }
        if(admin) {
            templateSearch((this.$search.current.value).trim(),2)
        } else {
            templateSearch((this.$search.current.value).trim(),selectTemp)

        }
        if(this.$search.current.value.trim()){
            this.setState({
                msg:'暂无模板信息'
            })
        }else{
            this.setState({
                msg:'还没有保存模板'
            })
        }
        this.setState({
            hasSearch: true
        })
    }
    
    handleEnter(e){
        if(e.keyCode==13){
            this.templateSearch();
        }
    }
    
    handleChange(){
        const {admin,selectTemp} = this.props;
        const value = (this.$search.current.value).substring(0,30);
        // this.$search.current.value = value
        if(!admin&&selectTemp==1&&value == ''){
            store.dispatch(initCommonItemList(1,""))
        }else if(!admin&&selectTemp==2&&value == ''){
            this.setState({
                hasSearch:false
            })
            store.dispatch(findTemplateNorms(''))
        }else if(admin){
            this.setState({
                hasSearch:false
            })
            store.dispatch(getFloderListAll(''))
        }
        setTimeout(() => {
            this.setState({
                val: value
            });
        }, 30);
    }

    clear(){
        const {clearTemplateSearch,selectTemp,admin} = this.props
        this.$search.current.value = '';
        this.setState({
            val:''
        });
        this.$search.current.focus();
        this.templateSearch();
        this.setState({
            hasSearch: false
        })
        clearTemplateSearch&&clearTemplateSearch()
        setTimeout(()=>{
            $(".floderSlideLis").eq(0).next().slideDown()
        },0)
        if(!admin){
            store.dispatch(initCommonItemList(1,""))
        }
    }
    clickTabChange(){

    }
    componentWillReceiveProps(next){
        //点清空恢复初始状态
      if(this.props.clearSearch!==next.clearSearch || next.reset){
        this.clear();
        this.props.clearReset()
      }
      const oldIndex = this.state.showIndex
    //   if(next.reset) {
    //     this.clear()
    //   }
      if(next.reset && oldIndex != 0) {
        $(".floderSlideLis").eq(oldIndex).next().slideUp()
          this.setState({
            showIndex: 0,
            hasSearch: false
          })
      }

    }
    whichTemp(num,val){
        setTimeout(()=>{
            $(".floderSlideLis").eq(0).next().slideDown()
        },0)

        this.props.whichTemp(num,val)
        // if(val){
        //     this.setState({
        //         hasSearch:true
        //     })
        // }
    }
    render() {
        const {selectTemp,whichTemp, checkItemsAdmin,handleAllCheckboxAdmin,handleMangerTemplateAdmin,allCheckShowAdmin,admin,adminItems,allCheckShow, handleMangerTemplate,handleClickGetMore, handleDelList, handleAllCheckbox, items,checkItems,current,hasMore,templateNormsSearchList } = this.props;

        const {height,showTipContent,hasSearch} = this.state
        return (
            <div className={style.wrapper} >
                {//管理员操作      
                    adminItems&&admin ? (allCheckShowAdmin ?
                        <div className={style.wrapperTop}>
                            <div className={style['check-wrap']} onClick={handleAllCheckboxAdmin} style={{paddingLeft:'10px'}}>
                                <img className={`${style['fl-element']} ${style['check-box']}`} src={this.getCheckIcon()} />
                            </div>
                            <span onClick={handleAllCheckboxAdmin}>全选</span>
                            <span className={`${style['fr-element']} ${style['done']}`} onClick={handleMangerTemplateAdmin}>完成</span>
                            {
                                checkItemsAdmin.length>0?<span className={`${style['fr-element']} ${style['del-items']}`} onClick={handleDelList}>删除</span>:
                                <span className={`${style['fr-element']} ${style['del-items-gray']}`}>删除</span>
                            }
                        </div> :
                        <div className={style.wrapperTop}>
                            <div className={style.templateSearch}>
                                <input placeholder="模板搜索" id="searchTmp" maxLength="30" ref={this.$search} type="text" onInput={this.handleChange} onPropertyChange={this.handleChange} onKeyUp={this.handleEnter}/>
                                {this.state.val?<img src={delIcon} id='clearTemplateSearch' alt="清空" onClick={this.clear}/>:''}
                                <div className={style.search} onClick={this.templateSearch}>搜索</div>
                            </div>
                            {
                                adminItems.length > 0&&<span className={`${style['fr-element']} ${style['manger']}`} onClick={handleMangerTemplateAdmin}>管理</span>
                            }
                    </div>) : null
                }
                {//个人
                    items&&!admin?
                        <div className={style.wrapperTop}>
                            <div className={style.templateSearch}>
                                <input placeholder="模板搜索" id="searchTmp" maxLength="30" ref={this.$search} type="text" onInput={this.handleChange} onPropertyChange={this.handleChange} onKeyUp={this.handleEnter}/>
                                {this.state.val?<img src={delIcon} alt="清空" onClick={this.clear}/>:''}
                                <div className={style.search} onClick={this.templateSearch}>搜索</div>
                            </div>
                    </div> : null
                }
                {
                    <div className={style.comAdminWrp}>
                        <div className={`${style.tempLists} ${style.tempListsP}`} ref={this.$cont} style={{display:admin?'none':'block',border:'1px solid #EAEDF1'}}>
                            {//个人
                                allCheckShow ?<div className={`${style.wrapperTop} ${style.wrapperTopM} ${style.personalTmp} ${selectTemp==1?style.personalTmpOwn:null}`} onClick={()=>whichTemp(1)}>
                                    <i></i>
                                    <i></i>
                                    <div className={style['check-wrap']} onClick={handleAllCheckbox}>
                                        <img className={`${style['fl-element']} ${style['check-box']}`} src={this.getCheckIcon()} />
                                    </div>
                                    <span onClick={handleAllCheckbox}>全选</span>
                                    <span className={`${style['fr-element']} ${style['done']}`} onClick={handleMangerTemplate}>完成</span>
                                    {checkItems.length>0&&<span className={`${style['fr-element']} ${style['del-items']}`} onClick={handleDelList}>删除</span>}
                                    {/* {
                                        checkItems.length>0?<span className={`${style['fr-element']} ${style['del-items']}`} onClick={handleDelList}>删除</span>:
                                        <span className={`${style['fr-element']} ${style['del-items-gray']}`}>删除</span>
                                    } */}
                                </div>:null
                            }
                            {
                                <div className={`${style.topBorder} clearfix`}>
                                    {
                                        !allCheckShow&&<div className={`${style.personalTmp} ${selectTemp==1?style.personalTmpOwn:''} clearfix`} onClick={()=>whichTemp(1,(this.state.val).trim(),hasSearch)}>
                                            <span className={style.tip}>个人模板</span>
                                            <i></i>
                                            {
                                                items.length > 0&&<span className={`${style['fr-element']} ${style['manger']}`} onClick={handleMangerTemplate}>管理</span>
                                            }
                                        </div>
                                    }
                                    {
                                        !admin?!allCheckShowAdmin&&<div 
                                            className={`${style.personalTmp} ${style.personalTmpStatand} ${selectTemp==2?style.personalTmpOwn:''}`} 
                                            onClick={()=>{this.whichTemp(2,(this.state.val).trim(),hasSearch);allCheckShow&&handleMangerTemplate(2)}}
                                            >标准模板 {selectTemp==2&&<img src={tempTip} className={style.tempTip} alt="" onMouseEnter={this.showTipContent} onMouseLeave={this.showTipContent}/>}
                                            {
                                                showTipContent&&<div className={style.tempTipContent}>
                                                    <img src={tempTrd} alt=""/>
                                                    <p>1. 标准模板中的科室，对应的是经朗通医疗团队整理的，符合临床医学意义的科室；</p>
                                                    <p>2.只有特定的“管理员”账号，可对“标准模板”进行修改，普通账号仅可进行“引用”。</p>
                                                </div>  
                                            }  
                                        </div>:''
                                    }
                                </div>
                            }
                            {
                                <div style={{height:height-54+'px',overflow:'auto'}}>
                                    {
                                        selectTemp==1&&this.genItems(items).length > 0?this.genItems(items):selectTemp==2&&this.genAdminItems(adminItems,true).length > 0?hasSearch ? this.genItems(templateNormsSearchList,true):this.genAdminItems(adminItems,true): <Empty message={this.state.msg}></Empty>
                                    }
                                </div>
                            }
                        </div>
                        {
                            admin&&<div className={style.tempLists} ref={this.$conts} style={{border:admin?'0':'1px solid #EAEDF1'}}>
                                <div style={{height:height+'px',overflow:'auto'}}>
                                    {this.genAdminItems(adminItems,true).length > 0?hasSearch ?this.genItems(templateNormsSearchList):this.genAdminItems(adminItems,true): <Empty message={this.state.msg}></Empty>}
                                </div>
                            </div>
                        }
                    </div>
                }
                {/* <div className={style.tempLists} ref={this.$cont}>
                    {
                        this.genItems().length > 0?this.genItems(): <Empty message={this.state.msg}></Empty>
                    }
                    {//注释掉的暂时没有分也功能
                      hasMore?<p onClick={()=>handleClickGetMore(current)} className={style.loadMore}>点击查看更多</p>:null
                    } 
                </div> */}
            </div>
        )
    }
}

export default TemplateItems;

TemplateItems.propTypes = {
    items: PropTypes.arrayOf(PropTypes.object),
    handleContentClick: PropTypes.func,
    handleUpdate: PropTypes.func,
    handleTemplateDel: PropTypes.func,
    handleTitleChange: PropTypes.func
};