/**
 * 
 * QueryCourierOrderPage
 * 快递单查询
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal,
    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 { $loadTemplate } from '../lodop/Common/Print.js';
import ShowCourierOrderModal from './courierorder/ShowCourierOrderModal';
import ShowPrescriptionModal from './courierorder/ShowPrescriptionModal';
import CourierOrderPrintModal from './courierorder/CourierOrderPrintModal';
import { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import moment from 'moment';
import store from 'store';

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

class QueryCourierOrderPage 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).format(dayFormat),
            admDateTo: moment(date).format(dayFormat)
        }
    }

    componentDidMount() {
        this.loadData(1);
        this.initData();
        this.loadCounrierOrder()
        this.loadStatusData()
        document.querySelector('.ant-table-body').style.height = (store.getState().tableHeight.y + 90) + 'px';
    }
    onSelectPrint = (ref) => {
        this.onChildPrint = ref
    }
    initData() {
        let data = {
            params: [{
                compontName: "QueryCourierOrderPage",
                type: "C",
                reactCode: ['QueryCourierOrderPage']
            }]
        }
        $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++) {
                        if (columns[i].dataIndex == 'opertion') {
                            dynColumns.push({
                                title: columns[i].title,
                                dataIndex: columns[i].dataIndex,
                                width: parseInt(columns[i].width),
                                align: columns[i].align || 'center',
                                render: (text, data) => {
                                    return <div>
                                        <Popconfirm title={this.setMessage('QueryCourierOrderPageCannel', 'descripts')} onConfirm={this.handleDel.bind(this, data)} >
                                            <span className='span' style={{ color: 'rgba(240,65,52,1)' }}>{this.setMessage('QueryCourierOrderPageCannelOrder', 'descripts')}</span>
                                        </Popconfirm>
                                        {/* <Divider type='vertical' /> */}
                                        <span style={{ color: '#1890ff', cursor: 'pointer', marginLeft: 10 }}
                                            onClick={this.showModal.bind(this, data)}>{this.setMessage('QueryCourierOrderPageExpress', 'descripts')}</span>

                                        <span style={{ color: '#1890ff', cursor: 'pointer', marginLeft: 10 }}
                                            onClick={this.onSubmitPrint.bind(this, data)}>{this.setMessage('QueryCourierOrderPagePrint', 'descripts')}</span>
                                    </div>
                                }
                            })
                        } else {
                            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({
                        column: dynColumns,
                        totalWidth: 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] : ''
    }

    onSubmitPrint(data) {
        this.onChildPrint.showModal(data)
        // var params = {
        //     params: [{
        //         orderID: data.orderID
        //     }]
        // }
        // $http.post('urlDeault', this, {
        //     code: "03030059",
        //     data: params,
        //     success: function (res) {
        //         if (res.errorCode == '0') {
        //             message.success('正在打印....')
        //             if (!Util.isEmpty(res.result)) {
        //                 var data = res.result
        //                 for (var i = 0; i < data.length; i++) {
        //                     $loadTemplate(data[i].template, data[i].printStr);
        //                 }
        //             }
        //         }
        //     }
        // });
    }

    loadData(page, pageSize, e) {
        var date = new Date();
        var params = {
            params: [{
                startDate: this.state.admDateFrom ? this.state.admDateFrom : moment(date).format(dayFormat),
                endDate: this.state.admDateTo ? this.state.admDateTo : moment(date).format(dayFormat),
                expressNo: this.state.expressNo,
                expressServiceID: this.state.expressServiceID,
                orderStatusID: this.state.orderStatusID,
                orderNo: this.state.orderNo,
                number: this.state.number
            }],
            pagination: [{
                pageSize: this.state.size == 'small' ? this.state.pageSize : PAGE_NUM_MORE_STATUS[0].code,
                currentPage: page
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030039",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.initData()
                    this.setState({
                        dataSource: res.result.data,
                        total: res.result.totalCount,
                        rowId: res.result.data && res.result.data.length > 0 ? res.result.data[0].patAdmID : '',
                        page: page,
                        search: e
                    })
                }
            }
        });
    }

    loadCounrierOrder() {
        var params = {
            params: [{
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030035",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.initData()
                    this.setState({
                        counrierOrder: res.result,
                    })
                }
            }
        });
    }

    loadStatusData() {
        var params = {
            params: [{}]
        }
        $http.post('urlDeault', this, {
            code: "03030038",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.initData()
                    this.setState({
                        statusData: res.result,
                    })
                }
            }
        });
    }

    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('QueryCourierOrderPageCannelSuccess', '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);
        });
    }

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

    showPrescriptionModal(data) {
        var params = {
            params: [{
                orderID: data.orderID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030050",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.setState({
                        prescriptData: res.result,
                        isShowPrescriptionModal: true
                    })
                }
            }
        });
    }

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

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

    onKeyDownMsg(e) {
        if (e.keyCode == '13') {
            this.loadData(1)
        }
    }

    render() {
        var date = new Date()
        //订单状态
        let statusOption = []
        this.state.statusData && this.state.statusData.map((item, index) => {
            statusOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })

        //快递服务
        let counrierOrderOption = []
        this.state.counrierOrder && this.state.counrierOrder.map((item, index) => {
            counrierOrderOption.push(<Option key={index} value={item.id}>{item.descripts}</Option>)
        })
        return <div style={{ background: '#F1F1F1' }} className='outpatient-body'>
            <div>
                {/**读卡 */}
                <ReadCard ref={ref => this.readCard = ref}></ReadCard>
                <ColumnAuthoritysModel
                    clientWidth='800px'
                    compontName="QueryCourierOrderPage"
                    configType="C"
                    onRef={this.onColumnRef}
                    reloadData={this.initData}
                />
                {/**物流信息弹框 */}
                <ShowCourierOrderModal isShow={this.state.isShowCourierOrderModal}
                    onHide={this.hideModal.bind(this, 'isShowCourierOrderModal')}
                    cuorierID={this.state.cuorierID}>
                </ShowCourierOrderModal>
                {/**处方详情 */}
                <ShowPrescriptionModal isShow={this.state.isShowPrescriptionModal}
                    prescriptData={this.state.prescriptData}
                    onHide={this.hideModal.bind(this, 'isShowPrescriptionModal')}>
                </ShowPrescriptionModal>
                <Card>
                    <Row>
                        <Col span={5}>
                            <RangeDatePicker label={this.setMessage('QueryCourierOrderPageDate', 'descripts')} format='YYYY-MM-DD' width={300}
                                locale={this.state.userData.language}
                                startDate={moment(date).format(dayFormat)} endDate={moment(date).format(dayFormat)}
                                startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                        </Col>

                        <Col span={4}>
                            {this.setMessage('QueryCourierOrderPageOrder', 'descripts')}
                            <Input placeholder={this.setMessage('QueryCourierOrderPageOrderNumber', 'descripts')} style={{ width: '70%' }} value={this.state.orderNo}
                                onKeyDown={this.onKeyDownMsg.bind(this)}
                                onChange={Util.commonInputChange.bind(this, 'orderNo')} />
                        </Col>

                        <Col span={3}>
                            {this.setMessage('QueryCourierOrderPageWaybil', 'descripts')}
                            <Input placeholder={this.setMessage('QueryCourierOrderPageWaybil', 'descripts')} style={{ width: '70%' }} value={this.state.expressNo}
                                onKeyDown={this.onKeyDownMsg.bind(this)}
                                onChange={Util.commonInputChange.bind(this, 'expressNo')} />
                        </Col>

                        <Col span={3} style={{ marginLeft: 5 }}>
                            {this.setMessage('QueryCourierOrderPagePatient', 'descripts')}
                            <Input placeholder={this.setMessage('QueryCourierOrderPagePatientID', 'descripts')} style={{ width: '70%' }} value={this.state.number}
                                onKeyDown={this.onKeyDownMsg.bind(this)}
                                onChange={Util.commonInputChange.bind(this, 'number')} />
                        </Col>

                        <Col span={3} style={{ marginLeft: 5 }}>
                            {this.setMessage('QueryCourierOrderPageService', 'descripts')}
                            <Select placeholder={this.setMessage('QueryCourierOrderPageService', 'descripts')} style={{ width: '70%' }} value={this.state.expressServiceID}
                                allowClear
                                onChange={Util.handleSelectChange.bind(this, 'expressServiceID')}>{counrierOrderOption}</Select>
                        </Col>

                        <Col span={3} style={{ marginLeft: 5 }}>
                            {this.setMessage('QueryCourierOrderPageStatus', 'descripts')}
                            <Select placeholder={this.setMessage('QueryCourierOrderPageOrderStatus', 'descripts')} style={{ width: '70%' }} value={this.state.orderStatusID}
                                    allowClear
                                onChange={Util.handleSelectChange.bind(this, 'orderStatusID')}>{statusOption}</Select>
                        </Col>

                        <Col span={2} style={{ marginLeft: 5 }}>
                            <Button type='primary' onClick={this.loadData.bind(this, 1, '', 'search')}>{this.setMessage('QueryCourierOrderPageSearch', 'descripts')}</Button>
                        </Col>

                    </Row>
                </Card>
                <div style={{ marginTop: 10 }}>
                    <Table columns={this.state.column} 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}
                        rowKey={(data) => {
                            return data.orderID
                        }}
                        scroll={{ x: this.state.totalWidth, y: store.getState().tableHeight.y + 140 + 'px' }}
                        onHeaderRow={column => {
                            return {
                                onDoubleClick: () => {
                                    this.columnRef.onOpenModel();
                                },
                            };
                        }}
                        pagination={false}>
                    </Table>
                    <CommonPagination size={this.state.size} current={this.state.page} total={this.state.total}
                        search={this.state.search}
                        onShowSizeChange={this.changePageSize.bind(this)} complete={true} dataSource={this.state.dataSource}
                        onChange={this.onChange.bind(this)} />
                    <CourierOrderPrintModal onSelectPrint={this.onSelectPrint}></CourierOrderPrintModal>
                </div>
            </div>
        </div>
    }
}

export default Form.create()(QueryCourierOrderPage);