// 收费弹框

import React from 'react';
import { Select, Input, Row, Col, Button, Spin, Divider, Popconfirm, message, Icon, Form, DatePicker, Table, Tabs, Modal, Card } from 'antd';
import { $http } from 'containers/config/https';
import { Keup, ArraySome } from 'tools/index';
import '../style/style.less'
import '../../../opadmReg/style/index.less';
// 组件const
const { Option } = Select;

export default class CashRegister extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            moneyData: {}, //金额对象
            accountPayWayId: '', // 院内账户支付方式id
            payWayCashId: '', // 现金支付方式id
            cashInCashVal: '0.00',
            chargeRecodeId: '', // 交款记录id
            otherPayDis: false, // 其他支付不可选
            otherPay: '', // 其他支付方式
            otherPayMoney: '0.00', // 其他支付金额
            zeroPay: '0.00', // 找零
            otherPayData: [], //其他付款方式
            unitsListVal: '', //合作单位
            unitsList: [], // 合作单位列表
            payType: '', // 付款方式
            cancel: '',
            hzDis: false,
            payingAccountAmt: '0.00', // 初始payingAccountAmt
        }

        this.myRef1 = React.createRef();
        this.myRef2 = React.createRef();
        this.myRef3 = React.createRef();
        this.myRef4 = React.createRef();
        this.myRef5 = React.createRef();
        this.myRef6 = React.createRef();


    }


    componentDidMount() {
        this.changeState(); // 变量转换
        this.initJuris(); // 权限
        this.unitsList() //合作单位
        setTimeout(() => {
            this.myRef1.current.focus();
        }, 300)
    }


    // 合作单位
    unitsList = () => {
        let data = {
            params: [{
                "code": "",
                "desc": '',
            }]
        }
        $http.post('urlS', this, {
            code: "01040060",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        unitsList: res.contractUnit, // 合作单位
                    });
                }
            }
        });
    }


    // 权限
    initJuris = () => {
        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: 'O'  // 类型
            }]
        }
        $http.post('urlS', this, {
            code: "05210001",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        otherPayData: res.groupConfig.HBOPConfigPaymode[0].OPCharge || [],  // 其他付款方式
                        payType: res.groupConfig.HBOPConfigPaymode[0].OPCharge[0].paywID || '',
                        otherPay: res.groupConfig.HBOPConfigPaymode[0].OPCharge[1].paywID || '',
                    }, () => {
                        let { otherPay, payType } = this.state
                        if (otherPay === '7' || payType === '7') {  //合作记账单位
                            this.setState({ hzDis: true })
                        } else {
                            this.setState({ hzDis: false })
                        }
                    });
                }
            }
        });
    }

    changeState = () => {
        this.setState({
            chargeRecodeId: this.props.chargeRecodeId || '',
            cancel: this.props.cancel || '',
        }, () => {
            this.money()  // 金额
        })
    }

    // 金额
    money = () => {
        var data = {
            params: [{
                "recodeIDStr": this.state.chargeRecodeId || '', // 交款记录id
            }]
        }


        $http.post('urlADS', this, {
            code: "05210008",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        moneyData: res.chargeAmtInfo[0], //金额对象
                        accountPayWayId: res.chargeAmtInfo[0].paywAccID, // 院内账户支付方式id
                        payWayCashId: res.chargeAmtInfo[0].paywCashID, // 现金支付方式id
                        cashInCashVal: '0.00',
                        zeroPay:'0.00',
                        otherPayMoney:'0.00',
                        payingAccountAmt: res.chargeAmtInfo[0].payingAccountAmt,
                    })
                }
            }
        });
    }


    // 收费确认
    chargingConfir = () => {
        let { accountPayWayId, payWayCashId, moneyData, cashInCashVal, otherPay, otherPayMoney, otherPayData, unitsListVal, payType } = this.state

        if (parseFloat(otherPayMoney) > 0) {
            if (otherPay === '' || !otherPay) {
                message.error('请选择其他支付方式')
                return false
            }
        }

        let otherPayCode = otherPayData.filter((item, i) => {
            return item.paywID === otherPay
        })

        if (otherPayCode.paywCode === 'CCP') { //合作单位记账
            if (unitsListVal === '' || !unitsListVal) {
                message.error('请选择合作医院')
                return false
            }
        }

        if (parseFloat(cashInCashVal) + parseFloat(otherPayMoney) < parseFloat((parseFloat(moneyData.lastPayAmt) - parseFloat(moneyData.payingAccountAmt)))) {
            message.error('实付金额小于应付金额')
            return false
        }




        // let otherPayStr = otherPay === '' ? '' : otherPay + '^' + parseFloat(parseFloat(moneyData.lastPayAmt) - parseFloat(cashInCashVal) - parseFloat(moneyData.payingAccountAmt)).toFixed(2) //支付方式
        // let cashInCashValStr = otherPay === '' ? moneyData.lastPayAmt : cashInCashVal

        let cashInCashValStr = parseFloat(cashInCashVal) > parseFloat(parseFloat(moneyData.lastPayAmt) - parseFloat(moneyData.payingAccountAmt)) ? parseFloat(parseFloat(moneyData.lastPayAmt) - parseFloat(moneyData.payingAccountAmt)) : cashInCashVal

        let otherPayStr = parseFloat(otherPayMoney) > 0 ? otherPay + '^' + parseFloat(parseFloat(moneyData.lastPayAmt) - parseFloat(cashInCashVal) - parseFloat(moneyData.payingAccountAmt)).toFixed(2) : '' //支付方式



        var data1 = {
            params: [{
                "recordIDinfo": this.state.chargeRecodeId || '', // 交款记录id
                "userID": JSON.parse(window.sessionStorage.userData).userID || '', //收费员ID
                "sflag": "0", //是收费还是退费
                "accID": this.state.moneyData.accountID, //病人账户ID
                "paywIDinfo": accountPayWayId + '^' + moneyData.payingAccountAmt + String.fromCharCode('2') + payType + '^' + cashInCashValStr + String.fromCharCode('2') + otherPayStr,//支付方式串 
                "printflag": "Y",//是否打印发票
            }]
        }

        var data2 = {
            params: [{
                "recordIDinfo": this.state.chargeRecodeId || '', // 交款记录id
                "userID": JSON.parse(window.sessionStorage.userData).userID || '', //收费员ID
                "sflag": "0", //是收费还是退费
                "accID": this.state.moneyData.accountID, //病人账户ID
                "paywIDinfo": '',//支付方式串 
                "printflag": "Y",//是否打印发票
            }]
        }

        $http.post('urlADS', this, {
            code: "05210024",
            data: data1,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    $http.post('urlADS', this, {
                        code: "05210007",
                        data: data2,
                        success: function (res) {
                            let errorCode = res.errorCode;
                            if (errorCode === '0') {
                                this.props.updatePay() // 退费弹框
                            }
                        }
                    });

                }
            }
        });


    }

        //计算
        sumMoney = () => {
            let { moneyData, payingAccountAmt } = this.state
    
            moneyData.payingAccountAmt = payingAccountAmt
    
            moneyData.payingAccountAmt = parseFloat(parseFloat(moneyData.payingAccountAmt) - parseFloat(this.state.otherPayMoney) - parseFloat(this.state.cashInCashVal)).toFixed(2)
    
            if (parseFloat(moneyData.payingAccountAmt) < 0) {
                moneyData.payingAccountAmt = '0.00'
            }
    
            this.setState({
                moneyData: moneyData
            })
        }

    // 其他支付方式金额
    otherPayMoney = (e) => {
        this.setState({ otherPayMoney: Keup.MoneyReplace(e.target.value) });
        if (Keup.MoneyReplace(e.target.value) === '') {
            return false
        }
        if (parseFloat(Keup.MoneyReplace(this.state.cashInCashVal)) + parseFloat(Keup.MoneyReplace(e.target.value)) > parseFloat(this.state.moneyData.lastPayAmt)) {
            this.setState({
                zeroPay: parseFloat(parseFloat(Keup.MoneyReplace(this.state.cashInCashVal)) + parseFloat(Keup.MoneyReplace(e.target.value)) - parseFloat(this.state.moneyData.lastPayAmt)).toFixed(2)// 找零
            }, () => {
                this.sumMoney()
            })

        } else {
            this.setState({
                zeroPay: '0.00', // 找零
            }, () => {
                this.sumMoney()
            })
        }
    }

    // 实收现金
    cashInCash = (e) => {
        let val = e.target.value
       
        const { moneyData } = this.state

        this.setState({
            cashInCashVal: Keup.MoneyReplace(val) // 金额过滤
        })

        if(Keup.MoneyReplace(val) === ''){
            val='0.00'
        }

        if (parseFloat(Keup.MoneyReplace(val)) > parseFloat(moneyData.lastPayAmt)) {
            this.setState({
                otherPayDis: true, // 其他支付不可选
                // otherPay: '', // 其他支付方式
                otherPayMoney: '0.00', // 其他支付金额
                zeroPay: parseFloat(parseFloat(Keup.MoneyReplace(val)) - parseFloat(moneyData.lastPayAmt)).toFixed(2)// 找零
            }, () => {
                this.sumMoney()
            })

        } else {
            this.setState({
                otherPayDis: false, // 其他支付不可选
                // otherPay: '', // 其他支付方式
                otherPayMoney: parseFloat(parseFloat(moneyData.lastPayAmt) - parseFloat(moneyData.payingAccountAmt) - parseFloat(Keup.MoneyReplace(val))).toFixed(2), // 其他支付金额
                zeroPay: '0.00', // 找零
            }, () => {
                this.sumMoney()
            })
        }

    
    }

    // 其他支付方式
    otherPay = (e) => {

        this.setState({ otherPay: e }, () => {
            let { otherPay, payType } = this.state
            setTimeout(() => {
                this.myRef4.current.focus();
            }, 300)
            if (otherPay === '7' || payType === '7') {  //合作记账单位
                this.setState({ hzDis: true })
            } else {
                this.setState({ hzDis: false })
            }
        });
    }

    // 支付方式
    payType = (e) => {
        this.setState({ payType: e }, () => {
            let { otherPay, payType } = this.state
            setTimeout(() => {
                this.myRef2.current.focus();
            }, 300)

            if (otherPay === '7' || payType === '7') {  //合作记账单位
                this.setState({ hzDis: true })
            } else {
                this.setState({ hzDis: false })
            }
        });
    }
    // 合作单位
    unitsListVal = (e) => {
        this.setState({ unitsListVal: e }, () => {
            setTimeout(() => {
                this.myRef6.current.focus();
            }, 300)
        });
    }



    //金额1回车
    onPressEnter1 = () => {
        let { payType, otherPay, otherPayDis } = this.state
        if (otherPayDis) {
            if (payType === '7' || otherPay === '7') {  //合作记账单位
                setTimeout(() => {
                    this.myRef5.current.focus();
                }, 300)
            } else {
                setTimeout(() => {
                    this.myRef6.current.focus();
                }, 300)
                // this.chargingConfir() //确认收费
            }

        } else {
            setTimeout(() => {
                this.myRef3.current.focus();
            }, 300)
        }

        // setTimeout(() => {
        //     this.myRef3.current.focus();
        // }, 300)



    }

    //金额1回车
    onPressEnter2 = () => {
        let { payType, otherPay, otherPayDis } = this.state
        if (payType === '7' || otherPay === '7') {  //合作记账单位
            setTimeout(() => {
                this.myRef5.current.focus();
            }, 300)
        } else {
            setTimeout(() => {
                this.myRef6.current.focus();
            }, 300)
            // this.chargingConfir() //确认收费
        }
    }




    render() {
        let { moneyData, } = this.state
        return (
            <div >
                <Row className='mT10'>
                    <Col span={24} style={{ fontSize: '14px' }} >
                        <div >
                            <div style={{ display: 'flex' }}><div className='border-radius-fee'></div>
                                <div style={{ marginLeft: 10, fontWeight: 'bold' }}>收费信息</div></div>
                            <div style={{ float: 'left', marginLeft: 30 }}>
                                <span><span style={{ background: '#F5F4F4' }}>实际金额(元)：{moneyData.recordPatAmt}</span>
                                    <span style={{ color: '#FA8C16' }}></span>
                                </span><br />

                                <span><span style={{ background: '#F5F4F4' }}>统筹金额(元)：{moneyData.paywTCAmt}</span>
                                    <span style={{ color: '#FA8C16' }}></span>
                                </span><br />
                                <span><span style={{ background: '#F5F4F4' }}>院内账户(元)：{moneyData.payingAccountAmt} </span>
                                    <span style={{ color: '#FA8C16' }}></span>
                                </span>
                                <span style={{ marginLeft: 10 }}>账户余额(元):<span style={{ color: '#FA8C16' }}> {moneyData.accountAmt}</span>
                                    <span style={{ marginLeft: '10px', width: '50px', color: 'rgb(66, 185, 131)' }}>{moneyData.accountFlagDesc}</span>
                                    {/* <label ><Checkbox style={{ marginLeft: 10 }} /><span>不使用账户</span></label>  */}

                                </span>
                                <br />
                                <span><span style={{ background: '#F5F4F4' }}>社保账户(元)：{moneyData.paywInsuAmt}</span>
                                    <span style={{ color: '#FA8C16' }}></span>
                                    <span style={{ marginLeft: 10 }}>账户余额(元)：<span style={{ color: '#FA8C16' }}>{moneyData.paywInsuAmt}</span></span>
                                </span>
                            </div>
                            <div style={{ float: 'right', marginRight: '18%' }}>
                                <span><span style={{ background: '#F5F4F4' }}>减免金额(元)：{moneyData.recordAllowAmt}</span>
                                    <span style={{ color: '#FA8C16' }}></span>
                                </span>
                            </div>
                        </div>
                    </Col>
                </Row>


                <Row className='mT10'>
                    <Col span={12}>
                        <Row className='mT10'>
                            <Col span={8} className='modalLabel '>付款方式：</Col>
                            <Col span={16} >
                                <Select ref={this.myRef1} showSearch optionFilterProp="title" placeholder="请选择付款方式" style={{ width: '100%' }} value={this.state.payType} onSelect={(event) => { this.payType(event) }}  >
                                    {this.state.otherPayData.map(item => <Option title={item.paywDesc + '^' + item.paywCode} key={item.paywID} value={item.paywID}  >{item.paywDesc}</Option>)}
                                </Select>
                            </Col>
                        </Row>

                    </Col>
                    <Col span={12}>
                        <Row className='mT10'>
                            <Col span={8} className='modalLabel' style={{ textAlign: 'right' }}>金额：</Col>
                            <Col span={16} >
                                <Input ref={this.myRef2} className='input' addonBefore="￥" onChange={(e) => { this.cashInCash(e); }} value={this.state.cashInCashVal} onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } this.setState({ cashInCashVal: parseFloat(event.target.value).toFixed(2) }) }} onFocus={(event) => { if (event.target.value === '0.00') { event.target.value = '' } }} onPressEnter={this.onPressEnter1} />
                            </Col>
                        </Row>

                    </Col>

                </Row>
                <Row>
                    <Col span={12}>
                        <Row className='mT10'>
                            <Col span={8} className='modalLabel '>其他付款方式：</Col>
                            <Col span={16} >
                                <Select ref={this.myRef3} showSearch disabled={this.state.otherPayDis}  optionFilterProp="title" placeholder="请选择其他付款方式" style={{ width: '100%' }} value={this.state.otherPay} onSelect={(event) => { this.otherPay(event) }}  >
                                    {this.state.otherPayData.map(item => <Option title={item.paywDesc + '^' + item.paywCode} key={item.paywID} value={item.paywID}  >{item.paywDesc}</Option>)}
                                </Select>
                            </Col>
                        </Row>

                    </Col>
                    <Col span={12}>
                        <Row className='mT10'>
                            <Col span={8} className='modalLabel' style={{ textAlign: 'right' }}>金额：</Col>
                            <Col span={16} ><Input ref={this.myRef4} disabled={this.state.otherPayDis}  className='input' addonBefore="￥" value={this.state.otherPayMoney} onChange={(event) => { this.otherPayMoney(event) }} onBlur={(event) => { if (event.target.value === '') { event.target.value = '0.00' } this.setState({ otherPayMoney: parseFloat(event.target.value).toFixed(2) }) }} onFocus={(event) => { if (event.target.value === '0.00') { event.target.value = '' } }} onPressEnter={this.onPressEnter2} /></Col>
                        </Row>
                    </Col>
                </Row>

                <Row className='mT10' style={{ display: this.state.hzDis ? 'block' : 'none' }}>
                    <Col span={4} className='modalLabel '>合作单位：</Col>
                    <Col span={20} >
                        <Select ref={this.myRef5} allowClear showSearch optionFilterProp="title" placeholder="请选择合作协作医院" style={{ width: '100%' }} value={this.state.unitsListVal} onSelect={(event) => { this.unitsListVal(event) }}  >
                            <Option value=''>请选择</Option>
                            {this.state.unitsList.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                        </Select>
                    </Col>
                </Row>
                <div style={{ textAlign: 'right', margin: '10px 0' }}>
                    <Button onClick={this.handleCancel} style={{ display: this.state.cancel === '' ? 'none' : 'block', marginRight: '20px' }}>取消</Button>
                    <Input ref={this.myRef6} type="primary" value="确定" readOnly="readOnly" onClick={this.chargingConfir} style={{ textAlign: 'center', backgroundColor: '#1999db', width: '60px', color: '#fff' }} onPressEnter={this.chargingConfir} />
                    {/* <Button type="primary" onClick={this.chargingConfir}>确定</Button> */}
                </div>

            </div >

        )
    }
}