/**
 * 未配送
 */

import React from 'react';
import {
    Card, Table, Input, Form, Select, Row, Col, Checkbox, Modal, Tabs,
    DatePicker, Button, Switch, Icon, Divider, message, Popconfirm, Tooltip, Menu, Spin
} 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 { PAGE_NUM_MORE_STATUS } from 'tools/statusConstants';
import { $loadTemplate } from '../../lodop/Common/Print.js';
import SendExpress from '../component/SendExpress';
import ShowPrescriptionModal from './ShowPrescriptionModal';
import ShowPrintListModal from './ShowPrintListModal';
import ShowUpdateAddressModal from './ShowUpdateAddressModal';
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;
const noData = require('../image/noData.png')

class ShowHaveDistributionTabPane 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',
            userData: userData,
            activeKey: '1',
            presc: [],
            cmpresc: [],
            specNos: [],
            checkNos: [],
            curStatus: false,
            loading: false
        }
    }

    componentWillReceiveProps(nextProp) {
        if (!Util.isEmpty(nextProp.distributionData) || !Util.isEmpty(nextProp.adressMsg)) {
            this.setState({
                distributionData: nextProp.distributionData,
                record: nextProp.record,
                adressMsg: nextProp.adressMsg,
                orderID: nextProp.orderID,
                patID: nextProp.patID,
            })
        } else {
            this.setState({
                distributionData: [],
                record: '',
                adressMsg: '',
                patID: '',
            })
        }
    }

    componentDidMount() {
        this.loadLocalMessage()
    }

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

    loadExpressMessage() {
        var { distributionData } = this.state;
        let distributionDataOption = []
        distributionData && distributionData.map((item, index) => {
            distributionDataOption.push(
                <Col span={5} style={{ margin: '3px 5px' }}><Card key={index} hoverable title={<div>
                    <div style={{ color: 'rgb(51, 51, 51)', fontWeight: 'bold' }}>
                        <span>{item.title}</span>&nbsp;&nbsp;
                        <span>{item.prescNo}</span>
                    </div>
                    <div><span>{this.setMessage('ShowHaveDistributionTabPaneDepart', 'descripts')}{item.relocDesc}</span>&nbsp;&nbsp;
                <span>{item.telphone}</span>
                    </div>
                </div>} extra={<span>{item.status}</span>}>
                    <div style={{ height: '120px', overflow: 'auto' }}>
                        {this.loadSunBody(item.data)}
                    </div>
                    <div style={{ textAlign: 'center', color: '#1890ff', cursor: 'pointer' }}
                        onClick={this.showPrescriptionModal.bind(this, item)}>{this.setMessage('ShowHaveDistributionTabPanePrescription', 'descripts')}</div>
                </Card></Col>
            )
        })
        return distributionDataOption
    }

    loadSunBody(data) {
        var sunBodyOption = []
        data && data.map((item, index) => {
            sunBodyOption.push(<div key={index} style={{
                height: 30, lineHeight: '30px',
                width: '100%', display: 'flex',
            }}>
                <div style={{ width: '60%' }} className='sunbody-esplise'><Tooltip title={item.ordDesc}>{item.ordDesc}
                </Tooltip></div>
                <span style={{ color: 'rgb(77, 193, 130)', width: '20%' }} className='sunbody-esplise'>
                    <Tooltip title={item.medOtherInfo}>{item.medOtherInfo}</Tooltip></span>
                <div style={{ width: '19.8%', textAlign: 'right' }}>{item.ordQty}</div>
            </div>)
        })
        return sunBodyOption
    }

    //寄快递
    handleSendExpress(status) {
        // this.expressRef.showModal()
        this.setState({
            isShowPrintListModal: true,
            receiveStatus: status
        })
    }

    onRef = (ref) => {
        this.expressRef = ref
    }

    handleTableInfo = () => {
        this.clearInput()
        var { handleTableInfo } = this.props;
        handleTableInfo && handleTableInfo()
    }

    clearInput() {
        this.setState({
            presc: [],
            cmpresc: [],
            specNos: [],
            checkNos: [],
            newCmpresc: [],
            newSpecNosc: [],
            newCheckNos: [],
            newPresc: [],
            distributionData: []
        })
    }

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

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

    onSubmit(data) {
        var params = {
            params: [{
                orderID: this.state.receiveStatus == 'again' ? undefined : this.state.orderID,
                patID: this.state.patID,
                expressID: data.expressID,
                expressPayID: data.expressPayID,
                sendStartDate: data.sendStartDate,
                sendStartTime: data.sendStartTime,
                parcelQuantity: data.parcelQuantity,
                expressType: data.expressType,
                tempRange: data.tempRange,
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                oldOrderID: this.state.receiveStatus == 'again' ? String(this.state.orderID) : undefined
            }]
        }
        $http.post('urlDeault', this, {
            code: this.state.receiveStatus == 'again' ? '03030089' : "03030061",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPaneOperation', 'descripts'))
                    var { handleTableInfo, loadData } = this.props;
                    handleTableInfo && handleTableInfo()
                    loadData && loadData(1)
                    this.hideModal('isShowPrintListModal')
                    if (data.recipeList == true) {
                        this.onSubmitRecipeList()//打印处方
                    }
                    if (data.printList == true) {
                        this.onSubmitPrint()//打印清单
                    }
                    if (data.label == true) {
                        this.onSubmitPrintLabel()//打印配送标签
                    }
                    if (data.distr == true) {
                        this.handlePrintDistribution()//打印诊断证明
                    }
                    if (data.EMR == true) {
                        this.handlePrintEMR()//打印病历
                    }
                }
            }
        });
    }

    onSubmitRecipeList() {
        var params = {
            params: [{
                orderID: this.state.orderID,
                userID: this.state.userData.userID,
                hospID: this.state.userData.hospID,
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030066",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }

    onSubmitPrint() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030059",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    // if (!Util.isEmpty(res.result.data)) {
                    //     $loadTemplate(res.result.template, res.result.data);
                    // }
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }
    onSubmitPrintLabel() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03030071",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.hideModal('isShowPrintListModal')
                    // if (!Util.isEmpty(res.result.data)) {
                    //     $loadTemplate(res.result.template, res.result.data);
                    // }
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        });
    }

    updateAddressModal() {
        this.setState({
            isShowUpdateAddressModal: true
        })
    }

    updateAddressMsg(data) {
        var params = {
            params: [{
                receiveCityID: data.receiveCityID,
                receiveAreaID: data.receiveAreaID,
                receiveVillageID: data.receiveVillageID,
                receiveProvinceID: data.receiveProvinceID,
                receiveAddress: data.receiveAddress,
                receiveMobile: data.receiveMobile,
                receiveName: data.receiveName,
                hospID: this.state.userData.hospID,
                userID: this.state.userData.userID,
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: '03030062',
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPaneModified', 'descripts'))
                    this.hideModal('isShowUpdateAddressModal')
                    var { handleTableInfo } = this.props;
                    handleTableInfo && handleTableInfo()
                }
            }
        })
    }
    //打印发票 处方 清单
    handlePrint = (flag) => {
        var params = {
            params: [{
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: flag == "1" ? '03030066' : (flag == '2' ? '03030059' : (flag == '3' ? '03030070' : '03030071')),
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success(this.setMessage('ShowHaveDistributionTabPanePrinting', 'descripts'))
                    if (!Util.isEmpty(res.result)) {
                        var data = res.result
                        for (var i = 0; i < data.length; i++) {
                            $loadTemplate(data[i].template, data[i].printStr);
                        }
                    }
                }
            }
        })
    }

    //取消订单
    handleCannelOrder() {
        var params = {
            params: [{
                orderID: this.state.orderID
            }]
        }
        $http.post('urlS', this, {
            code: '03030037',
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    message.success('取消成功');
                    var { handleTableInfo, loadData } = this.props;
                    handleTableInfo && handleTableInfo()
                    loadData && loadData(1)
                }
            }
        })
    }

    //打印诊断证明
    handlePrintDistribution() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                locID: this.state.userData.locID,
                userID: this.state.userData.userID,
                // admID: this.state.patientData && this.state.patientData.admID,
                expressOrderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "03050232",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var print = res.result;
                    if (!Util.isEmpty(print)) {
                        for (var i = 0; i < print.length; i++) {
                            $loadTemplate(print[i].template, print[i].printStr);
                        }
                    }
                    message.success('打印成功！')
                }
            }
        });
    }

    //打印病历
    handlePrintEMR() {
        var params = {
            params: [{
                hospID: this.state.userData.hospID,
                // locID: this.state.userData.locID,
                // userID: this.state.userData.userID,
                // admID: this.state.patientData && this.state.patientData.admID,
                expressOrderID: this.state.orderID
            }]
        }
        $http.post('urlDeault', this, {
            code: "10020005",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    let templateCode = 'HLWMZBL';
                    $loadTemplate(templateCode, res.result);
                    // var print = res.result;
                    // if (!Util.isEmpty(print)) {
                    //     for (var i = 0; i < print.length; i++) {
                    //         $loadTemplate(print[i].template, print[i].printStr);
                    //     }
                    // }
                    message.success('打印成功！')
                }
            }
        });
    }

    // 处理填写快递单号按钮点击事件
    handleFillExpressNumber = () => {
        Modal.confirm({
            title: '请输入快递单号',
            content: (
                <div>
                    <Input
                        placeholder="请输入快递单号"
                        ref={input => this.expressNumberInput = input}
                        style={{ width: '100%' }}
                    />
                </div>
            ),
            onOk: () => {
                const expressNumber = this.expressNumberInput.state.value;
                if (!expressNumber) {
                    message.error('快递单号不能为空');
                    return Promise.reject();
                }
                // 将快递单号存储到state
                this.setState({ expressNumber: expressNumber }, () => {
                    // 显示加载框
                    this.setState({ loading: true });
                    // 调用SaveExpressOrderByHSGK方法
                    this.SaveExpressOrderByHSGK();
                });
            },
            onCancel: () => {
                return Promise.resolve();
            }
        });
    }

    SaveExpressOrderByHSGK = (e) => {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let record = this.state.record
                if (record.statusCode == '01') {
                    // 将快递单号添加到record对象中
                    record.expressNumber = this.state.expressNumber || '';
                    this.handleExpressOrderByHSGK(record)
                }
            }
        })
        
    }


    handleExpressOrderByHSGK(record) {
        let data = {
            params: [{
                orderID:record.orderID&&record.orderID||"",
                patientID:record.patID&&record.patID||"",
                expressNumber:record.expressNumber||this.state.expressNumber||"",//快递单号
                userID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).userID : "",//用户Id
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",//医院Id
            }],
        }

        $http.post('urlS', this, {
            code: '03030093',
            data: data,
            success: function (res) {
                // 请求完成，隐藏加载框
                this.setState({ loading: false });
                if (+res.errorCode === 0) {
                    this.props.handleTableInfo()
                    message.success('保存成功')
                    this.setState({ visible: false,expressNumber:'' })
                } else {
                    message.error(res.errorMsg || '保存失败');
                }
            },
            error: function () {
                // 请求失败，隐藏加载框
                this.setState({ loading: false });
                message.error('网络错误，请稍后重试');
            }
        })
    }

    render() {
        var { distributionData, loading } = this.state;

        return <div style={{ height: '76vh' }} className='no-disbtn-body'>
            <Spin spinning={loading} tip="处理中...">
            <SendExpress
                newPresc={this.state.newPresc}
                admID={this.state.admID}
                newCmpresc={this.state.newCmpresc}
                newSpecNosc={this.state.newSpecNosc}
                newCheckNos={this.state.newCheckNos}
                titleData={this.state.record}
                handleTableInfo={this.handleTableInfo}
                onRef={this.onRef}
            >
            </SendExpress>
            {/**处方详情 */}
            <ShowPrescriptionModal isShow={this.state.isShowPrescriptionModal}
                prescriptData={this.state.prescriptData}
                onHide={this.hideModal.bind(this, 'isShowPrescriptionModal')}>
            </ShowPrescriptionModal>
            {/**打印清单 */}
            <ShowPrintListModal isShow={this.state.isShowPrintListModal}
                adressMsg={this.state.adressMsg}
                onSubmit={this.onSubmit.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowPrintListModal')}>
            </ShowPrintListModal>
            {/**修改收货地址 */}
            <ShowUpdateAddressModal isShow={this.state.isShowUpdateAddressModal}
                adressMsg={this.state.adressMsg}
                onSubmit={this.updateAddressMsg.bind(this)}
                onHide={this.hideModal.bind(this, 'isShowUpdateAddressModal')}>
            </ShowUpdateAddressModal>
            <div style={{ height: '80vh' }}>
                <div style={{ height: 48, lineHeight: '48px', borderBottom: '1px solid #e8e8e8' }} className="title">
                   <Row>
                   <Col span={4}>
                    < span>{this.setMessage('ShowHaveDistributionTabPaneTotal', 'descripts')}{this.state.distributionData && this.state.distributionData.length}</span>
                    </Col>
                    <Col span={20} style={{textAlign: "right"}}>
                    <Menu mode="horizontal">
                        <Menu.Item key="ipay">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!Util.isEmpty(this.state.record) && this.state.record.statusCode == '01' ? false : true} onClick={this.handleFillExpressNumber}>填写快递单号</Button>

                        </Menu.Item>
                        <Menu.Item key="mail">
                            <Button type='primary' style={{ marginLeft: 5 }} onClick={this.handleSendExpress.bind(this)}
                                disabled={!Util.isEmpty(this.state.record) && this.state.record.statusCode == '01' ? false : true}>{this.setMessage('ShowHaveDistributionTabPaneDelivery', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="app" disabled>
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("1")}>{this.setMessage('ShowHaveDistributionTabPanePrescriptions', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="al">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("2")}>{this.setMessage('ShowHaveDistributionTabPaneList', 'descripts')}</Button>
                        </Menu.Item>
                        <Menu.Item key="ali">
                            <Button type="primary" style={{ marginLeft: 5 }} onClick={() => this.handlePrint("3")}>{this.setMessage('ShowHaveDistributionTabPanechecklist', 'descripts')}</Button>

                        </Menu.Item>
                        <Menu.Item key="ipay">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={this.handlePrintDistribution.bind(this)}>打印诊断证明</Button>

                        </Menu.Item>
                        <Menu.Item key="alipa">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={this.handlePrintEMR.bind(this)}>打印病历</Button>

                        </Menu.Item>
                        <Menu.Item key="alip">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={!this.state.orderID} onClick={() => this.handlePrint("4")}>{this.setMessage('ShowHaveDistributionTabPanelabel', 'descripts')}</Button>

                        </Menu.Item>
                        <Menu.Item key="ipa">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={
                                (!Util.isEmpty(this.state.record) && (this.state.record.statusCode == '01' || this.state.record.statusCode == '06')) ? true : (!this.state.orderID ? true : false)}
                                onClick={this.handleCannelOrder.bind(this)}>取消订单</Button>
                        </Menu.Item>
                        <Menu.Item key="li">
                            <Button type="primary" style={{ marginLeft: 5 }} disabled={
                                (!Util.isEmpty(this.state.record) && (this.state.record.statusCode == '01')) ? true : (!this.state.orderID ? true : false)
                            }
                                onClick={this.handleSendExpress.bind(this, 'again')}>重新下单</Button>
                        </Menu.Item>
                    </Menu>
                    </Col>
                   </Row>
                </div>
             
                <div style={{ height: 40, lineHeight: '40px', borderBottom: '1px solid #e8e8e8' }}>
                    <div style={{ float: 'left' }}>
                        {this.setMessage('ShowHaveDistributionTabPaneReceiving', 'descripts')}<span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveName : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveMobile : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.adressMsg) ? this.state.adressMsg.receiveAddress : '--'}</span>&nbsp;&nbsp;
                        <span>{!Util.isEmpty(this.state.record) && this.state.record.expressNo ?
                            <span style={{ color: '#1999db' }}>( {this.setMessage('ShowHaveDistributionTabPaneLogistics', 'descripts')}{this.state.record.expressNo})</span> : ''}</span>
                    </div>
                    {!Util.isEmpty(this.state.record) && this.state.record.statusCode == '01' ?
                        <div style={{ float: 'right', marginRight: 10, cursor: 'pointer', color: '#1890ff' }}
                            onClick={this.updateAddressModal.bind(this)}> {this.setMessage('ShowHaveDistributionTabPaneModify', 'descripts')}</div> : null}
                </div>
                <Row style={{ marginTop: 5, height: '73vh', overflow: 'auto' }}>
                    {!Util.isEmpty(distributionData) ? this.loadExpressMessage() :
                        <div style={{ textAlign: 'center', marginTop: '10%' }}><img src={noData} /><div style={{ marginTop: 10 }}> {this.setMessage('ShowHaveDistributionTabPanerelevant', 'descripts')}</div></div>}
                </Row>
            </div>
            </Spin>
        </div>
    }
}

export default Form.create()(ShowHaveDistributionTabPane);