/*
* 引用模版
* */

import React, { Component } from 'react';
import { Form, Modal, Table, message, Tooltip } from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import RangeDatePicker from 'components/rangePicker/index';
import '../style/index.less';
import moment from 'moment';

class CopyTextModal extends Component {

    constructor(props) {
        super(props);
        var date = new Date();
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        var titleData = JSON.parse(sessionStorage.getItem('titleData'))
        var patientData = JSON.parse(sessionStorage.getItem('patientData'))
        // var newDate = date.setMonth(date.getMonth() - 1);
        // var endDate = date.setMonth(date.getMonth() + 1);
        this.state = {
            leftData: [],
            rightData: [],
            userData: userData,
            titleData: titleData,
            patientData: patientData,
            total: 0,
            page: 1,
            pageSize: 10,
            codePage: 1,
            ids: [],
            totalCount: 0,
            date: date,
            admDateFrom: '',
            admDateTo: '',
            code: []
        }
    }
    componentWillReceiveProps(nextProp) {
        if (nextProp.isShow === true) {
            var date = new Date();
            var newDate = date.setMonth(date.getMonth() - 1);
            var endDate = date.setMonth(date.getMonth() + 1);
            this.setState({
                admDateFrom: moment(newDate).format(dayFormat),
                admDateTo: moment(endDate).format(dayFormat),
            }, () => {
                this.loadData()
                this.loadCommonModal()
            })
        } else if (this.props.isShow === false) {
            this.cleanInput();
        }
    }

    componentDidMount() {
        // this.initData();
        this.loadData();
    }

    loadCommonModal() {
        let data = {
            params: [{
                compontName: "DoctorAdviceModal",
                type: "C",
                reactCode: ['DoctorAdviceModal']
            }]
        }
        $http.post('urlDeault', this, {
            code: "01040073",
            data: data,
            success: (res) => {
                if (+res.errorCode === 0) {
                    this.setState({
                        localeProvider: this.state.userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
                    },()=>{
                        this.initData()
                    })
                }
            }
        })
    }

    initData() {
        this.columns = [
            {
                title: this.setMessage('DoctorAdviceModalDate','descripts'),
                dataIndex: 'admDate',
                width: 130,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalDepartment','descripts'),
                dataIndex: 'admLocDesc',
                width: 130,
                align: 'left',
                render: (text, data) => {
                    return <Tooltip title={data.admLocDesc}><div className='copy-text-ellipisis'>{data.admLocDesc}</div></Tooltip>
                }
            }, {
                title: this.setMessage('DoctorAdviceModalDoctor','descripts'),
                dataIndex: 'admDocDesc',
                width: 120,
                align: 'left',
            },
        ]
        this.rightColumn = [
            {
                title: this.setMessage('DoctorAdviceModalNumber','descripts'),
                dataIndex: '1',
                width: 50,
                align: 'left',
                render: (text, data, index) => {
                    return <span style={{ width: 50 }}>{index + 1}</span>
                    // return {
                    //     props: {
                    //         className: data.ordMinFlag == 'Y' ? 'rowClass' : ''
                    //     },
                    //     children: <span style={{ width: 50 }}>{index + 1}</span>
                    // }
                }
            }, {
                title: this.setMessage('DoctorAdviceModalAssociation','descripts'),
                dataIndex: 'ordLinkSeqNo',
                width: 80,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalSpecification','descripts'),
                dataIndex: 'ordMedItemDesc',
                width: 340,
                align: 'left',
                render: (text, data) => {
                    return <Tooltip title={data.ordMedItemDesc}><div>{data.ordMedItemDesc}</div></Tooltip>
                }
            }, {
                title: this.setMessage('DoctorAdviceModalUsageDesc','descripts'),
                dataIndex: 'ordUsageDesc',
                width: 100,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalFrequence','descripts'),
                dataIndex: 'ordFrequenceDesc',
                width: 140,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalordDose','descripts'),
                dataIndex: 'ordDose',
                width: 100,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalordDurQty','descripts'),
                dataIndex: 'ordDurQty',
                width: 120,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalordPrice','descripts'),
                dataIndex: 'ordPrice',
                width: 100,
                align: 'right',
            }, {
                title: this.setMessage('DoctorAdviceModalordQty','descripts'),
                dataIndex: 'ordQty',
                width: 100,
                align: 'left',
            }, {
                title: this.setMessage('DoctorAdviceModalAdditional','descripts'),
                dataIndex: '111',
                width: 120,
                align: 'left',
            },
        ]
    }

    loadData(page, pageSize, e) {
        var params = {
            params: [{
                // patID: this.state.titleData ? this.state.titleData.patID : '',
                patID: this.state.patientData ? this.state.patientData.patID : '',
                hospID: this.state.userData ? this.state.userData.hospID : '',
                admDateFrom: this.state.admDateFrom,
                admDateTo: this.state.admDateTo
            }],
            // pagination: [{
            //     pageSize: this.state.pageSize,
            //     currentPage: page
            // }]

        }
        $http.post('urlDeault', this, {
            code: "03050052",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        leftData: res.result.data,
                        total: res.result.totalCount
                    })
                }
            }
        });
    }

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

    //清空输入框
    cleanInput() {
        var date = new Date()
        var newDate = date.setMonth(date.getMonth() - 1);
        var endDate = date.setMonth(date.getMonth() + 1);
        this.setState({
            ids: [],
            admID: '',
            code: [],
            leftData: [],
            rightData: [],
            admDateFrom: moment(newDate).format(dayFormat),
            admDateTo: moment(endDate).format(dayFormat),
            showTime: true
        })
    }

    changeRegistrTime(date, dateStr) {
        this.setState({
            admDateFrom: dateStr[0],
            admDateTo: dateStr[1]
        }, () => {
            this.loadData(1)
        })
    }

    startChange(date) {
        this.setState({
            admDateFrom: date,
        }, () => {
            this.loadData(1)
        })
    }

    endChange(date) {
        this.setState({
            admDateTo: date,
        }, () => {
            this.loadData(1)
        })
    }

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

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

    loadRightData(value, page, pageSize) {
        var params = {
            params: [{
                admID: this.state.admID,
                quoteFlag: 'Y'
            }],
            // pagination: [{
            //     pageSize: this.state.pageSize,
            //     currentPage: page
            // }]

        }
        $http.post('urlDeault', this, {
            code: "03050022",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        rightData: res.result.data,
                        totalCount: res.result.totalCount
                    })
                }
            }
        });
    }

    //分页切换
    onChange(e) {
        this.setState({ page: e }, () => {
            this.loadData(e);
        });
    }

    //分页切换
    changePageSize(current, pageSize) {
        this.setState({ pageSize: pageSize, page: current }, () => {
            this.loadData(current, pageSize);
        });
    }

    changeAdvicePage(current, pageSize) {
        this.setState({ newPage: pageSize, codePage: current }, () => {
            this.loadRightData('', current, pageSize);
        });
    }

    changeData(e) {
        this.setState({ codePage: e }, () => {
            this.loadRightData('', e, '');
        });
    }

    onSelectChange(ids, useData) {
        this.setState({
            useData:useData
        })
    }

    onSelect(data, flag) {
        var { rightData, ids, useData } = this.state;
        var code = []
        var sourceData = []
        if (Util.isEmpty(data.checkStatus) || data.checkStatus == false) {
            for (var i = 0; i < rightData.length; i++) {
                if (data.ordSeqNo == rightData[i].ordSeqNo || data.ordSeqNo == rightData[i].ordLinkSeqNo) {
                    // data['checkStatus'] = true
                    this.state.rightData[i]['checkStatus'] = true
                    this.state.ids.push(rightData[i].ordID)
                }
            }
        } else if (data.checkStatus == true) {
            data.checkStatus = false
            if (!Util.isEmpty(useData)) {
                for (var i = 0; i < useData.length; i++) {
                    for (var j = 0; j < ids.length; j++) {
                        if ((useData[i].ordID) == ids[j]) {
                            sourceData.push(useData[i])
                        }
                    }
                }
                for (var i = 0; i < sourceData.length; i++) {
                    if ((data.ordID !== sourceData[i].ordID)) {
                        if(data.ordSeqNo == sourceData[i].ordLinkSeqNo){
                            this.state.ids = []
                            this.setState({})
                        }else{
                            code.push(sourceData[i].ordID)
                            this.setState({ ids: code })
                        }
                    } else if (sourceData.length == 1) {
                        this.state.ids = []
                    }
                }
            } else {
                this.state.ids = []
            }
        }
        this.setState({})
    }

    onSelectAll(flag, selectedRows, changeRows) {
        for (var i = 0; i < changeRows.length; i++) {
            if (flag) {
                changeRows[i]['checkStatus'] = true
                this.state.ids.push(changeRows[i].ordID)
            } else {
                changeRows[i]['checkStatus'] = false
                this.state.ids = []
            }
        }
        this.setState({})
    }

    //提交
    onSubmit() {
        var { ids, code } = this.state;
        if (Util.isEmpty(ids)) {
            // message.error('请选择您需要引用的医嘱处方')
            message.error(this.setMessage('DoctorAdviceModalquito','descripts'),this.state.userData && this.state.userData.messageTime)
            return
        }
        let { onSubmit } = this.props;
        var admID = this.state.patientData ? this.state.patientData.admID : '';

        onSubmit && onSubmit(admID, ids);
    }

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

    render() {
        var { ids, code } = this.state;
        const rowSelection = {
            ids,
            onChange: this.onSelectChange.bind(this),
            onSelect: this.onSelect.bind(this),
            onSelectAll: this.onSelectAll.bind(this),
            selectedRowKeys: ids,
        }
        var date = new Date()
        return <div>
            <Modal className='copy-modal'
                title={this.setMessage('DoctorAdviceModalhisp','descripts')}
                maskClosable={false}
                okText={this.state.userData.language == 'EN'?'Submit':'确定'}
                cancelText={this.state.userData.language == 'EN'?'Cancel':'取消'}
                visible={this.props.isShow}
                onCancel={this.closeModal.bind(this)}
                onOk={this.onSubmit.bind(this)}>
                <div>
                    <div style={{ width: '26%', float: 'left' }}>
                        <Table columns={this.columns}
                        className='copy-modal-antdBody'
                            dataSource={this.state.leftData}
                            scroll={{ y: '35vh', x: 400 }} bordered
                            title={() => {
                                return <div>
                                    <span>{this.setMessage('DoctorAdviceModalFind','descripts')}</span>
                                    {/* <RangePicker onChange={this.changeRegistrTime.bind(this)} 
                                    defaultValue={[moment(this.state.admDateFrom,dayFormat),moment(date,dayFormat)]}/> */}
                                    <RangeDatePicker format='YYYY-MM-DD' width={280} isShow={this.state.showTime}
                                        startDate={this.state.admDateFrom?moment(this.state.admDateFrom).format(dayFormat):''}
                                        locale={this.state.userData.language}
                                        endDate={this.state.admDateTo?moment(this.state.admDateTo).format(dayFormat):''}
                                        startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                                </div>
                            }}
                            rowKey={(data) => {
                                return data.admID
                            }}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                            pagination={false}></Table>
                        {/* <Pagination
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.page}
                            total={this.state.total}
                            onShowSizeChange={this.changePageSize.bind(this)}
                            onChange={this.onChange.bind(this)}
                            style={{ textAlign: "right", marginTop: '13px' }}
                        /> */}
                    </div>

                    <div style={{ width: '72.5%', float: 'right' }}>
                        <Table columns={this.rightColumn}
                            dataSource={this.state.rightData}
                            rowSelection={rowSelection}
                            scroll={{ y: '35vh', x: 1300 }} bordered
                            title={() => {
                                return <span>{this.setMessage('DoctorAdviceModalWest','descripts')}</span>
                            }}
                            rowKey={(data) => {
                                return data.ordID
                            }}
                            pagination={false}></Table>
                        {/* {this.state.totalCount>10?<Pagination
                            size="small"
                            showQuickJumper
                            showSizeChanger
                            defaultCurrent={1}
                            current={this.state.codePage}
                            total={this.state.totalCount}
                            onShowSizeChange={this.changeAdvicePage.bind(this)}
                            onChange={this.changeData.bind(this)}
                            style={{ textAlign: "right", marginTop: '13px' }}
                        />:null} */}
                    </div>

                </div>
            </Modal></div>
    }
}

export default Form.create()(CopyTextModal);