/**
 * 快递单
 * 
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal, Tabs,
    DatePicker, Button, Switch, Icon, Divider, message, Popconfirm, Tooltip,
} from 'antd';
import { Util, dayFormat } from 'tools/index';
import { $http } from 'containers/config/https';
import ReadCard from 'components/readcard/ReadCard';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import RangeDatePicker from 'components/rangePicker/index';
import ShowNoDistributionTabPane from './courierorder/ShowNoDistributionTabPane';
import ShowHaveDistributionTabPane from './courierorder/ShowHaveDistributionTabPane';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import './courierStyle/index.less';
import moment from 'moment';
import store from 'store';

const { RangePicker } = DatePicker;
const Search = Input.Search;
const Option = Select.Option;
const { TabPane } = Tabs;

class ExpressOrderPage extends React.Component {

    constructor(props) {
        super(props);
        var date = new Date()
        var userData = JSON.parse(sessionStorage.getItem('userData'));
        this.state = {
            dataSource: [],
            total: 0,
            page: 1,
            pageSize: 10,
            size: 'small',
            curPageDetail: PAGE_NUM_MORE_STATUS[0].code,
            userData: userData,
            admDateFrom: moment(date).subtract(1, 'days').format(dayFormat),
            admDateTo: moment(date).format(dayFormat),
            activeKey: '1',
            orderStatus: "1",
            isTime: true,
            time: 30
        }
    }

    componentDidMount() {
        this.loadData(1);
        this.initData();
        this.loadCardType()
        this.loadLocalMessage()
        this.handleSwithChange(true)
        document.querySelector('.ant-table-body').style.height = store.getState().tableHeight.y + 130 + 'px';
    }
    componentWillUnmount() {
        clearInterval(this.timerID);
    }
    //获取卡类型
    loadCardType() {
        var params = {
            params: [{
                cardTypeFlag: '1',//卡类型
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030005",
            data: params,
            success: function (res) {
                var cardStatus = '', replaceZero = '', cardLength = '', readMode = ''
                if (res.errorCode == '0') {
                    if (res.cardType && res.cardType.length > 0) {
                        var cardType = res.cardType;
                        for (var i = 0; i < cardType.length; i++) {
                            if (cardType[i].defaultFlag == 'Y') {
                                cardStatus = cardType[i].id,
                                    replaceZero = cardType[i].replenishZero
                                cardLength = cardType[i].cardLength
                                readMode = cardType[i].readMode
                            }
                        }
                    }
                    this.setState({
                        cardTypeData: res.cardType,
                        cardStatus: cardStatus,
                        readMode: readMode,
                        cardLength: cardLength,
                        replaceZero: replaceZero,
                    })
                }
            }
        });
    }

    loadLocalMessage() {
        let data = {
            params: [{
                // compontName: "QueryCourierOrderPage",
                type: "C",
                reactCode: ['ExpressOrderPage']
            }]
        }
        $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
                    })
                }
            }
        })

    }

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

    initData() {
        this.columns = [{
            title: '信息',
            dataIndex: 'queStatusDesc',
            width: 400,
            align: 'left',
            render: (text, data) => {
                return <div><div style={{ borderRight: '1px solid #EEEEEE', height: 79, display: 'flex' }}>
                    <div className={data.patSexCode == '1' ?
                        'splice-boys' : (data.patSexCode == '2' ? 'splice-girls' : 'splice-others')}></div>
                    <div style={{ height: 79, borderRight: '1px solid #EEEEEE' }}></div>
                    {!Util.isEmpty(data) ? <div style={{ fontSize: '16px' }}>
                        {/* <div style={{ padding: '10px 0 0 20px' }}></div> */}
                        <div style={{ padding: '10px 0 0 20px' }}>
                            <span style={{ color: '#333333', fontWeight: 'bold', cursor: 'pointer' }}>
                                {data.patName || '--'}</span><Divider type="vertical" />
                            <span>{data.patSexDesc || '--'}</span><Divider type="vertical" />
                            <span>{data.patAge || '--'}</span><Divider type="vertical" />
                            <span><Icon className='patNo-splice' />{data.patNo || '--'}</span>
                        </div>
                        <div style={{ fontWeight: 400, color: '#666666', fontSize: '16px', padding: '10px 0 0 20px' }}>
                            <span>{data.patMobile || '--'}</span><Divider type="vertical" />
                            <span><Icon className='statusdesc-splice' />{data.patSocialStatusDesc || '--'}</span><Divider type="vertical" />
                            <span><Icon className='typeDesc-splice' />{data.patTypeDesc || '--'}</span><Divider type="vertical" />
                            {/* <span>{/**{this.setMessage('DoctorAdviceModalAccount', 'descripts')} */}
                            {/* <span style={{ color: '#1999db' }}><Icon className='account-splice' />{data.accountBalance || '--'}</span> </span>  */}
                        </div>
                    </div> : <span style={{ color: '#999999', lineHeight: '79px', marginLeft: '20%' }}>{this.setMessage('ExpressOrderPageNoMsg', 'descripts')}</span>}
                </div>


                    <div style={{ padding: '5px 0 0 10px', color: '#666666', fontSize: '14px', borderTop: '1px solid #e8e8e8' }}>
                        <div style={{ float: 'left' }}>
                            <div>{this.setMessage('ExpressOrderPageOrder', 'descripts')}<span>{data.orderNo}</span></div>
                            <div>{this.setMessage('ExpressOrderPageDate', 'descripts')}<span>{data.orderDate}</span></div>
                        </div>
                        <div style={{ float: 'right', marginRight: 5 }}>
                            <div style={{ color: 'red'}}>{data.status}</div>
                        <div style={{ color: '#1999db' }}>{data.expServiceDesc || '--'}</div>
                        </div>
                    </div>
                </div>
            }
        }
        ]
    }

    loadData(name) {
        var date = new Date();
        var params = {
            params: [{
                dateFrom: this.state.admDateFrom ? this.state.admDateFrom : moment(date).subtract(1, 'days').format(dayFormat),
                dateTo: this.state.admDateTo ? this.state.admDateTo : moment(date).format(dayFormat),
                hospID: this.state.userData.hospID,
                number: this.state.number,
                cardNo: this.state.patCardNo,
                orderStatus: this.state.orderStatus,
                cardTypeID: this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus),
                dispNo: this.state.dispNo
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030057",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                        record: '',
                        orderID: '',
                        distributionData: [],
                        orderID: (name == 'dispNo' || name == 'search') && !Util.isEmpty(res.result.data) ? res.result.data[0].orderID : '',
                        record: (name == 'dispNo' || name == 'search') && !Util.isEmpty(res.result.data) ? res.result.data[0] : '',
                    }, () => {
                        if ((name == 'dispNo' || name == 'search') && !Util.isEmpty(res.result.data)) {
                            this.loadExpressMessage(res.result.data[0])
                        }
                    })
                }
            }
        });
    }

    handleDel(data) {
        var params = {
            params: [{
                orderID: data.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030037",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ExpressOrderPageCannel', 'descripts'))
                    this.loadData(1)
                }
            }
        });
    }

    showModal(data) {
        this.setState({
            isShowCourierOrderModal: true,
            cuorierID: data.orderID
        })
    }

    hideModal(name) {
        this.setState({
            [name]: false
        })
    }

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

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

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

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

    loadNodisbtn = (refs) => {
        this.noBtnRefs = refs
    }

    loadHavebtn = (refs) => {
        this.haveRefs = refs
    }

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

    loadExpressMessage(record) {
        var params = {
            params: [{
                orderID: record ? record.orderID : '',
                //orderID: this.state.record ? this.state.record.orderID : '',
                // hospID: this.state.userData.hospID,
                // userID: this.state.userData.userID,
                language: this.state.userData.language,
            }]
        }
        var orderID = record ? record.orderID : ''
        if (orderID === "") {
            this.setState({
                distributionData: [],
                adressMsg: ""
            })
            return
        }
        $http.post('urlDeault', this, {
            code: "03030058",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        distributionData: res.result.order,
                        adressMsg: res.result.address
                    })
                }
            }
        });
    }

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

    //切换卡类型
    changeCardType(name, e) {
        var { cardTypeData } = this.state;
        for (var i = 0; i < cardTypeData.length; i++) {
            if (e == cardTypeData[i].id) {
                this.setState({
                    cardLength: cardTypeData[i].cardLength,
                    replaceZero: cardTypeData[i].replenishZero,
                    cardTypeId: cardTypeData[i].id,
                    readMode: cardTypeData[i].readMode,
                    [name]: e,
                    inputStatus: true
                })
            }
        }
    }

    loadKeyDown(e) {
        if (e.keyCode == '13') {
            this.setState({//自动补0，渲染到组件中
                patCardNo: this.state.replaceZero == 'Y' ? (Array(parseInt(this.state.cardLength)).join(0) + this.state.patCardNo).slice(-parseInt(this.state.cardLength)) : this.state.patCardNo
            }, () => {
                if (!Util.isEmpty(this.state.patCardNo)) {
                    this.loadData('search')
                } else {
                    this.setState({
                        adressMsg: '',
                        orderID: '',
                        record: ''
                    }, () => {
                        this.loadData()
                    })
                }
            })
        }
    }


    handleReadCard() {
        var cardType = this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus);
        this.readCard.ReadCard(cardType, "R", (json) => {
            this.setState({ readPatID: json && json.patInfo ? json.patInfo.patID : '', patCardNo: json.cardNo, readStatus: 'read' }, () => {
                if (!Util.isEmpty(this.state.patCardNo)) {
                    this.loadData('search')
                } else {
                    this.setState({
                        adressMsg: '',
                        orderID: '',
                        record: ''
                    }, () => {
                        this.loadData()
                    })
                }
            })
        })
    }

    searchPatientMsg(name, e) {
        if (e.keyCode == '13') {
            if (!Util.isEmpty(this.state.number)) {
                this.loadData(name)
            } else {
                this.setState({
                    adressMsg: '',
                    orderID: '',
                    record: ''
                }, () => {
                    this.loadData()
                })
            }
        }
    }

    changeTabpane(e) {
        this.setState({
            activeKey: e
        })
    }
    handleSwithChange = (v) => {
        this.setState({
            isTime: v
        })
        if (v) {
            this.timerID = setInterval(
                () => this.tick(),
                this.state.time * 1000
            );
        } else {
            clearInterval(this.timerID);
        }
    }
    tick = () => {
        var date = new Date();
        var params = {
            params: [{
                dateFrom: this.state.admDateFrom ? this.state.admDateFrom : moment(date).subtract(1, 'days').format(dayFormat),
                dateTo: this.state.admDateTo ? this.state.admDateTo : moment(date).format(dayFormat),
                hospID: this.state.userData.hospID,
                number: this.state.number,
                cardNo: this.state.patCardNo,
                orderStatus: this.state.orderStatus,
                cardTypeID: this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus),
                dispNo: this.state.dispNo
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030057",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        dataSource: res.result.data,
                    })
                }
            }
        });
    }
    render() {
        var date = new Date()

        //卡类型
        let cardTypeOption = []
        this.state.cardTypeData && this.state.cardTypeData.map((item, index) => {
            cardTypeOption.push(<Option key={index} value={item.id}>
                <Tooltip title={this.state.userData.language == 'EN' ? item.enDescripts : item.descripts}>
                    {this.state.userData.language == 'EN' ? (item.enDescripts || item.descripts) : item.descripts}</Tooltip></Option>)
        })
        return <div style={{ background: '#F1F1F1' }} className='outpatient-body'>
            <div>
                {/**读卡 */}
                <ReadCard ref={ref => this.readCard = ref}></ReadCard>
                <Card>
                    <Row>
                        <Col span={5}>
                            <Select style={{ width: '100px' }} placeholder={this.setMessage('ExpressOrderPageSelect', 'descripts')}
                                allowClear
                                showSearch
                                value={this.state.patCardTypeID ? this.state.patCardTypeID : (this.state.cardStatus)}
                                getPopupContainer={triggerNode => triggerNode.parentNode}
                                onChange={this.changeCardType.bind(this, 'patCardTypeID')}>
                                {cardTypeOption}
                            </Select>
                            <Search
                                placeholder={this.setMessage('ExpressOrderPageRead', 'descripts')} style={{ width: '250px', marginLeft: 10 }}
                                onChange={Util.commonInputChange.bind(this, 'patCardNo')}
                                value={this.state.patCardNo}
                                enterButton={this.setMessage('ExpressOrderPageCall', 'descripts')}
                                readOnly={this.state.readMode == 'R' ? true : false}
                                onPressEnter={(e) => console.dir(e)}
                                onKeyDown={this.loadKeyDown.bind(this)}
                                onSearch={this.handleReadCard.bind(this)}
                            />
                        </Col>
                        <Col span={3}>
                            {this.setMessage('ExpressOrderPageIdentity', 'descripts')}<Input onChange={Util.commonInputChange.bind(this, 'number')}
                                onKeyDown={this.searchPatientMsg.bind(this, 'search')}
                                placeholder={this.setMessage('ExpressOrderPageMessage', 'descripts')} style={{ width: '67%' }} />
                        </Col>
                        <Col span={3}>
                            {this.setMessage('ExpressOrderPagedosage', 'descripts')}<Input onChange={Util.commonInputChange.bind(this, 'dispNo')}
                                onKeyDown={this.searchPatientMsg.bind(this, 'dispNo')}
                                placeholder={this.setMessage('ExpressOrderPageNo', 'descripts')} style={{ width: '67%' }} />
                        </Col>
                        <Col span={3}>
                            {this.setMessage('ExpressOrderPageStatus', 'descripts')}
                            <Select placeholder={this.setMessage('ExpressOrderPageOrderStatus', 'descripts')} style={{ width: '67%' }} value={this.state.orderStatus}
                                onChange={Util.handleSelectChange.bind(this, 'orderStatus')} allowClear>
                                <Option key='1' value='1'>{this.setMessage('ExpressOrderPageNodistribution', 'descripts')}</Option>
                                <Option key='2' value='2'>{this.setMessage('ExpressOrderPageHave', 'descripts')}</Option>
                                <Option key='3' value='3'>取消配送</Option>
                            </Select>
                        </Col>
                        <Col span={5}>
                            <RangeDatePicker label={this.setMessage('ExpressOrderPageDates', 'descripts')} format='YYYY-MM-DD' width={300}
                                locale={this.state.userData.language}
                                startDate={moment(date).subtract(1, 'days').format(dayFormat)} endDate={moment(date).format(dayFormat)}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                        </Col>

                        <Col span={1}>
                            <Button type='primary' onClick={this.loadData.bind(this, 1, '', 'search')}>{this.setMessage('ExpressOrderPageSearch', 'descripts')}</Button>
                        </Col>
                        <Col span={2} style={{ marginTop: "6px" }}>
                            {this.setMessage('ExpressOrderPageRefresh', 'descripts')}：
                        <Switch checkedChildren={this.setMessage('ExpressOrderPageYes', 'descripts')}
                                unCheckedChildren={this.setMessage('ExpressOrderPageNos', 'descripts')} checked={this.state.isTime} onChange={(val) => this.handleSwithChange(val, 'isTime')} />
                        </Col>
                        <Col span={2}>
                            <Input type="number" value={this.state.time} onChange={Util.commonInputChange.bind(this, 'time')}
                                placeholder={this.setMessage('ExpressOrderPageInterval', 'descripts')}
                                style={{ width: '65%' }}
                            /> (s)
                        </Col>
                    </Row>
                </Card>
                <Card style={{ background: '#F1F1F1' }} className='express-order-table'>
                    <Card style={{ float: 'left', width: '25%' }}>
                        <Table columns={this.columns} style={{ background: 'white', height: store.getState().tableHeight.y + 140 + 'px' }}
                            dataSource={this.state.dataSource}
                            loadData={this.loadData.bind(this)}
                            onRow={this.onClickRow} bordered
                            rowClassName={this.setRowClassName}
                            showHeader={false}
                            rowKey={(data) => {
                                return data.id
                            }}
                            scroll={{ y: store.getState().tableHeight.y + 140 + 'px' }}
                            pagination={false}>
                        </Table>
                    </Card>
                    <Card style={{ float: 'right', width: '74.9%', height: store.getState().tableHeight.y + 162 + 'px' }}>
                        <ShowHaveDistributionTabPane distributionData={this.state.distributionData}
                            adressMsg={this.state.adressMsg}
                            orderID={this.state.orderID}
                            patID={this.state.patID}
                            loadData={this.loadData.bind(this)}
                            record={this.state.record} handleTableInfo={this.loadExpressMessage.bind(this)} />
                        {/* <Tabs type='card' onChange={this.changeTabpane.bind(this)} activeKey={this.state.activeKey}>
                            <TabPane tab="未配送" key="1"></TabPane>
                            <TabPane tab="已配送" key="2"><ShowHaveDistributionTabPane /></TabPane>
                        </Tabs> */}
                    </Card>
                </Card>
            </div>
        </div>
    }
}

export default Form.create()(ExpressOrderPage);