import React from 'react';
import { SearchOption, InspectCommon, Calendar ,Notify,ConfirmModal} from '@commonComp';
import { deepClone } from '@utils/tools';
import styles from './index.less';
import date1 from './img/date1.png';
import date2 from './img/date2.png';
import close from './img/close.png';
import store from '@store';
import $ from 'jquery';

class Inspect extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false,
            showFill: false,
            date: false,
            currentIdx: '',
            dateTime:"",
            currentData:{},
            numPlus:0,     //判断是否所有的填写单都是空
            num:0,            //暂存数据，获取一次，不能每次都是新的数据
            toastText:'',
            visible:false,
            type:null,
            id:null
        }
        this.handleChangeDate = this.handleChangeDate.bind(this)
        this.handleShowDate = this.handleShowDate.bind(this)
        this.getCurrentDate = this.getCurrentDate.bind(this)
        this.getItemList = this.getItemList.bind(this)
        this.getSearchList = this.getSearchList.bind(this)
        this.changeActivePart = this.changeActivePart.bind(this)
        this.normalVal = this.normalVal.bind(this)
        this.showDetails = this.showDetails.bind(this)
        this.delConfirm = this.delConfirm.bind(this)
        this.handleCancel = this.handleCancel.bind(this)
    }
    delConfirm(){//弹窗确定
        const{delPartItem,handleCloseExcel} = this.props;
        const{type,id} = this.state;
        if(type==1){
            delPartItem(id)
        }else if(type==2){
            handleCloseExcel(id)
        }
        this.setState({
            visible:false,
            type:null,
            id:null,
        })
        Notify.success("删除成功");
    }
    handleDelClick(type,idx){
        this.setState({
            type:type,
            id:idx,
            visible:true
        })
        if(type==1){//单项
            this.setState({
                toastText:'是否删除该化验项？'
            })
        }else if(type==2){//导入项
            this.setState({
                toastText:'是否删除导入项？'
            })
        }
    }
    handleCancel(){
        this.setState({
            visible:false,
            type:null,
            id:null,
        })
    }
    componentDidMount() {
        $(document).click((event) => {
            let searchWrap = $('#searchWrap')[0];   // 搜索按钮
            let searchOption = $('#searchOption')[0];   // 搜索列表
            let inspectFill = $('#inspectFill')[0];         // 公共填写单
            if(searchOption){
                if ( searchOption != event.target && searchWrap != event.target && !$.contains(searchOption, event.target)) { // Mark 1
                    this.setState({ show: false });
                }
            }
            if(inspectFill){
                if ( event.target.getAttribute('data-flg') != 'current' && inspectFill != event.target && !$.contains(inspectFill, event.target)) { // Mark 1
                    this.setState({ showFill: false });
                }
            }
        });
        this.getCurrentDate();
    }
    componentWillReceiveProps(nextProps){
        if(nextProps.fillActive.name != this.props.fillActive.name){
            this.setState({num:0})
        }
    }
    handleChangeDate(info) {
        let date = info.year+'-'+(info.month<10?'0'+info.month:info.month)+'-'+(info.day<10?'0'+info.day:info.day);
        this.setState({dateTime:date,date:false})
    }
    handleSearchShow(e) {
        let tmpShow = this.state.show;
        this.setState({ show: !tmpShow })
        // e.stopPropagation();
    }
    handleFillShow(e,idx) {
        let tmpShow = this.state.showFill;
        let baseList = store.getState().inspect.fillActive;
        this.setState({ 
            showFill: !tmpShow, 
            currentIdx:idx,
            currentData:baseList
        })
        // e.stopPropagation();
    }
    handleShowDate(){
        this.setState({
            date:!this.state.date
        })
    }
    getCurrentDate(){
        let myDate = new Date();
        let year = myDate.getFullYear();       //获取完整的年份(4位,1970-????)
        let mon = myDate.getMonth()-0+1;       //获取当前月份(0-11,0代表1月)
        let day = myDate.getDate();            //获取当前日(1-31)
        let date = year+'-'+(mon<10?'0'+mon:mon)+'-'+(day<10?'0'+day:day);
        this.setState({dateTime:date})
        
    }
    changeActivePart(idx,val){
        let nums = this.state.num;
        let fillActive;
        if(nums == 0){
            fillActive = this.props.fillActive;
        }else{
            fillActive = this.state.currentData;
        }
        ++nums;
        this.setState({num:nums});
        let tempArr = deepClone(fillActive);
        let tempNumPlus = 0;
        for (let i = 0; i < tempArr.details.length; i++) {
            if (i == idx) {
                tempArr.details[i].value = val
            }
            if(tempArr.details[i].value != undefined && tempArr.details[i].value != ''){
                tempArr.show = true;
            }else{
                ++tempNumPlus;
                if(tempNumPlus == tempArr.details.length){
                    tempArr.show = false;
                }
                   
            }
        }
        tempArr.time = this.state.dateTime;
        this.setState({currentData:tempArr})
    }
    getItemList(){        //填写单展示
        let number = this.state.num;
        let fillActive;
        if(number == 0){
            fillActive = this.props.fillActive;
        }else{
            fillActive = this.state.currentData;
        }
        return <ul className={styles.searchLis}>
            {
                fillActive && fillActive.details && fillActive.details.map((item,idx) => {
                    if(item.controlType == 1){
                        return (
                            <li className={`${styles.itemPart} ${fillActive.details.length>1?'':styles.itemPartOne}`}>
                                <span className={styles.itemPartL}>{item.name}</span>
                                <select className={styles.itemPartR} onChange={(e)=>{
                                        if(e.target.value == '请选择') {
                                            this.changeActivePart(idx,'')
                                            return;
                                        }
                                        this.changeActivePart(idx,e.target.value);
                                    }}
                                >
                                    <option value="请选择">请选择</option>
                                    {
                                        (item.questionDetailList).map((val)=>{
                                            return <option value={val.name} 
                                                selected={val.name == item.value?true:false}
                                            >{val.name}</option>
                                        })
                                    }
                                </select>
                            </li>
                        )
                    }else if(item.controlType == 6){
                        return (
                            <li className={`${styles.itemPart} ${fillActive.details.length>1?'':styles.itemPartOne}`}>
                                <span className={styles.itemPartL}>{item.name}</span>
                                <span className={styles.itemPartT}>
                                    <input type="text" 
                                        placeholder="(填写)"
                                        value={item.value}
                                        onKeyUp={(e)=>{this.changeActivePart(idx,e.target.value.trim())}} 
                                    />
                                    <p className={styles.unit}>{item.labelSuffix}</p>
                                </span>
                            </li>
                        )
                    }
                })
            }
        </ul>
    }
    getSearchList(list){      //搜索列表
        const {handleSign} = this.props;
        return <ul>
        {
            list && list.map((item,idx) => {
                return <li key={idx}
                    className={styles.searchLi}
                    title={item.name}
                    onClick={() => {
                        handleSign(item.questionId,idx);
                        this.setState({ show: false })
                    }}
                >
                    {item.name}{item.name == item.retrievalName?null:'('+item.retrievalName+')'}
                </li>
            })
        }
    </ul>
    }
    normalVal(min,max){
        if((min-0) && (max-0)){
            return `正常值: (${min}~${max})`
        }else if((min-0) && !(max-0)){
            return `正常值: (>=${min})`
        }else if(!(min-0) && (max-0)){
            if(min == '' || min == null){
                return `正常值: (<=${max})`
            }else{
                return `正常值: (${min}~${max})`
            }
        }else{
            return null;
        }
    }
    showDetails(val){
        if(val.questionDetailList.length > 0){
            return val.questionDetailList.map((item)=>{
                if(val.value == item.name){
                    return <td className={item.abnormal != '0' ?"red":'' }>{val.value}</td>
                }
            })
        }else{
            return <td><span className={val.value > val.maxValue || val.value < val.minValue?"red":''}>{val.value}</span> { val.labelSuffix}</td>
        }
    }
    render() {
        const { handleChangeValue, list, labelList,delPartItem, handleLabelSub, handleClear, handleConfirm, fillActive,getExcelDataList,handleCloseExcel } = this.props;
        const {toastText,visible} = this.state;
        return (
            <div className={styles.wrapper}>
                <div className={styles.check}>
                    {
                        getExcelDataList.length > 0 && getExcelDataList.map((items,idx)=>{
                            return <div style={{marginTop:'10px'}}>
                                {
                                    items && items.lisExcelRes.length > 0 ? <ul className={styles.excelDataLists}>
                                    <img className={styles.close} src={close} alt="关闭导入excel数据" onClick={(idx)=>{this.handleDelClick(2,idx)}}/>
                                    {
                                        items.lisExcelRes.map((item,idx)=>{
                                            return <li className={styles.excelDataLis} style={{border:items.lisExcelRes.length-1 == idx? 0:''}}>
                                                <span className={styles.excelDataTitle}>
                                                    {item.menus}
                                                </span>
                                                <table>
                                                    {
                                                        item.lisExcelItem && item.lisExcelItem.map((value)=>{
                                                            return <tr>
                                                                <td>{value.itemName}</td>
                                                                <td><span className={value.type == 1?'red':null}>{value.value}</span> {value.unit}</td>
                                                                <td>
                                                                    {this.normalVal(value.min,value.max)}
                                                                </td>
                                                                <td>{value.time == ''?('导入时间: '+this.state.dateTime):'化验时间: '+value.time}</td>
                                                            </tr>
                                                        })
                                                    }
                                                </table>
                                            </li>
                                        })
                                    }
                                </ul>:null
                                }
                            </div>
                        })
                    }
                    <ul className={styles.labelWrap} >
                        {
                            labelList && labelList.map((item,idx) => {
                                return <li key={item.questionId}> 
                                    {
                                        // 标签，血常规。。
                                        item.show ?
                                        <p className={styles.staticTagActive}>
                                            <span data-flg="current" style={{color:"#333"}} onClick={(e) => { handleLabelSub(e, item.questionId,idx); this.handleFillShow(e,idx) }}>{item.name}</span>
                                        </p>:
                                        <p>
                                            <i data-flg="current" onClick={(e) => { handleLabelSub(e,item.questionId,idx); this.handleFillShow(e,idx) }}>{item.name}</i>
                                        </p>
                                    }
                                    {
                                        item.show ? 
                                            <table className={styles.table}>
                                                {
                                                    item.details.map((val)=>{
                                                        if(val.value && val.value != ''){
                                                            return <tr>
                                                                <td>{val.name}</td>
                                                                {this.showDetails(val)}
                                                                <td>
                                                                    {this.normalVal(val.minValue,val.maxValue)}
                                                                </td>
                                                                <td>{'化验时间:'+item.time}</td>
                                                            </tr>
                                                        }
                                                    })
                                                }
                                            </table>:null
                                    }
                                    <div className={styles.searchResult}>
                                        {
                                            this.state.showFill && fillActive.id == item.id && idx == this.state.currentIdx ?
                                                <InspectCommon
                                                    showFill={this.state.showFill}
                                                    handleClear={(e)=>{
                                                        handleClear(e,idx)
                                                        this.setState({
                                                            showFill:false
                                                        })
                                                    }}
                                                    handleConfirm={(e)=>{
                                                        // handleConfirm(e,idx,this.state.dateTime,fillActive);
                                                        if(JSON.stringify(this.state.currentData) == '{}'){
                                                            handleConfirm(e,idx,this.state.dateTime,fillActive);
                                                        }else{
                                                            handleConfirm(e,idx,this.state.dateTime,this.state.currentData);
                                                        }
                                                        this.setState({showFill:false})
                                                    }}
                                                >
                                                    <div className={styles.searchResultT}>
                                                        <img style={{"position":"absolute","top":"8px","right":"8px"}} src={date1} alt="" onClick={this.handleShowDate}/>
                                                        <p style={{position:"absolute",right:"38px",top:"4px",lineHeight:"28px"}}>
                                                            {this.state.dateTime}
                                                        </p>
                                                        <div style={{display:this.state.date?"block":"none",position:"relative"}}>
                                                            {/* 日期组件 */}
                                                            <Calendar isShow={true} handleChange={this.handleChangeDate}></Calendar>
                                                        </div>
                                                    </div>
                                                        {/* 填写单内容显示 */}
                                                        { this.getItemList(idx) }
                                                </InspectCommon>
                                            : null
                                        }
                                    </div>
                                    <img className={styles.partDel} src={close} alt="删除项" onClick={(idx)=>{this.handleDelClick(1,idx)}}/>
                                </li>
                            })
                        }
                    </ul>
                </div>
                <div style={{position:"relative"}}>
                    <span id="searchWrap" className={`${styles.staticTag}`} onClick={(e) => this.handleSearchShow(e)}>添加化验项</span>
                    <SearchOption handleChangeValue={handleChangeValue} visible={this.state.show}>
                        {this.getSearchList(list)}
                    </SearchOption>
                </div>
                <ConfirmModal 
                    visible={visible}
                    confirm={()=>{this.delConfirm()}}
                    close={this.handleCancel}
                    cancel={this.handleCancel}
                    okText="删除"
                    cancelText='取消'
                    okBorderColor={'#3B9ED0'}
                    okColor={'#fff'}
                    oKBg={'#3B9ED0'}
                >
                    <p className={styles['center']}>{toastText}</p>
                </ConfirmModal>
            </div>
        )
    }
}

export default Inspect;