/**
 * 预约治疗
 */
import React from 'react';
import {
    Modal, Row, Col, Select, Card, Radio, Input, Button, Tree, Icon, Tag, Table,
    Divider, message, DatePicker
} from 'antd';
import { Util, dayFormat, timeFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import '../style/index.less';
import moment from 'moment';

const Option = Select.Option;
const confirm = Modal.confirm;
const Search = Input.Search;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

class ShowConfirmApplicationModal extends React.Component {

    constructor(props) {
        super(props);
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var date = new Date()
        this.state = {
            userData: userData,
            radioValue: '1',
            ids: [],
            dataSource: [],
            dateTime: moment(date).format(dayFormat),
            bookScheduleID: []
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            this.setState({
                cureConAppID: nextProp.cureConAppID,
                admID: nextProp.admID,
                flag: nextProp.flag
            }, () => {
                this.initData()
                this.loadOrderData()
                this.loadApplicationList()
                this.getDoctor()
            })
        } else if (this.props.isShow === false) {
            this.clearInput()
        }
    }

    loadOrderData() {
        let data = {
            params: [{
                compontName: "ShowConfirmApplicationModal",
                type: "C",
                reactCode: ['ShowConfirmApplicationModal']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    var columns = res.result.C;
                    var dynColumns = []
                    for (var i = 0; i < columns.length; i++) {
                        dynColumns.push({
                            title: this.state.userData.language == 'EN' ? columns[i].enDescripts : columns[i].title,
                            dataIndex: columns[i].dataIndex,
                            width: parseInt(columns[i].width),
                            align: columns[i].align || 'center',
                        })
                    }
                    this.setState({
                        columns: dynColumns,
                        listWidth: res.totalWidth,
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    })
                    this.props.hanlderThis.setState({
                        reload: false,
                    })
                }
            }
        })
    }

    //国际化
    setMessage(name, message) {
        return this.state.localeProvider && this.state.localeProvider[name] ? this.state.localeProvider[name][message] : ''
    }


    initData() {
        this.columns = [
            {
                title: this.state.userData.language == 'EN' ? 'appOrder' : '项目名称',
                dataIndex: 'appOrder',
                width: 200,
                align: 'left',
            },
            {
                title: this.state.userData.language == 'EN' ? 'price' : '项目单价',
                dataIndex: 'ordSingleAmt',
                width: 100,
                align: 'right',
            },
            {
                title: this.state.userData.language == 'EN' ? 'orderQty' : '项目数量',
                dataIndex: 'orderQty',
                width: 100,
                align: 'left',
            },
            {
                title: this.state.userData.language == 'EN' ? 'cureQty' : '已治疗',
                dataIndex: 'cureQty',
                width: 100,
                align: 'left',
            },
            {
                title: this.state.userData.language == 'EN' ? 'appQty' : '有效预约数量',
                dataIndex: 'appQty',
                width: 150,
                align: 'left',
            },
            {
                title: this.state.userData.language == 'EN' ? 'usableQty' : '剩余预约数量',
                dataIndex: 'usableQty',
                width: 150,
                align: 'left',
            },
        ],
            this.rightColumns = [
                {
                    title: this.state.userData.language == 'EN' ? 'seqNo' : '队列序号',
                    dataIndex: 'seqNo',
                    width: 70,
                    align: 'left',
                },
                {
                    title: this.state.userData.language == 'EN' ? 'order time' : '预约时间',
                    dataIndex: 'bookDateTime',
                    width: 150,
                    align: 'left',
                },
                {
                    title: this.state.userData.language == 'EN' ? 'Doctor' : '医生',
                    dataIndex: 'cureDoctorDesc',
                    width: 80,
                    align: 'left',
                },
                {
                    title: this.state.userData.language == 'EN' ? 'Status' : '状态',
                    dataIndex: 'bookStatusDesc',
                    width: 80,
                    align: 'left',
                },
                {
                    title: this.state.userData.language == 'EN' ? 'opersion' : '操作',
                    dataIndex: 'opersion',
                    width: 80,
                    align: 'left',
                    render: (text, data) => {
                        return data.bookStatusCode == 'B' ? <span style={{ color: '#1890FF', cursor: 'pointer' }}
                            onClick={this.handleCannelOrder.bind(this, data.bookScheduleID)}>{this.setMessage('ShowConfirmApplicationModalcancel', 'descripts')}</span> : null
                    }
                }
            ]
    }

    handleCannelOrder(id) {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                bookScheduleIDArr: [id]
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050170",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success(this.setMessage('ShowConfirmApplicationModalsuccess', 'descripts'))
                    this.loadLeftTable()
                }
            }
        });
    }

    closeModal(name) {
        let { onHide } = this.props;
        onHide && onHide();
    }

    clearInput() {
        this.setState({
            leftData: [],
            rowIds: ''
        })
    }

    loadApplicationList() {
        var params = {
            params: [{
                cureAppID: this.state.flag ? this.state.cureConAppID : [this.state.cureConAppID]
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040197",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        dataSource: res.result.data,
                        rowIds: res.result.data ? res.result.data[0].ID : '',
                        cureLocID: res.result.data ? res.result.data[0].cureLocID : '',
                    }, () => {
                        this.loadTimeRange()
                    })
                }
            }
        });
    }

    //获取医生排班信息
    loadScheduling() {
        var params = {
            params: [{
                cureAppID: this.state.rowIds ? this.state.rowIds : this.state.cureConAppID,
                timeRangeID: this.state.timeRangeId,
                doctorID: this.state.doctorID,
                medicalNo: this.state.medicalNo,
                date: this.state.dateTime ? moment(this.state.dateTime).format(dayFormat) : '',
                locID: this.state.cureLocID,
                hospID: this.state.userData.hospID,
                medItemID: this.state.medItemID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050166",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    let doctorList = res.result && res.result.data && res.result.data.length > 0 ? res.result.data : [];
                    let windowHost = window.location && window.location.origin ? window.location.origin : (window.location && window.location.protocol ? (window.location.protocol + '//' + window.location.hostname) : "");
                    for (var i = 0; i < doctorList.length; i++) {
                        let url = doctorList[i].image
                        doctorList[i].image = url.indexOf("http") !== -1 ? url : windowHost + url;
                    }
                    this.setState({
                        doctorList
                    })
                }
            }
        });
    }

    changeDateTime(e) {
        this.setState({
            dateTime: e ? moment(e).format(dayFormat) : ''
        }, () => {
            this.loadScheduling()
        })
    }

    changeTime(name) {
        var date = new Date()
        if (name == 'left') {
            if (moment(this.state.dateTime, dayFormat).unix() < (moment(date, dayFormat).unix())) {
                message.error(this.setMessage('ShowConfirmApplicationModalcurrent', 'descripts'))
                return
            }
            this.setState({
                dateTime: this.state.dateTime ? moment(this.state.dateTime).subtract(1, 'days') : '',
                orderData: ''
            }, () => {
                this.loadScheduling()
            })
        } else if (name == 'right') {
            this.setState({
                dateTime: this.state.dateTime ? moment(this.state.dateTime).add(1, 'days') : '',
                orderData: ''
            }, () => {
                this.loadScheduling()
            })
        }
    }

    //获取开始时间和结束时间
    changeTimeRang(e) {
        this.setState({
            timeRangeId: e,
        }, () => {
            this.loadScheduling()
        })
    }


    //获取坐诊医生
    getDoctor() {
        var params = {
            params: [{
                locID: this.state.userData.locID,
                groupID: '',
                depDoctorID: '',
                CureApplicationID: this.state.cureConAppID,
                hospID: this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            // code: "03020049",
            code: "03050215",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        doctorData: res.depDoctor
                    })
                }
            }
        });
    }

    //查询时段服务
    loadTimeRange() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040010",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        timeRange: res.timeRange,
                        timeRangeId: res.timeRange ? res.timeRange[0].id : ''
                    }, () => {
                        this.loadScheduling()
                    })
                }
            }
        });
    }

    loadOrderModal(data) {
        // this.setState({
        //     resDetailID: item.resDetailID,
        //     isShowToOrderModal: true
        // })
        if (parseInt(data.registedNum) >= parseInt(data.registNum)) {
            message.error(this.setMessage('ShowConfirmApplicationModaldoctor', 'descripts'));
            return
        }
        var params = {
            params: [{
                patID: '',
                resDetailID: data.resDetailID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03040018",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        orderData: res.data,
                        resDetailID: data.resDetailID,
                    })
                }
            }
        });
    }

    addBackground(data, index) {
        this.setState({
            rowId: index,
            code: data.id
        })
    }

    addElement(data, index, e) {
        if (e.keyCode == '13') {
            this.submitOrder(data)
        } else if (e.keyCode == '37') {//左方向键
            if (parseInt(this.state.rowId) - 1 < 0) {
                this.setState({//当向左移动已无数据时，默认第一个数据
                    rowId: '0'
                })
            } else {
                this.setState({
                    rowId: parseInt(this.state.rowId) - 1
                })
            }
        } else if (e.keyCode == '38') {//上方向键
            if (parseInt(this.state.rowId) - 4 < 0) {
                this.setState({//当上移已无数据时，默认当前数据
                    rowId: index
                })
            } else {
                this.setState({
                    rowId: parseInt(this.state.rowId) - 4
                })
            }
        } else if (e.keyCode == '39') {//右方向键schedulData
            if (parseInt(this.state.rowId) + 1 == this.state.orderData.resDetail.length) {
                this.setState({//当右移大于当前数据的长度时，默认当前数据
                    rowId: index
                })
            } else {
                this.setState({
                    rowId: parseInt(this.state.rowId) + 1
                })
            }
        } else if (e.keyCode == '40') {//下方向键
            if (parseInt(this.state.rowId) + 4 >= this.state.orderData.resDetail.length) {
                this.setState({//当下移大于当前数据的长度时，默认当前数据
                    rowId: index
                })
            } else {
                this.setState({
                    rowId: parseInt(this.state.rowId) + 4
                })
            }
        }
    }

    //双击去预约
    submitOrder(data) {
        if (Util.isEmpty(this.state.rowIds)) {
            message.error(this.setMessage('ShowConfirmApplicationModalitems', 'descripts'))
            return
        }
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
                curAppID: this.state.rowIds ? this.state.rowIds : this.state.cureConAppID,
                resDetailID: this.state.resDetailID,
                bookMethodID: 'WIN',
                resTimeID: data.id,

            }]
        }
        $http.post('urlDeault', this, {
            code: "03050167",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    message.success(this.setMessage('ShowConfirmApplicationModalappointment', 'descripts'))
                    this.loadLeftTable(data.id)
                }
            }
        });
    }

    loadLeftTable(id) {
        var params = {
            params: [{
                cureAppID: this.state.rowIds
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050169",
            data: params,
            success: function (res) {
                if (res.errorCode === '0') {
                    this.setState({
                        leftData: res.result.data
                    })
                }
            }
        });
    }

    changeDoctorId(name, e) {
        this.setState({
            [name]: e
        }, () => {
            this.loadScheduling()
        })
    }

    onSubmit() {
        var { onSubmit } = this.props;
        onSubmit && onSubmit()
    }

    //点击行，渲染当前行样式 
    setRowClassName = (record) => {
        return record.ID === this.state.rowIds ? 'clickRowStyle' : '';
    }

    //点击行，渲染当前行样式
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    rowIds: record.ID,
                    cureLocID: record.cureLocID
                }, () => {
                    this.loadScheduling()
                })
            }
        };
    }

    onBottomColumnRef = (ref) => {
        this.btnColumnRef = ref;
    }

    render() {
        var { doctorList, bookScheduleID } = this.state;
        //卡类型
        let cardTypeOption = []
        this.state.cardTypeData && this.state.cardTypeData.map((item, index) => {
            cardTypeOption.push(<Option key={index} value={item.id} code={item.descripts}>{item.descripts}</Option>)
        })

        //坐诊医生
        let doctorOption = []
        this.state.doctorData && this.state.doctorData.map((item, index) => {
            doctorOption.push(<Option key={index} value={item.id} code={item.descriptsSPCode} name={item.descripts}>
                {item.descripts}</Option>)
        })

        let timeRangeOption = []
        this.state.timeRange && this.state.timeRange.map((item, index) => {
            timeRangeOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        var doctorListOption = []
        doctorList && doctorList.map((item, index) => {
            doctorListOption.push(<Col span={6} key={index} value={item.doctorName}
                className={this.state.resDetailID == item.resDetailID ? 'appoint-check-style' : 'appoint-disabled-style'}
                onClick={this.loadOrderModal.bind(this, item)}
                style={{ width: '31%', height: 90, cursor: 'pointer', marginLeft: 5, marginTop: 5 }}>
                <div style={{ float: 'left', width: '65%' }}>
                    <div style={{ display: 'flex' }}>
                        {!Util.isEmpty(item.image) ? <div style={{ width: 80, height: 87 }}><img src={item.image} style={{ width: '100%', height: '100%' }} /></div> :
                            <div style={{ marginTop: 3 }} className={item.docSexCode == '1' ? 'card-splice-boy' : 'card-splice-girl'}></div>}
                        <div>
                            <div style={{ marginTop: '25%' }}>
                                <span>{item.doctorName}
                                    <Icon className={item.onLineStatusCode == 'Y' ? 'card-splice-onLine' : 'card-splice-out'} />
                                </span>
                                {/* <div style={{ color: 'orange' }}>普通针刺</div> */}
                            </div>
                        </div>
                    </div>
                </div>
                <div style={{ float: 'right', width: '34.5%', textAlign: 'center', borderLeft: '1px solid #e8e8e8', lineHeight: '85px' }}>
                    <span><span style={{ color: '#1999db' }}>{item.registedNum}</span>/{item.registNum}</span></div>
            </Col>)
        })

        var loadOrderNum = []
        if (!Util.isEmpty(this.state.orderData)) {
            var resDetail = this.state.orderData.resDetail;
            resDetail && resDetail.map((item, index) => {
                loadOrderNum.push(
                    <div className='order-table-body' style={{ cursor: 'pointer' }}
                        onKeyDown={this.addElement.bind(this, item, index)} tabIndex={'-1'}
                        onClick={this.addBackground.bind(this, item, index)} onDoubleClick={this.submitOrder.bind(this, item)}>
                        <div style={{ display: 'flex' }}><div className={item.workStatusCode == 'S' ? 'stop-order-num' :
                            (item.workStatusCode == 'F' ? 'full-order-num' : '')}></div>
                            <div className={item.workStatusCode == 'N' ? 'order-table-disable' : 'order-table-title'}>{item.timeDetail}</div></div>
                        <div style={{ background: index == this.state.rowId ? '#bfe6f8' : '' }}>
                            <div>{this.setMessage('ShowConfirmApplicationModalUsed', 'descripts')}</div>
                            {index == this.state.rowId ? <div style={{ display: 'flex', marginLeft: 50 }}>{item.regResources}
                                <Button autoFocus={true} style={{ border: '0', height: 10, background: '#bfe6f8' }}></Button></div> :
                                <div>{item.regResources}</div>}
                        </div>
                    </div>
                )
            })
        }


        return <div className='show-application-modal'>
            <ColumnAuthoritysModel
                clientWidth='800px'
                compontName="ShowConfirmApplicationModal"
                configType="C"
                onRef={this.onBottomColumnRef}
                reloadData={this.loadOrderData}
            />
            <Modal className='confirm-application-moadl'
                title={this.setMessage('ShowConfirmApplicationModaltherapy', 'descripts')}
                maskClosable={false}
                footer={null}
                visible={this.props.isShow}
                onOk={this.onSubmit.bind(this)}
                okText={'保存'}
                onCancel={this.closeModal.bind(this)}>
                <div style={{ width: '100%' }}>
                    <Card title={this.setMessage('ShowConfirmApplicationModaltreatment', 'descripts')}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                            bordered
                            rowKey={(data) => {
                                return data.id
                            }}
                            onHeaderRow={column => {
                                return {
                                    onDoubleClick: () => {
                                        this.btnColumnRef.onOpenModel();
                                    },
                                };
                            }}
                            pagination={false}></Table>
                    </Card>

                    <div style={{ marginTop: 5 }}>
                        <Card style={{ float: 'left', width: '60%' }} title={<span>{this.setMessage('ShowConfirmApplicationModalTherapist', 'descripts')}</span>}>
                            <Row>
                                <Col style={{ textAlign: 'center' }} span={10}>
                                    {this.setMessage('ShowConfirmApplicationModalDate', 'descripts')} <Icon type='left' style={{ marginRight: 5, cursor: 'pointer' }} onClick={this.changeTime.bind(this, 'left')} />
                                    <DatePicker style={{ width: '57%' }} onChange={this.changeDateTime.bind(this)}
                                        value={!Util.isEmpty(this.state.dateTime) ? moment(this.state.dateTime, dayFormat) : ''} />
                                    <Icon type='right' style={{ marginLeft: 5, cursor: 'pointer' }} onClick={this.changeTime.bind(this, 'right')} />
                                </Col>
                                <Col span={7}>
                                    {this.setMessage('ShowConfirmApplicationModalTime', 'descripts')}
                                    <Select placeholder={this.setMessage('ShowConfirmApplicationModalperiod', 'descripts')} style={{ width: '65%' }} onChange={this.changeTimeRang.bind(this)}
                                        getPopupContainer={triggerNode => triggerNode.parentNode} value={this.state.timeRangeId}>
                                        {timeRangeOption}
                                    </Select>
                                </Col>
                                <Col span={7}>
                                    {this.setMessage('ShowConfirmApplicationModalDoctors', 'descripts')}
                                    <Select placeholder={this.setMessage('ShowConfirmApplicationModalselect', 'descripts')} style={{ width: '65%' }} showSearch
                                        allowClear={true}
                                        filterOption={(input, option) =>
                                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.code.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                            || option.props.name.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                        }
                                        value={this.state.doctorID}
                                        onChange={this.changeDoctorId.bind(this, 'doctorID')}
                                        getPopupContainer={triggerNode => triggerNode.parentNode}>
                                        {doctorOption}</Select>
                                </Col>
                            </Row>
                            <div style={{ marginTop: 5, height: '20vh', overflow: 'auto' }}>
                                {doctorListOption}
                            </div>
                            <Card style={{ marginTop: 5 }} title={<span style={{ color: 'orange' }}> {this.setMessage('ShowConfirmApplicationModalnote', 'descripts')}</span>}>
                                <div className='order-num-table'>
                                    {loadOrderNum}
                                </div>
                            </Card>
                        </Card>
                        <Card style={{ float: 'right', width: '39.8%' }} title={<span> {this.setMessage('ShowConfirmApplicationModalrecord', 'descripts')}</span>}>
                            <Table columns={this.rightColumns}
                                dataSource={this.state.leftData}
                                bordered
                                rowKey={(data) => {
                                    return data.id
                                }}
                                scroll={{ x: '500px', y: '40vh' }}
                                pagination={false}></Table>
                        </Card>
                    </div>
                </div>
            </Modal>
        </div>
    }
}

export default ShowConfirmApplicationModal;