// 集中打印 | 院内发票集中打印 | 院内发票集中打印(住院)
import React from 'react';
import moment from 'moment';
import { Select, Input, Row, Col, Button, message, Table, Tabs, Modal } from 'antd';
import { $http } from 'containers/config/https';
import HopNumber from './component/HopNumber'
import { $loadTemplate } from '../../lodop/Common/Print.js';
import ReadCard from '../../../components/readcard/ReadCard';
import PubilcTablePagination from '../../common/PubilcTablePagination.jsx'; // 公共table组件
import PayMentRecordModal from './component/PayMentRecordModal.jsx'
// import fetchJsonp from 'fetch-jsonp';
import store from '../../../store';
import RangeDatePicker from 'components/rangePicker/index';
// import ShowPrintCompantModal from './component/ShowPrintCompantModal';
import $ from 'pages/workstation/component/js/jquery-3.2.1.min.js';
import { Util } from 'tools/index';
import './style/style.less'
import '../../opadmReg/style/index.less';
import { ArraySome } from '../../../tools/index';
import TipHeader from './component/TipHeader'
// import { $loopPrint } from "../../lodop/Common/Print";
// 组件const
const { Option } = Select;
const TabPane = Tabs.TabPane;
// const { RangePicker } = DatePicker;
// const dateFormat = 'YYYY-MM-DD' || undefined;
const { Search } = Input;

export default class HospitalDeposit extends React.Component {
    constructor(props) {
        var userData = JSON.parse(sessionStorage.getItem('userData'))
        super(props)
        this.state = {
            patID: '',
            total: 0,
            page: 1,
            pageSize: 10,
            dataPatChar: [], // 挂号table数据
            dataAdmReason: [], // 费用类型table数据
            userInfo: {}, // 用户数据
            patNo: '', // 登记号
            cardNo: '', // 卡号
            cardType: '', // 卡类型
            invoice: '', // 发票
            cardTypeData: [], // 卡类型
            settlementTypeData: [], // 结算类型
            IfAllAdmPay: '', // 是否是多选
            columnsPatCharSome: [],// 费用类型table
            allPrice: '0', // 发票数
            orderAdmReason: [
                {}// 默认费用类型
            ], // tab费用类型
            admIdStr: [], // 费用类型数组
            payrecordstr: [], // 付款记录表id串
            tabKey: 0,// 当前的tab页面key
            PayReasonDr: '',// 收费类型

            modalShow: false, //  发票号跳号弹框的显示
            selectedRowKeys1: [],
            selectedRowKeys2: [],
            isListCheckload: [],//是否加载过
            admID: '', // 就诊id
            OPInsuType: '', //
            selecteId: '', //
            oldSelectedRowKeysArr: [],// 上一个选择数据
            activeKey: '0', //tab当前key
            findCondition: 'Y',
            StartDate: moment().subtract(7, "days"),  // //开始日期
            EndDate: moment(),  // //结束日期
            visible: false,
            userInfoModal: {},
            selectedRowsArr: [],
            invIDSt: '',
            dateValue: new Date(),
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            readModeI: true,
            readModeR: true,
            invNum: '0',
            userData: userData,
            loading: false
        }

        // 挂号table
        this.columnsPatChar = [{
            title: '序号',
            dataIndex: 'num',
            key: '1',
            align: "center",
            width: '100px'
        }, {
            title: '打印发票',
            dataIndex: 'admLocDesc',
            key: '2',
            align: "center",
            width: 'auto',
            render: (text, record, index) => {
                return (
                    <div>
                        {
                            <span className='spanHref' >{record.invPayReasonDesc} |  发票金额￥：{record.invPatAmt} </span>
                        }
                    </div>
                );
            }
        },]



    }

    componentDidMount() {
        for (var i = 0; i < document.querySelectorAll("div.maxHeight div.ant-table-body").length; i++) {
            document.querySelectorAll("div.maxHeight div.ant-table-body")[i].style.height = store.getState().tableHeight.y + 'px';
        }
        this.initJuris() //权限
        this.cardTypeList() //卡类型
        // this.cloumData()
        this.CNEN() // 国际化

        // 数据加载成功关闭loading
        this.child.handleLoading()
        this.setState({
            orderAdmReason: [
                { ordReasonID: '0', ordReasonDesc: `${this.state.language.CentralizedPrintingpayrecord && this.state.language.CentralizedPrintingpayrecord.descripts}` } // 默认费用类型
            ],
        })
    }

    //调用金税，获取库存信息
    loadGoldTaxMessage() {
        // var data = 'input={"inputDir":"' + "JSInv/prykjsapplication.dll" + '","clsName":"' + "prykjsapplication.JSHelper" + '","funcName":"' + "GetJSData" + '","dllInput":"' + dllInput + '"}'
        // fetchJsonp('http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?' + '&' + data, {
        //     jsonpCallback: 'JsonCallback',
        // })
        //     .then((response) => {
        //         return response.json()
        //     }).then(function (json) {
        //         console.dir(json)
        //         json = decodeURIComponent(JSON.parse(json))
        //         if (json.errorCode == "0") {
        //             if (json.invStock = 0) {
        //                 that.setState({
        //                     disBtn: true
        //                 })
        //             }
        //         } else {
        //             message.error(json.errorMessage);
        //         }

        //         return json

        //     }).catch(function (ex) {
        //         console.dir(ex)
        //         return false
        //     })
        let that = this;
        var source = encodeURIComponent("{ fpzl: 2 }");
        var dllInput = 'SID=0\&\&\&\SIDParam=' + source; // JSON.stringify({ "SID": "0", "SIDParam": source })
        // var dllPath = 'JSInv/prykjsapplication.dll'
        // var className = 'prykjsapplication.JSHelper'
        // var funcName = 'GetJSData'
        // let data = 'input={"inputDir":"' + dllPath + '","clsName":"' + className + '","funcName":"' + funcName + '","dllInput":"' + dllInput + '"}'
        let dllParams = JSON.stringify({ 'inputDir': 'JSInv/prykjsapplication.dll', 'clsName': 'prykjsapplication.JSHelper', 'funcName': 'GetJSData', 'dllInput': dllInput });
        if (typeof (CefSharp) != "undefined") {   // 新元素定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            setTimeout(() => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    var res = JSON.parse(returnVale);
                    if (res.resultCode == '0') {
                        var source = JSON.parse(decodeURIComponent(res.result))
                        if (source && source.ENCMSG.invStock == 0) {
                            that.setState({
                                disBtn: true
                            })
                        } else {
                            that.setState({
                                invoice: source ? source.ENCMSG.fphm : ''
                            })
                        }
                    }
                })
            }, 100);
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
                frame.DynamicLoadingDLL(dllParams)
                    .then(
                        data => {
                            let res = JSON.parse(data);
                            if (res.resultCode == '0') {
                                var source = JSON.parse(decodeURIComponent(res.result))
                                if (source && source.ENCMSG.invStock == 0) {
                                    that.setState({
                                        disBtn: true
                                    })
                                } else {
                                    that.setState({
                                        invoice: source ? source.ENCMSG.fphm : ''
                                    })
                                }
                            }
                        },
                        err => {
                            console.log('error', err);
                        }
                    )
            } else {
                $.getJSON("http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?JsonCallback=?", {
                    input: dllParams
                },
                    function (data) {
                        var res = JSON.parse(data);
                        if (res.resultCode == '0') {
                            var source = JSON.parse(decodeURIComponent(res.result))
                            if (source && source.ENCMSG.invStock == 0) {
                                that.setState({
                                    disBtn: true
                                })
                            } else {
                                that.setState({
                                    invoice: source ? source.ENCMSG.fphm : ''
                                })
                            }
                        }
                    });
            }
        }
    }

    edit = (record) => {
        let obj = {
            ID: record.recordID,
            invType: 'PAY',

        }
        this.setState({
            userInfoModal: obj,
            visible: true
        })

    }

    CNEN = () => {
        var data = {
            params: [{
                "reactCode": ["CentralizedPrinting"],
                "compontName": "CentralizedPrinting",
                "type": "C"
            }]
        }

        $http.post('urlS', this, {
            code: "01040073",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                        this.cloumData(this.state.languageTable2)
                    })
                }
            }
        });
    }

    LanCNEN = (code) => {
        let { languageData } = this.state
        this.setState({
            language: languageData[code]
        })
    }

    // 权限
    initJuris = () => {
        // console.log(this.props.location)
        var data = {
            params: [{
                logonHospID: JSON.parse(window.sessionStorage.userData).hospID, //医院id
                logonGroupID: JSON.parse(window.sessionStorage.userData).groupID,  //角色id
                logonUserID: JSON.parse(window.sessionStorage.userData).userID, //人员id
                invTypeCode: this.props.location.state && this.props.location.state.invType ? this.props.location.state.invType : "O"  // 类型
            }]
        }
        $http.post('urlS', this, {
            code: "05210001",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode == '0') {

                    this.setState({
                        invoice: res.currentInvNoInfo,  // 发票号
                        IfAllAdmPay: res.sysConfig.IfAllAdmPay,  // 是否多选
                        otherPayData: res.groupConfig.HBOPConfigPaymode[0].OPCharge || [],  // 其他付款方式
                        IfSupplementOrd: res.sysConfig.IfSupplementOrd,  // 收费界面是否可以补录医嘱
                        invNum: res.invNum || '0',  // 发票数剩余

                    }
                        // , () => {
                        //     this.loadGoldTaxMessage()
                        // }
                    );
                    /*
                    if (res.groupConfig.IfChargeFlag === 'Y') {
                        if (res.groupConfig.IfInvNo === 'Y' && res.currentInvNoInfo.split('^')[0] !== '0') {
                            message.error('该收费员无发票号')
                        }
                    } else {
                        message.error('无收费权限')
                        this.setState({
                            disabledInput: true,  // 收费权限
                        });
                    }*/
                    if (res.currentInvNoInfo.split('^')[0] !== '0') {
                        message.error('该收费员无发票号')
                    }
                }
            }
        });
    }

    //卡类型
    cardTypeList = () => {
        var data = {
            params: [{
                cardTypeFlag: 1,
            }]
        }

        $http.post('urlS', this, {
            code: "03030005",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let cardDeffault = res.cardType.filter((item) => {
                        return item.defaultFlag === 'Y';
                    })
                    this.setState({
                        cardType: cardDeffault[0].id, // 默认卡
                        cardTypeData: res.cardType,  // 用户数据
                    }, () => {
                        this.CardTypeChange(this.state.cardType)
                    });
                }
            }
        });
    }

    // 时间
    onChangeTime = (date, dateString) => {
        this.setState({
            StartDate: dateString[0],    //开始日期
            EndDate: dateString[1],  //结束日期
        })

    }

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

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


    // 读卡 --- 根据卡号取病人信息
    handleReadCard = (value, event) => {
        let { readModeI, readModeR, cardType } = this.state
        if (event.keyCode) {
            if (readModeI) {
                this.searchUser('cardNo'); // 重新调用查询接口
            }
            return false
        }
        if (readModeR) {
            this.readCard.ReadCard(cardType, "R", (json) => {
                let patNo = json && json.patInfo ? json.patInfo.patNo : ''
                this.setState({ patNo, cardNo: json.cardNo }, () => {
                    //this.searchUser('cardNo'); // 重新调用查询接口
                    if (patNo) {
                        this.searchUser('patNo'); // 重新调用查询接口
                    } else {
                        this.searchUser('cardNo'); // 重新调用查询接口
                    }
                })
            })
        }

    }

    // // 回车读卡 --- 根据卡号取病人信息
    // handleReadCarddownE = (e, type) => {
    //     if (e.keyCode === 13) {

    //         this.searchUser('cardNo') // 读卡 --- 根据卡号取病人信息
    //     }
    // }

    // 读卡
    searchUser = (type) => {
        var data;
        let { cardType, cardNo, patNo, cardTypeData } = this.state
        if (!type) {   // 查询全部
            data = {
                params: [{
                    "number": patNo || '', // 登记号/身份证号
                    "cardTypeID": cardType,   //卡类型id
                    "cardNo": cardNo,    //卡号
                }]
            }
        }

        if (type === 'patNo') {
            data = {
                params: [{
                    "number": patNo || '', // 登记号/身份证号
                    "cardTypeID": "",   //卡类型id
                    "cardNo": "",    //卡号
                }]
            }

            if (patNo === '') {
                return false
            }
        }

        if (type === 'cardNo') {
            data = {
                params: [{
                    "number": '', // 登记号/身份证号
                    "cardTypeID": cardType || '',     //卡类型id
                    "cardNo": cardNo || '', //卡号
                }]
            }

            if (cardNo === '') {
                return false
            }
            if (cardType === '') {
                message.error('请选择卡类型')
                return false
            }


            let cardTypeFilter = cardTypeData.filter(function (item) {
                return item.id == cardType;
            })

            let zeroLength = cardTypeFilter[0].cardLength

            if (zeroLength && zeroLength != '' && parseFloat(zeroLength) != 0) {
                this.setState({
                    cardNo: ArraySome.addPreZero(cardNo, zeroLength)
                })
                data = {
                    params: [{
                        "number": '', // 登记号/身份证号
                        "cardTypeID": cardType || '',     //卡类型id
                        "cardNo": ArraySome.addPreZero(cardNo, zeroLength) || '', //卡号
                    }]
                }
            }
        }



        $http.post('urlS', this, {
            code: "03040004",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {

                    this.setState({
                        userInfo: res.data || [],  // 用户数据
                        settlementTypeData: res.data.admReason || [],  // 结算类型
                        patNo: res.data.patNo || '',  // ID
                        patID: res.data.patID || '',  // ID
                        selectedRowKeys2: [],
                        dataPatChar: []
                    }, () => {
                        this.medicalInformation() // 缴费记录
                    });

                } else {
                    this.clearnFile()  // 清空
                }
            }
        });
    }

    // 缴费记录
    medicalInformation = () => {
        let { pageSize, page } = this.state
        var data = {
            "params": [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id ,
                "patID": this.state.patID,
                "stDate": this.state.StartDate || "",
                "endDate": this.state.EndDate || "",
                "invTypeCode": this.props.location.state && this.props.location.state.invType ? this.props.location.state.invType : "O"  // 类型
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
            }]
        }



        $http.post('urlS', this, {
            code: "05210025",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let recordInfo = res.recordInfo
                    for (var i = 0; i < recordInfo.length; i++) {
                        recordInfo[i].key = i;
                    }
                    this.setState({
                        dataAdmReason: recordInfo || []
                    })

                }
            }
        });


    }

    // 回车查询登记号
    patNodownE = (e, type) => {
        if (e.keyCode === 13) {
            this.searchUser(type)
        }
    }

    // 查询条件 --- 卡类型·
    cardType = (e) => {
        this.setState({ cardType: e }, () => {
            this.CardTypeChange(e)
        });
    }
    // 查询条件 --- 卡号
    cardNo = (e) => {
        let { readModeI } = this.state
        if (!readModeI) {
            return false
        }
        this.setState({ cardNo: e.target.value });
    }

    // Card
    CardTypeChange = (e) => {
        if (!e) {
            return false
        }
        let { cardTypeData } = this.state
        let readMode = cardTypeData.filter((item, i) => {
            return item.id == e;
        })

        switch (readMode[0] && readMode[0].readMode) {
            // 只可input
            case 'I':
                this.setState({
                    readModeI: true,
                    readModeR: false,
                    cardNo: "",

                })
                break;
            // 只可读卡
            case 'R':
                this.setState({
                    readModeR: true,
                    readModeI: false,
                    cardNo: "",
                })
                break;
            // 皆可
            default:
                this.setState({
                    readModeI: true,
                    readModeR: true,
                    cardNo: "",
                })
                break;
        }

    }


    // 查询条件 --- 登记号
    patNo = (e) => {
        this.setState({ patNo: e.target.value });
    }

    //清空
    clearnFile = () => {
        this.setState({
            patID: '',
            dataAdmReason: [], // 费用类型table数据
            orderAdmReason: [
                { ordReasonID: '0', ordReasonDesc: `${this.state.language.CentralizedPrintingpayrecord && this.state.language.CentralizedPrintingpayrecord.descripts}` } // 默认费用类型
            ], // tab费用类型
            userInfo: {}, // 用户数据
            cardNo: '',
            patNo: '',
            invoice: '',
            dataPatChar: [],  // 挂号table数据
            settlementTypeData: [], // 结算类型
            allPrice: '0', // 发票数
            isListCheckload: [], // //是否加载过
            selectedRowKeys: [], //  清除选中
            selectedRowKeys2: [], //  清除选中
            admID: '', // 就诊id
            OPInsuType: '', //
            selecteId: '', //
            oldSelectedRowKeysArr: [],// 上一个选择数据
            activeKey: '0', //tab当前key
            findCondition: 'Y',
            StartDate: undefined,  // //开始日期
            EndDate: undefined,  // //结束日期
            userInfoModal: {},
            selectedRowsArr: [],
            invIDSt: '',
            dateValue: new Date(),
            readModeI: true,
            readModeR: true,
            invNum: '0',
        });

    }

    //获取金税开票信息
    loadInvoiceMessage() {
        this.setState({ loading: true })
        var params = {
            params: [{
                userID: this.state.userData.userID,
                recordID: this.state.ids,
                customerBankAccountNr: this.state.customerBankAccountNr,
                customerName: this.state.customerName,
                customerTaxNr: this.state.customerTaxNr,
                customerAddressTel: this.state.customerAddressTel,
            }]
        }
        $http.post('urlADS', this, {
            code: "05210077",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    var source = res.result;
                    if (!Util.isEmpty(source)) {
                        source['listed'] = (source.listed == 'true' ? true : false)
                    }
                    this.setState({
                        invoiceSource: source
                    }, () => {
                        if (source && source.existingFlag == 'Y') {
                            this.setState({
                                loading: false
                            }, () => {
                                // message.error(cource.reminder)
                                Modal.warning({
                                    title: '打印提示',
                                    content: source.reminder,
                                });
                            })
                        } else {
                            if (this.state.userData && this.state.userData.hospCode === "H19" && this.state.userData.hospCode === "H10") {
                                this.setState({ loading: false })
                                /**
                                 * @ByYQL: 长春 -区分医保/自费打印方式
                                 * Create 2022-3-7
                                 */
                                if (source?.invoiceFileUrl) {
                                    source && source.invoiceFileUrl ? window.open(source.invoiceFileUrl) : "";
                                } else if (source?.printStr) {
                                    $loadTemplate(source?.templateName, source?.printStr);
                                }
                            } else {
                                this.loadInvoiceSource()//获取发票开具信息
                            }
                        }
                    })
                } else {
                    this.setState({ loading: false })
                }
            }
        });
    }

    loadInvoiceSource() {
        let that = this;
        var source = encodeURIComponent(JSON.stringify(that.state.invoiceSource));
        var dllInput = 'SID=1\&\&\&\SIDParam=' + source; // JSON.stringify({ "SID": "0", "SIDParam": source })
        let dllParams = JSON.stringify({ 'inputDir': 'JSInv/prykjsapplication.dll', 'clsName': 'prykjsapplication.JSHelper', 'funcName': 'GetJSData', 'dllInput': dllInput });
        if (typeof (CefSharp) != "undefined") {   // 新元素定制浏览器
            CefSharp.BindObjectAsync("xysCefToJavaScripts");
            setTimeout(() => {
                xysCefToJavaScripts.driveLocalHardware(dllParams).then((returnVale) => {
                    let res = JSON.parse(returnVale);
                    console.dir(res)
                    if (res.resultCode == '0') {
                        let source = JSON.parse(decodeURIComponent(res.result));
                        that.setState({
                            fpSource: source ? source.ENCMSG : '',
                            loading: false
                        }, () => {
                            that.saveInviceMessage();
                        })

                    } else {
                        that.setState({
                            loading: false
                        })
                    }
                })
            }, 100);
        } else {
            const frame = chrome?.webview?.hostObjects?.Bridge || ''; // 新版浏览器
            if (frame) {
                frame.DynamicLoadingDLL(dllParams)
                    .then(
                        data => {
                            let res = JSON.parse(data);
                            console.dir(res)
                            if (res.resultCode == '0') {
                                let source = JSON.parse(decodeURIComponent(res.result));
                                that.setState({
                                    fpSource: source ? source.ENCMSG : '',
                                    loading: false
                                }, () => {
                                    that.saveInviceMessage();
                                })

                            } else {
                                that.setState({
                                    loading: false
                                })
                            }
                        },
                        err => {
                            console.log('error', err);
                            that.setState({
                                loading: false
                            })
                        }
                    )
            } else {
                $.getJSON("http://127.0.0.1:62534/XYSWCFService/DynamicLoadingDLL?JsonCallback=?", {
                    input: dllParams
                },
                    function (data) {
                        let res = JSON.parse(data);
                        console.dir(res)
                        if (res.resultCode == '0') {
                            let source = JSON.parse(decodeURIComponent(res.result))
                            console.dir(source)
                            that.setState({
                                fpSource: source ? source.ENCMSG : '',
                                loading: false
                            }, () => {
                                that.saveInviceMessage();
                            })

                        } else {
                            that.setState({
                                loading: false
                            })
                        }
                    });
            }
        }
    }

    //保存金税信息
    saveInviceMessage() {
        var params = {
            params: [{
                recordID: this.state.ids,
                ...this.state.fpSource
            }]
        }
        $http.post('urlADS', this, {
            code: "05210078",
            data: params,
            success: function (res) {
                if (res.errorCode == '0') {
                    this.printButtont()
                }
            }
        });
    }

    // 打印按钮
    printButtont = () => {
        let { selectedRowsArr } = this.state
        if (selectedRowsArr && selectedRowsArr.length < 1) {
            return false
        }
        var data = {
            recordIDArr: selectedRowsArr,
            params: [{
                userID: React.$getSessionData()?.userID || '',             //收费员
                paywIDinfo: '',//个人自付支付方式数据(不包括    医保) ID^金额^合作单位ID_$c(2)_ID^金额^合作单位ID
                accmID: '',//账户ID
                IfPayInvMode: 'N',//集中打印发票是否重新计费支付方式（集中打印是医保结算也是重新计算支付方式）Y 是,N 否
                ifDirectPrint: 'N', //是否缴费直接打印标志
                groupID: JSON.parse(window.sessionStorage.userData).groupID,//登录安全组
                locID: JSON.parse(window.sessionStorage.userData).locID,//登录科室
                hospID: JSON.parse(window.sessionStorage.userData).hospID, //医院id //登录医院
                ip: React.$getSessionData('ipConfig')?.ipv4 || '',
                invNo: ''//金税发票号码 
            }]
        }

        $http.post('urlADS', this, {
            code: "05210034",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        invIDSt: res.invIDStr
                    }, () => {
                        //this.loadPrintGoldTax()//金税打印
                        if ((JSON.parse(window.sessionStorage.userData).hospCode === 'H26') || (JSON.parse(window.sessionStorage.userData).hospCode === 'H10') || (JSON.parse(window.sessionStorage.userData).hospCode === 'H17')) {
                            this.handlePrintChargeVoucher(this.state.invIDSt)
                        } else {
                            this.print()   // 打印
                        }

                        this.clearnFile()//清空
                    })
                }
            }
        });
    }

    // 打印
    print = () => {

        var data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id
                "groupID": JSON.parse(window.sessionStorage.userData).groupID,  //角色id
                "printType": "",
                "printTemplateCode": "OutInvoice",
                "recordIDStr": '',
                "invIDStr": this.state.invIDSt || '',
            }]
        }

        $http.post('urlADS', this, {
            code: "05100153",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let dataArr = res.data
                    let template = res.template
                    dataArr.map((item, i) => {
                        $loadTemplate(template[i], item.toString());
                    })
                    this.clearnFile()
                }
            }
        });
    }
    handlePrintChargeVoucher(data) {
        var params = {
            params: [{
                recordinvID: data,
            }]
        }
        $http.post('urlADS', this, {
            code: "05210094",
            data: params,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let dataArr = res.result
                    dataArr && dataArr.map((item, i) => {
                        $loadTemplate(item.template, item.printStr);
                    })
                }
            }
        });
    }

    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }


    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.medicalInformation();
        })
    }

    // 数据配置
    cloumData(resC) {
        // var data = {
        //     params: [{
        //         compontName: "CentralizedPrinting",
        //         type: 'C',
        //     }]
        // }

        // $http.post('urlS', this, {
        //     code: "01040073",
        //     data: data,
        //     success: function (res) {
        //         let errorCode = res.errorCode;
        //         if (errorCode === '0') {
        //             let resC = res.result.C

        //             for (var i = 0; i < resC.length; i++) {
        //                 resC[i].key = i;
        //             }

        //             this.setState({
        //                 columnsPatCharSome: resC, // 费用类型table
        //             }, () => {
        //                 this.ordListAdd('0', 0)    //render 自定义项目名称
        //             });
        //         }
        //     }
        // });
        let { languageCode } = this.state
        for (var i = 0; i < resC.length; i++) {
            resC[i].key = i;
        }
        if (languageCode === "EN") {
            resC.map((item, i) => {
                item.title = item.enDescripts
            })
        }

        if (languageCode === "CN") {
            resC.map((item, i) => {
                item.title = item.descripts
            })
        }

        this.setState({
            columnsPatCharSome: resC, // 费用类型table
        }, () => {
            this.ordListAdd('0', 0, languageCode)    //render 自定义项目名称
        });
    }


    //render 自定义项目名称
    ordListAdd = (i, indexs, languageCode) => {
        let { columnsPatCharSome } = this.state
        let that = this

        columnsPatCharSome.splice(7, i, {
            title: languageCode === 'CN' ? "操作" : 'operation',
            dataIndex: 'record',
            key: '99999',
            align: "center",
            width: '100px',
            render(text, record, index) {
                return (

                    <div>
                        {
                            <span className='spanHref' onClick={() => that.edit(record)}>{languageCode === 'CN' ? "查看明细" : 'Check details'}</span>
                        }
                    </div>
                );
            }

        })


        this.setState({
            columnsPatCharSome: columnsPatCharSome, // 费用类型table
        });
    }



    rowSelectionOnChange1 = (selectedRowKeys1, selectedRows) => {
        let { selectedRowsArr } = this.state
        selectedRowsArr = []
        selectedRows.map((item, i) => {
            selectedRowsArr.push(item.recordIDStr)
        })
        let l = selectedRowKeys1.length
        this.setState({
            selectedRowKeys1: selectedRowKeys1,
            allPrice: l,
            selectedRowsArr: selectedRowsArr
        })
    }

    rowSelectionOnChange2 = (selectedRowKeys2, selectedRows) => {
        let str = ''

        selectedRows.map((item, i) => {
            str += item.recordID + '^'
        })
        str = str.substring(0, str.length - 1);

        var ids = []
        if (!Util.isEmpty(selectedRows)) {
            for (var i = 0; i < selectedRows.length; i++) {
                ids.push(selectedRows[i].recordID)
            }
        }

        var data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id
                "recordIDStr": str
            }]
        }

        $http.post('urlADS', this, {
            code: "05210026",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                let InvingInfo = res.InvingInfo;
                if (!InvingInfo) {
                    this.setState({ dataPatChar: [], allPrice: '0', ids: ids })

                }
                if (errorCode === '0') {
                    for (var i = 0; i < InvingInfo.length; i++) {
                        InvingInfo[i].key = i;
                    }

                    this.setState({
                        dataPatChar: InvingInfo || [],
                        ids: ids
                    }, () => {
                        let key = []
                        let { dataPatChar } = this.state
                        dataPatChar.map((item, i) => {
                            let index = i + 1
                            key.push(index)
                        })

                        this.rowSelectionOnChange1(key, dataPatChar)
                    })

                }
            }
        });
    }

    // 取消
    handleCancel = () => {
        this.setState({
            modalShow: false,
            visible: false,
        })
    }

    //发票弹窗显示
    historyModal = () => {
        this.setState({
            modalShow: true,
        });
    }

    //打印公司发票
    handlePrintCompanyModal() {
        this.setState({
            isShowPrintCompantModal: true
        })
    }

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

    // onSubmit(params) {
    //     this.setState({
    //         customerBankAccountNr: params.customerBankAccountNr,
    //         customerName: params.customerName,
    //         customerTaxNr: params.customerTaxNr,
    //         customerAddressTel: params.customerAddressTel,
    //     }, () => {
    //         this.loadInvoiceMessage()
    //     })
    // }

    render() {

        let { selectedRowKeys2, selectedRowKeys1, language } = this.state


        let rowSelection1 = {
            selectedRowKeys1,
            onChange: this.rowSelectionOnChange1,
        };

        let rowSelection2 = {
            selectedRowKeys2,
            onChange: this.rowSelectionOnChange2,
        };

        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.columnsPatCharSome,
            // 表格数据
            data: this.state.dataAdmReason,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            // page: this.state.page,
            x: 800,
            isRowSelection: true, // checkBox
            y: store.getState().tableHeight.y - 240,
            height: store.getState().tableHeight.y - 195,

        }


        return (
            <div>
                {/* <ShowPrintCompantModal isShow={this.state.isShowPrintCompantModal}
                    onHide={this.hideModal.bind(this, 'isShowPrintCompantModal')}
                    onSubmit={this.onSubmit.bind(this)}>
                </ShowPrintCompantModal> */}
                <ReadCard ref={r => this.readCard = r} />
                <div >
                    <Row >
                        <Col span={6} style={{ textAlign: 'center' }}>
                            <Row >
                                <Col span={23} >
                                    <TipHeader userInfo={this.state.userInfo} key={this.state.userInfo.patID + this.state.userInfo.accTSubID} />
                                </Col>
                            </Row>
                            <Row style={{ height: '203px' }}>
                                <Col span={23} >
                                    <Col span={24} style={{ height: '40px', lineHeight: '40px', textAlign: 'left' }} ><i className="invPng"></i><span>{language.CentralizedPrintingcin && language.CentralizedPrintingcin.descripts}:</span><span className='curP' style={{ color: '#1890FF', }} onClick={() => { this.historyModal() }} > {this.state.invoice ? this.state.invoice : ''}</span>  <span style={{ color: 'red', float: 'right', marginRight: '20px', display: parseFloat(this.state.invNum) < 10 ? 'block' : 'none' }}>{language.PatientChargesInvoicesurplus && language.PatientChargesInvoicesurplus.descripts}{this.state.invNum},{language.PatientChargesPleasepurch && language.PatientChargesPleasepurch.descripts}</span></Col>
                                    <Col span={24} >
                                        <div className='boxTitle'><i className="printing"></i>{language.CentralizedPrintingcno && language.CentralizedPrintingcno.descripts}</div>
                                        <div className='priceBox' style={{ height: '112px', lineHeight: '112px' }}>
                                            <span style={{ fontSize: '60px' }}>{this.state.allPrice} </span>
                                        </div>
                                    </Col>
                                </Col>
                            </Row>
                            <Col span={1}
                                style={{
                                    height: '100%',
                                    background: 'rgb(240, 242, 245)',
                                    float: 'right',
                                    position: 'absolute',
                                    right: '0px',
                                    top: '0px'
                                }} >
                            </Col>

                        </Col>
                        <Col span={18} style={{ padding: 10 }}>
                            <div className="table-operations">
                                <Row style={{ minHeight: '50px', paddingBottom: '10px' }}>
                                    <Col span={24}>
                                        <Select allowClear style={{ width: '100px', margin: '12px 15px 0 0' }} placeholder="请选择卡类型" value={this.state.cardType} onChange={(event) => { this.cardType(event) }}  >
                                            <Option value=''>请选择</Option>
                                            {this.state.cardTypeData.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                        </Select>
                                        <Search maxLength={50} className={`search ${!this.state.readModeI ? 'disabled' : ''}`} style={{ width: '200px', margin: '12px 15px 0 0' }} allowClear placeholder="请输入卡号" disabled={this.state.disabledInput} value={this.state.cardNo} enterButton={language.CentralizedPrintingcard && language.CentralizedPrintingcard.descripts} onChange={(event) => { this.cardNo(event) }} onSearch={this.handleReadCard} /> {/* onKeyUp={(e) => { this.handleReadCarddownE(e, 'cardNo'); }}*/}
                                        {language.CentralizedPrintingpatient && language.CentralizedPrintingpatient.descripts}：<Input maxLength={50} allowClear style={{ width: '200px', margin: '12px 15px 0 0' }} placeholder={language.CentralizedPrintingpatient && language.CentralizedPrintingpatient.message} className='input' value={this.state.patNo} onChange={(event) => { this.patNo(event) }} onKeyUp={(e) => { this.patNodownE(e, 'patNo'); }} />
                                        {/* 缴费日期：<RangePicker allowClear style={{ width: '260px', margin: '12px 15px 0 0' }}
                                value={this.state.StartDate === undefined || this.state.EndDate === undefined || this.state.StartDate === "" || this.state.EndDate === "" ? null : [moment(this.state.StartDate, dateFormat), moment(this.state.EndDate, dateFormat)]}
                                onChange={this.onChangeTime} /> */}
                                        <span style={{ display: 'inline-block', margin: '12px 15px 0 0' }}><RangeDatePicker label={`${language.CentralizedPrintingpayment && language.CentralizedPrintingpayment.descripts}：`} format='YYYY-MM-DD' width={280}
                                            startDate={this.state.StartDate} endDate={this.state.EndDate} key={this.state.dateValue} startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} /></span>
                                        <Button onClick={() => this.searchUser()} style={{ margin: '12px 15px 0 0', background: 'rgba(255,255,255,1)' }}>{language.CentralizedPrintingquery && language.CentralizedPrintingquery.descripts}</Button>
                                    </Col>
                                </Row>
                            </div>
                            <Table
                                bordered
                                dataSource={this.state.dataPatChar}
                                columns={this.columnsPatChar}
                                pagination={false}
                                // rowSelection={rowSelection1}
                                className="smallTable"
                                scroll={{ y: 175 }}
                                style={{ minHeight: '225px' }}
                            />
                            <div style={{ position: 'absolute', bottom: '-45px', right: 0, zIndex: 1 }}>
                                <Button onClick={this.clearnFile} style={{ border: 'none' }}><i className="clearn"></i>{language.CentralizedPrintingempty && language.CentralizedPrintingempty.descripts}</Button>
                                <Button onClick={this.printButtont.bind(this)} disabled={this.state.disBtn} loading={this.state.loading}
                                    style={{ margin: '23px 15px 0 0', border: 'none' }}><i className="printing"></i>{language.CentralizedPrintingprint && language.CentralizedPrintingprint.descripts}</Button>
                                {/* <Button type='link' disabled={this.state.disBtn} loading={this.state.loading} onClick={this.handlePrintCompanyModal.bind(this)}><i className="printing"></i>打印公司发票</Button> */}
                            </div>
                        </Col>
                    </Row>
                </div>
                <div style={{ background: '#f0f2f5', height: '10px' }}></div>
                <div style={{ padding: 24, paddingTop: '0' }}>
                    <Row>
                        <i className="tab"></i>
                        <Tabs defaultActiveKey="0" activeKey={this.state.activeKey}>
                            <TabPane tab={language.CentralizedPrintingpayrecord && language.CentralizedPrintingpayrecord.descripts} key='0'  >
                                {/* handelThis将夫组件的属性与方法给子组件访问 */}
                                <div className='maxHeight'>
                                    <PubilcTablePagination
                                        param={param}
                                        handelThis={this}
                                        onRef={this.onRef}
                                        rowSelectionPublic={rowSelection2}
                                    />
                                </div>
                            </TabPane>
                        </Tabs>
                    </Row>
                </div>
                <Modal
                    visible={this.state.modalShow}
                    title='设置发票号'
                    onCancel={this.handleCancel}
                    onOk={this.handleCancel}
                    width='600px'
                    footer={null}
                >
                    {/* <HistoryModal userInfo={this.state.userInfo} updateParent={this.updateParent}></HistoryModal> */}
                    <HopNumber
                        key={this.state.invoice}
                        invTypeCode={this.props.location.state && this.props.location.state.invType ? this.props.location.state.invType : 'O'}
                        handleCancel={this.handleCancel}
                        initJuris={this.initJuris}
                    />
                </Modal>
                <Modal
                    width="800px"
                    okText="打印清单"
                    title="病人费用明细"
                    visible={this.state.visible}
                    onCancel={this.handleCancel}
                >
                    <PayMentRecordModal
                        onRef={this.onRef}
                        userInfo={this.state.userInfoModal}
                        key={this.state.userInfoModal.ID}
                        special="center"
                    >
                    </PayMentRecordModal>
                </Modal>
            </div >
        )
    }
}
