import React from 'react'
import {Form, message, Modal, Row, Col, Radio, Tabs, Select, DatePicker, Input, TimePicker, Button, Divider, Checkbox, Table} from 'antd';
import moment from 'moment';
import PatientInfo from '../Patient/PatientInfo.jsx'
import { $http } from '../../../containers/config/https';
import './style/style.less';
import RangeDatePicker from 'components/rangePicker/index';
import store from 'store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from '../../columnAuthority/ColumnAuthoritysModel';

let user = {}
let patientData = {}
const { Option } = Select;
class PatientSchedule extends React.Component{
    //PatientSchedule
    constructor(props) {
        super(props);
        var date = new Date()
        user = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
        patientData = JSON.parse(sessionStorage.getItem('patientData'));
        this.state = {
            columns: [],
            data: [],
            page:"1",
            pageSize:"10",
            total:0,
            data:[],
            columns:[],
            ENObj:{},
            CNObj:{},
            stDate: moment(date).subtract(1, 'months').format('YYYY-MM-DD'),
            endDate:moment(date).format('YYYY-MM-DD'),
            operationStatusData:[],
            operationTypeData:[],
            locType:[],
            LocData:[],
            patWardData:[],
            operationRoomData:[],
            patWardID:"",
            applyLocID:"",
            operationRoomID:"",
            operationStatusID:"",
            operationType:"",
            patNumber:"",
            nurserArr:[],
            record:{},
            dataIndexArr:[],
            tableWidth:"",
        }
    }

    componentDidMount() {
       this.getOption();
       this.getApplyLocData();
       this.getPatWardData();
       this.loadDataColums();
       this.getSelectData();
    }

    //获取科室下拉数据
	getApplyLocData = () => {
		let data = {
			params: [{
				hospID: user.hospID,
				type: 'O^I^OI^E',
			}]
		}
		$http.post('urlS', this, {
			code: '04020008',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						LocData: res.result.Data,
					})
				}
			}
		});
	}
	//获取病区下拉数据
	getPatWardData = () => {
		let data = {
			params: [{
				hospID: user.hospID,
				type: 'W',
			}]
		}
		$http.post('urlS', this, {
			code: '04020008',
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						patWardData: res.result.Data,
					})
				}
			}
		});
    }
    
    // 获取下拉框数据
		getSelectData = () => {
			let data = {
				"params": [{
					hospID: user && user.hospID ? user.hospID : '', // 登录医院id       
					locID: user.locID,
				}]
			};
			$http.post('urlDeault', this, {
				code: "04160001",
				data: data,
				success: function (res) {
					if (+res.errorCode === 0) {
						this.setState({
                            nurserArr:  res.NurseArr,
                        })
					}
				},
				error: function (error) {
					message.error('失败：' + error);
				}
			});
		}

    loadDataColums = () =>{
        let data = {
            params: [{
                reactCode: ['PatientSchedule'],
                compontName: 'PatientSchedule',
                type: 'C',
            }]
        }
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    var columns = []
                    columns = res.result.C
                    if (columns) {
                        for (var ci = 0; ci < columns.length; ci++) {
                            if (columns[ci].dataIndex == 'confirmTakeDate') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <DatePicker
                                                onChange={this.selectDispatchInfo.bind(this,index, "confirmTakeDate")}
                                                value={(data.confirmTakeDate === "") ? null : moment(data.confirmTakeDate ,'YYYY-MM-DD')}
                                                style={{width:'100%'}}
                                            >
                                            </DatePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'inRoomDate') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{width:'100%'}}
                                                format='HH:mm'
                                                onChange={this.selectDispatchInfo.bind(this, index,"inRoomTime")}
                                                value={(data.inRoomTime === "") ? null : moment(data.inRoomTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'outRoomDate') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{width:'100%'}}
                                                format='HH:mm'
                                                onChange={this.selectDispatchInfo.bind(this, index,"outRoomTime")}
                                                value={(data.outRoomTime === "") ? null : moment(data.outRoomTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            

                            if (columns[ci].dataIndex == 'edit') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <Checkbox onChange={this.onselectOperation.bind(this,data,index)}></Checkbox>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'confirmTakeTime') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{width:'100%'}}
                                                format='HH:mm'
                                                onChange={this.selectDispatchInfo.bind(this, index,"confirmTakeTime")}
                                                value={(data.confirmTakeTime === "") ? null : moment(data.confirmTakeTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'sendTime') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{width:'100%'}}
                                                format='HH:mm'
                                                onChange={this.selectDispatchInfo.bind(this,index,"seeTime")}
                                                value={(data.seeTime === "") ? null : moment(data.seeTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'takeTime') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{width:'100%'}}
                                                format='HH:mm'
                                                onChange={this.selectDispatchInfo.bind(this, index,"takeTime")}
                                                value={(data.takeTime === "") ? null : moment(data.takeTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'confirmTakeUser') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <Select style={{width:'100%'}} showSearch allowClear optionFilterProp="role" defaultValue={data.confirmTakeUserID} onChange={this.selectDispatchInfo.bind(this,index,"confirmTakeUserID")} >
                                                {this.state.nurserArr.map(data => (<Select.Option key={data.id} value={data.id} role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode} >{data.descripts}</Select.Option>))}
                                            </Select>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'confirmSeeDate') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <DatePicker
                                            
                                                onChange={this.selectDispatchInfo.bind(this,index, "confirmSeeDate")}
                                                value={(data.confirmSeeDate === "") ? null : moment(data.confirmSeeDate ,'YYYY-MM-DD')}
                                                style={{width:'100%'}}
                                            >
                                            </DatePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'confirmSeeTime') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <TimePicker
                                                style={{ width: '150px' }}
                                                format='HH:mm'
                                                style={{width:'100%'}}
                                                onChange={this.selectDispatchInfo.bind(this,index, "confirmSeeTime")}
                                                value={(data.confirmSeeTime === "") ? null : moment(data.confirmSeeTime, 'HH:mm:ss')}
                                            >
                                            </TimePicker>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            if (columns[ci].dataIndex == 'confirmSeeUserDr') {
                                var diagColumns = [];
                                diagColumns.push({
                                    title: user.language != 'EN' ? user.language != 'EN' ? columns[ci].title : columns[ci].enDescripts : columns[ci].enDescripts,
                                    dataIndex: columns[ci].dataIndex,
                                    //width: width,
                                    align: 'center',
                                    render: (text, data, index) => {
                                        return (
                                            <Select showSearch allowClear optionFilterProp="role"  defaultValue={data.confirmSeeUserID} onChange={this.selectDispatchInfo.bind(this,index,"confirmSeeUserID")} style={{width:'100%'}}>
                                                {this.state.nurserArr.map(data => (<Select.Option key={data.id} value={data.id} role={data.code + '^' + data.descripts + '^' + data.descriptsSPCode}  >{data.descripts}</Select.Option>))}
                                            </Select>
                                        )
                                    }
                                })
                                columns[ci] = diagColumns[0]
                            }

                            
                        }
                    }
                    this.setState({
                        ENObj: res.result.language.EN,
                        CNObj: res.result.language.CN,
                        columns: columns,

                        tableWidth: res.totalWidth,
                        //colunmsCode: ColunmsCode
                    },()=>{
                        this.loadDispatch()
                    })
                }
            }
        })
    }

    selectDispatchInfo = (index, flag,e,timeString) => {
        if(flag.indexOf("User") != -1){
            this.state.data[index][flag] = e
        }else{
            this.state.data[index][flag] = timeString
        }
        console.log(this.state.data[index][flag]) 
    }

    loadDispatch = () => {
        let data = {
            params: [{
                stDate:this.state.stDate,
                endDate:this.state.endDate,
                patWardID:this.state.patWardID,
                applyLocID:this.state.applyLocID,
                operationRoomID:this.state.operationRoomID,
                operationStatusID:this.state.operationStatusID,
                operationType:this.state.operationType,
                patNumber:this.state.patNumber,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04160018",
            data: data,
            success: (res) => {
                if(res.errorCode == "0"){
                    this.setState({
                        data:res.result.Data,
                        total:res.result.TotalCount,
                    })
                }
            }
        })
    }

    // 获取下拉数据源
	getOption = () => {
		let data = {
			params: [{

			}]
		};
		$http.post('urlDeault', this, {
			code: "04160007",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						operationStatusData: res.result.operationStatusData,
						operationTypeData: res.result.operationTypeData,
						locType: res.result.locType,
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
			}
		});
	}

    onselectOperation =  (data,index,e) =>{

        if(this.state.dataIndexArr.indexOf(index+1) == -1){
            this.state.dataIndexArr.push(index+1)
        }else{
            var indexArr = this.state.dataIndexArr.indexOf(index+1)
            var newArr = this.state.dataIndexArr.splice(0,indexArr).concat(this.state.dataIndexArr.splice(indexArr+1,this.state.dataIndexArr.length-1))
            console.log(newArr)
            this.setState({
                dataIndexArr:newArr
            })
        }
    }

    // 翻页
	onChange = (page, pageSize) => {
		this.setState({ page: page, pageSize: pageSize }, () => {
			// 重新调用查询方法
			this.loadDispatch();
		});
	};

	onShowSizeChange = (current, size) => {
		this.setState({ page: current, pageSize: size }, () => {
			// 重新调用查询方法
			this.onChange(current, size);
		})
	};

    loadOperationDispatch = () => {
        //04040015{
       let data = {
           params: [{
            stDate:this.state.stDate,
            endDate:this.state.endDate,
           }]
       }
       $http.post('urlDeault', this, {
           code: "04160018",
           data: data,
           success: (res) => {
               if(res.errorCode == "0"){
                   this.setState({
                       data:res.result.Data,
                   })
               }
           }
       })
   }

    startChange(date) {
        this.setState({
            stDate: date,
        })
    }

    endChange(date) {
        this.setState({
            endDate: date,
        })
    }

    // 获取下拉框数据
	getselect = (lockID) => {
		let data = {
			params: [{
				locID: lockID?lockID:user.locID
			}]
		};
		$http.post('urlDeault', this, {
			code: "04160005",
			data: data,
			success: function (res) {
				if (+res.errorCode === 0) {
					this.setState({
						operationRoomData: res.result
					})
				}
			},
			error: function (error) {
				message.error('失败：' + error);
			}
		});
	}

    handleSelectCondition  (flag, e) {
        if(flag == "applyLocID"){
            this.state.operationRoomData = []
            this.getselect(e)
        }
        this.setState({
             [flag]: e 
        },()=>{
            this.loadDispatch()
        });
        
    }

    changePatNumber (e) {
        this.setState({
            patNumber:e.target.value
        },()=>{
            this.loadDispatch()
        })
    }

    onRow = (record) => {
        var that = this
        return {
          onClick: () => {
            if(this.state.record.id == record.id){
                this.setState({
                    record:{},
                })
            }else{
                this.setState({
                    record:record,
                })
            }
            
          }
          
        };
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    saveDispatchInfo = () => {
        var updateArr = []
        for (var i=0;i<this.state.dataIndexArr.length;i++){
            updateArr.push(this.state.data[this.state.dataIndexArr[i]-1])
        }
        console.log(updateArr)
        let data = {
            params: [{
                scheduleArr:updateArr,
            }]
        }
        $http.post('urlDeault', this, {
            code: "04160021",
            data: data,
            success: (res) => {
                if(res.errorCode == "0"){
                    message.success("保存成功")
                    this.loadOperationDispatch()
                }
            }
        })
    }




    render() {

        // operationStatusData:[],
        // operationTypeData:[],
        // locType:[],
        // LocData:[],
        // patWardID:"",
        //     applyLocID:"",
        //     operationRoomID:"",
        //     operationStatusID:"",
        //     operationType:"",
        //     patNumber:"",


        let patWardDatas = [];
        this.state.patWardData.map((item) => {
            patWardDatas.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })


        let LocDatas = [];
        this.state.LocData.map((item) => {
            LocDatas.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        let operationTypes = [];
        this.state.operationTypeData.map((item) => {
            operationTypes.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        let operationStatus = [];
        this.state.operationStatusData.map((item) => {
            operationStatus.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })


        let operationRooms = [];
        this.state.operationRoomData.map((item) => {
            operationRooms.push(
                <Option key={item.id} value={item.id} >
                    {item.descripts}
                </Option>
            )
        })

        return (
            <div className="scheduleCol" style={{height:'100%',overflow: 'hidden'}}>
                <ColumnAuthoritysModel
                        clientWidth='800px'
                        compontName="PatientSchedule"
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.loadDataColums}
                />
                <div >
                    <Row>
                        <Col span={6}>
                            <RangeDatePicker format='YYYY-MM-DD' label="申请日期" labelwidth="73px" totalwidth="350" width="300px"
                            startDate={this.state.stDate} endDate={this.state.endDate}
                            startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                        </Col>
                        <Col span={6}>
                            <div>   
                                患者病区：<Select value={this.state.patWardID}
                                onChange={this.handleSelectCondition.bind(this, "patWardID")}
                                style={{ width: '120px' }}>
                                    <Option key="" value="" >全部</Option>
                                    {patWardDatas}  
                                </Select>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div> 
                                申请科室：<Select value={this.state.applyLocID}
                                    onChange={this.handleSelectCondition.bind(this, "applyLocID")}
                                    style={{ width: '120px' }}>
                                        <Option key="" value="" >全部</Option>
                                    {LocDatas}
                                </Select>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div> 
                                手术间：<Select value={this.state.operationRoomID}
                                    onChange={this.handleSelectCondition.bind(this, "operationRoomID")}
                                    style={{ width: '120px' }}>
                                        {/* <Option key="" value="" >全部</Option> */}
                                    {operationRooms}
                                </Select>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div> 
                                手术类型：<Select value={this.state.operationType}
                                    onChange={this.handleSelectCondition.bind(this, "operationType")}
                                    style={{ width: '120px' }}>
                                        <Option key="" value="" >全部</Option>
                                    {operationTypes}
                                </Select>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div> 
                                手术状态：<Select value={this.state.operationStatusID}
                                    onChange={this.handleSelectCondition.bind(this, "operationStatusID")}
                                    style={{ width: '120px' }}>
                                        <Option key="" value="" >全部</Option>
                                    {operationStatus}
                                </Select>
                            </div>
                        </Col>
                        <Col span={6}>
                            <div>
                                <span>患者编号:</span><Input  style={{ width: '120px'}} onChange={this.changePatNumber.bind(this)}/>
                            </div>
                        </Col>
                        <Col span={6}  style={{ marginLeft:"-50px"}}>
                            <div>
                                <Button type="primary"  onClick={this.loadDispatch} style={{width:'30%'}}>查询</Button>
                                <Button type="primary"  onClick={this.saveDispatchInfo} style={{width:'30%',marginLeft:'20px'}}>保存</Button>
                            </div>
                        </Col>
                    </Row> 
                </div>

                <div style={{ width: '100%', height: '10px', background: '#f0f2f5',marginTop:'5px' }}></div>

                <div style={{ width: '100%', height: '100%', overflow: 'hidden',marginTop:'7px' }}>
                    
                    
                    <div style={{ width: '100%', height: 'calc(100% - 200px)', overflow: 'hidden' }} className='coursetable'>
                        <Table
                            style={{ width: '100%', "padding": "5px",height:"100%" }}
                            dataSource={this.state.data}
                            columns={this.state.columns}
                            rowClassName="editable-row"
                            bordered
                            pagination={false}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.columnRef.onOpenModel();
                                    },
                                };
                            }}
                            onRow={this.onRow}
                            scroll={{x: this.state.tableWidth,y:'calc(100% - 60px)'}}
                        />
                    </div>
                    
                    <div style={{ width: '100%', height: '45px', overflow: 'hidden',marginTop:'7px' }}>
                        <CommonPagination
                            size='small'
                            current={this.state.page}
                            total={this.state.total}
                            search='search'
                            onShowSizeChange={this.onShowSizeChange.bind(this)}
                            complete={true}
                            dataSource={this.state.data}
                            onChange={this.onChange.bind(this)}
                            scroll={{ y: store.getState().tableHeight.y + 'px' }}
                        />
                    </div>
                </div>
            </div>
        )
    }



}export default PatientSchedule