// 作废重收

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

export default class WasteAndReclaimed extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            recordinvID: '', //收款记录发票记录服务的ID
            invType: '',//收款记录发票记录服务的类型
            parkRecordDrinfo: '', // 退费的负付款记录
            chargeRecodeId: '', // 交款记录id
            payArr: [],
            newPaywAmtNum: 0,
            payWData: [],
            FPatAmt: '',
            NewPatAmt: '',
            OldPatAmt: '',
            unitID: '',
            hzDis: false,
            unitsList: [], // 合作单位列表
            unitsListVal: '', //合作单位
            visible: false, // 第三方弹框
            authcodeVal: '',
        }

    }


    componentDidMount() {
        this.changeState(); // 变量转换
        this.unitsList(); //合作单位
        this.props.onRef && this.props.onRef(this);
    }

    // 合作单位
    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, // 合作单位
                    });
                }
            }
        });
    }

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

    // 合作单位
    unitsListVal = (e) => {
        this.setState({ unitsListVal: e });
    }


    // 金额
    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',
        //             })
        //         }
        //     }
        // });



        let data2 = {
            params: [{
                recordinvID: this.state.recordinvID || '', //付款记录表ID或集中打印发票表ID
                invtype: this.state.invType || '', // 记录类型 集中打印发票表ID, 传INV 付款记录表ID, 传PAY
                parkRecordDrinfo: this.state.parkRecordDrinfo || '', // 退费ID
                newpayrecordinfo: this.state.chargeRecodeId || '', // 新付款记录rowid串
                userID: JSON.parse(window.sessionStorage.userData).userID || '', //收费员ID
                paytype: 'O', // CB_InvType 中(代码 O 门诊发票, I 住院发票, R 挂号发票, )
                groupID: JSON.parse(window.sessionStorage.userData).groupID || '', // 登录安全组
                locID: JSON.parse(window.sessionStorage.userData).locID || '', // 登录科室
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '', // 登录医院
                ip: React.$getSessionData('ipConfig')?.ipv4 || '', // ip
            }]
        }

        $http.post('urlADS', this, {
            code: "05210028",
            data: data2,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    //

                    let { payArr, newPaywAmtNum } = this.state
                    payArr = res.payWData[0].parkPaywinfo.concat(res.payWData[0].paywIDinfo)
                    let someArr = new Map();
                    let newArr = payArr.filter((a) => !someArr.has(a.paywID) && someArr.set(a.paywID, 1))
                    // payArr = ArraySome.ArrayWeigh(payArr, 'remove') // 数组去重
                    payArr = newArr // 数组去重
                    for (let i = 0; i < payArr.length; i++) {
                        payArr[i].money = 0

                    }

                    // 初始值的总数
                    newPaywAmtNum = 0
                    res.payWData.map((item, i) => {
                        newPaywAmtNum += parseFloat(item.newPaywAmt)
                    })


                    this.setState({
                        payWData: res.payWData,
                        FPatAmt: res.FPatAmt,
                        NewPatAmt: res.NewPatAmt,
                        OldPatAmt: res.OldPatAmt,
                        payArr: payArr,
                        newPaywAmtNum: newPaywAmtNum,
                    }, () => {
                        this.sumNoney()
                    })

                }



            }
        });

    }


    moneySA = (e, i) => {
        let { payWData } = this.state
        payWData[i].parkPaywID = e


        if (payWData[i].parkPaywID === '7' || payWData[i].newPaywID === '7') {  //合作记账单位
            this.setState({ hzDis: true })
        } else {
            this.setState({ hzDis: false })
        }

        this.setState({
            payWData: payWData
        }, () => {
            this.sumNoney()
        })
    }
    moneySB = (e, i) => {
        let { payWData } = this.state
        payWData[i].newPaywID = e

        if (payWData[i].parkPaywID === '7' || payWData[i].newPaywID === '7') {  //合作记账单位
            this.setState({ hzDis: true })
        } else {
            this.setState({ hzDis: false })
        }


        this.setState({
            payWData: payWData
        }, () => {
            this.sumNoney()
        })
    }
    moneyIA = (e, i) => {
        let { payWData, newPaywAmtNum } = this.state
        let val = e.target.value
        if (!val || val === '') {
            val = '0'
        }

        if (i === 0) {
            if (payWData[1]) {
                if (parseFloat(newPaywAmtNum) - parseFloat(val) - parseFloat(payWData[1].newPaywAmt) < 0) {
                    message.error('不可大于收款金额！')
                    return false
                }
            } else {
                if (parseFloat(newPaywAmtNum) - parseFloat(val) < 0) {
                    message.error('不可大于收款金额！')

                    return false
                }
            }
        }

        if (i === 1) {
            if (payWData[0]) {
                if (parseFloat(newPaywAmtNum) - parseFloat(val) - parseFloat(payWData[0].newPaywAmt) < 0) {
                    message.error('不可大于收款金额！')

                    return false
                }
            }
        }


        if (!e.target.value || e.target.value === '') {
            payWData[i].newPaywAmt = '' // 金额过滤val

        } else {
            payWData[i].newPaywAmt = Keup.MoneyReplace(val) // 金额过滤val

        }

        this.setState({
            payWData: payWData
        }, () => {
            this.sumNoney()
        })
    }

    // 计算
    sumNoney = () => {
        let { payWData, payArr } = this.state
        let pay = []
        for (let i = 0; i < payArr.length; i++) {
            payArr[i].money = 0

        }
        payWData.map((item, i) => {
            pay.push({ type: item.newPaywID, num: item.newPaywAmt === '' ? "0" : item.newPaywAmt }, { type: item.parkPaywID, num: item.parkPaywAmt })
        })


        let sumArr = payArr.map((item, i) => {
            pay.map((item2, i) => {
                if (item.paywID == item2.type) {
                    item.money += parseFloat(item2.num)
                }
            })
            return item
        })
        this.setState({
            payArr: sumArr
        })
    }

    payvData = Util.debounce(() => {
        let { newPaywAmtNum, payWData } = this.state;
        let thisNum = 0;
        payWData.map((item, i) => {
            thisNum += parseFloat(item.newPaywAmt)
        })
        if (parseFloat(newPaywAmtNum) != parseFloat(thisNum)) {
            message.error('退费金额不一致！')
            return false
        }
        let newPayWData = payWData
        newPayWData.map((item, i) => {
            item.parkPaywinfo = []
            item.paywIDinfo = []
        })
        this.setState({ payLoading: true });
        var data = {
            params: [{
                recordinvID: this.state.recordinvID || '', //付款记录表ID或集中打印发票表ID
                invtype: this.state.invType || '', // 记录类型 集中打印发票表ID, 传INV 付款记录表ID, 传PAY
                parkRecordDrinfo: this.state.parkRecordDrinfo || '', // 退费ID
                newpayrecordinfo: this.state.chargeRecodeId || '', // 新付款记录rowid串
                userID: JSON.parse(window.sessionStorage.userData).userID || '', //收费员ID
                paytype: 'O', // CB_InvType 中(代码 O 门诊发票, I 住院发票, R 挂号发票, )
                groupID: JSON.parse(window.sessionStorage.userData).groupID || '', // 登录安全组
                locID: JSON.parse(window.sessionStorage.userData).locID || '', // 登录科室
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '', // 登录医院
                ip: React.$getSessionData('ipConfig')?.ipv4 || '', // ip
                payWData: newPayWData || [],
                unitID: this.state.unitsListVal || ''
            }]
        }
        $http.post('urlADS', this, {
            code: "05210029",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    if (res.transactionPayflag !== '') {
                        if (res.transactionPayflag === 'P') {
                            this.setState({
                                visible: true
                            }, () => {
                                setTimeout(() => {
                                    let { input } = this.userName; /** 如果是textArea的话，const { textAreaRef } = this.passWord;*/
                                    input.focus();
                                }, 300);
                            })
                        } else {
                            this.authcode("", () => {
                                // 29接口之后调取
                                this.nextCall()
                            }) // 第三方支付 不传参数
                        }
                    } else {
                        // 为空 直接执行后面的
                        this.nextCall()
                    }
                } else {
                    this.setState({ payLoading: false });
                }
            },
            error: function () {
                this.setState({ payLoading: false });
            }
        });
    })

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

        if (this.state.chargeRecodeId === '') {
            this.props.updateMoney() // 退费弹框
        } else {
            $http.post('urlADS', this, {
                code: "05210007",
                data: data2,
                success: function (res) {
                    let errorCode = res.errorCode;
                    this.setState({ payLoading: false });
                    if (errorCode === '0') {
                        this.props.updateMoney() // 退费弹框
                        if (res.invIDinfo && res.invIDinfo != '') {
                            this.props.handelThis.print2(res.invIDinfo)  // 打印
                        }
                        if (res.compleRecordIDinfo && res.compleRecordIDinfo != '') {
                            console.log(JSON.parse(window.sessionStorage.userData).hospCode, "JSON.parse(window.sessionStorage.userData).hospCode")
                            if (JSON.parse(window.sessionStorage.userData).hospCode == "H02") {
                                this.props.handelThis.handlePrintChargeVoucherNew(res.compleRecordIDinfo)
                            } else {
                                this.props.handelThis.handlePrintChargeVoucher(res.compleRecordIDinfo)//打印收费凭证.print2(res.invIDinfo)  // 打印
                            }

                        }
                    }
                },
                error: function () {
                    this.setState({ payLoading: false });
                }
            });
        }
    }

    authcodeVal = (e) => {
        this.setState({
            authcodeVal: e.target.value
        })
    }

    enterInputNextFocus = (e) => { // 回车
        let val = e.target.value
        this.authcode(val, () => {
            // 29接口之后调取
            this.nextCall()
        }) // 第三方支付
    }

    authcode = (authcode, callback) => {
        let { payWData } = this.state;
        let thisNum = 0;
        payWData.map((item, i) => {
            thisNum += parseFloat(item.newPaywAmt)
        })
        let newPayWData = payWData
        newPayWData.map((item, i) => {
            item.parkPaywinfo = []
            item.paywIDinfo = []
        })
        var data = {
            params: [{
                recordinvID: this.state.recordinvID || '', //付款记录表ID或集中打印发票表ID
                invtype: this.state.invType || '', // 记录类型 集中打印发票表ID, 传INV 付款记录表ID, 传PAY
                parkRecordDrinfo: this.state.parkRecordDrinfo || '', // 退费ID
                newpayrecordinfo: this.state.chargeRecodeId || '', // 新付款记录rowid串
                userID: JSON.parse(window.sessionStorage.userData).userID || '', //收费员ID
                paytype: 'O', // CB_InvType 中(代码 O 门诊发票, I 住院发票, R 挂号发票, )
                groupID: JSON.parse(window.sessionStorage.userData).groupID || '', // 登录安全组
                locID: JSON.parse(window.sessionStorage.userData).locID || '', // 登录科室
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '', // 登录医院
                ip: React.$getSessionData('ipConfig')?.ipv4 || '', // ip
                payWData: newPayWData || [],
                unitID: this.state.unitsListVal || '',
                authcode: authcode || '',
            }]
        }

        $http.post('urlADS', this, {
            code: "05100342",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    callback()
                    this.setState({
                        payLoading: false,
                        visible: false, // 第三方弹框
                    })
                } else {
                    this.setState({ payLoading: false });
                }
            },
            error: function () {
                this.setState({ payLoading: false });
            }
        });
    }

    render() {
        let { authcodeVal, payLoading } = this.state
        return (
            <div >
                <div>
                    <p className='Titl'>退收详情</p>
                    <Row className='TitRow' style={{ fontWeight: 'bold' }}>
                        <Col span={4}>
                            收款 (￥: {this.state.OldPatAmt})
                        </Col>
                        <Col span={11}>
                            负 (￥: {this.state.FPatAmt})
                        </Col>
                        <Col span={9}>
                            重收 (￥: {this.state.NewPatAmt})
                        </Col>
                    </Row>
                    <div style={{ maxHeight: '400px', overflow: 'auto' }}>
                        {this.state.payWData.map((item, i) =>
                            <Row className='TitRow' key={i} >
                                <Col span={4}>
                                    {item.oldPaywDesc + ':'}<span style={{ color: "#00ff99" }}> {'￥' + item.oldPaywAmt}</span>
                                </Col>
                                <Col span={11}>
                                    退回方式及金额
                                    <Select style={{ width: '130px', margin: '0 5px' }} placeholder="请选择" value={item.parkPaywID.toString()} onChange={(e) => { this.moneySA(e, i); }} disabled={item.isInsuFlag.toString() === 'Y' ? true : false} >
                                        {item.parkPaywinfo.map(item => <Option title={item.paywDesc + '^' + item.paywCode} key={item.paywID} value={item.paywID}  >{item.paywDesc}</Option>)}
                                    </Select>
                                    <Input style={{ width: '130px', marginTop: '9px' }} placeholder="请输入金额" className='input' addonBefore="￥" value={item.parkPaywAmt} disabled />
                                </Col>
                                <Col span={9}>
                                    <Select style={{ width: '130px', marginRight: '5px' }} placeholder="请选择" value={item.newPaywID.toString()} onChange={(e) => { this.moneySB(e, i); }} disabled={(parseFloat(this.state.NewPatAmt) === 0) || (item.isInsuFlag.toString() === 'Y') ? true : false}>
                                        {item.paywIDinfo.map(item => <Option title={item.paywDesc + '^' + item.paywCode} key={item.paywID} value={item.paywID}  >{item.paywDesc}</Option>)}
                                    </Select>
                                    <Input style={{ width: '130px', marginTop: '9px' }} allowClear placeholder="请输入金额" className='input' addonBefore="￥" value={item.newPaywAmt} onChange={(e) => { this.moneyIA(e, i); }} disabled={item.isInsuFlag.toString() === 'Y' ? true : false} />
                                </Col>
                            </Row>
                        )}
                    </div>
                    <Row className='mT10' style={{ display: this.state.hzDis ? 'block' : 'none' }}>
                        <Col span={2} className='modalLabel '>合作单位：</Col>
                        <Col span={6} >
                            <Select 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>
                    <p className='Titl' style={{ marginTop: '24px' }}>应收应退金额</p>

                    {this.state.payArr.map((item, i) =>
                        <Row className='TitRow' style={{ border: 'none', textAlign: 'left', display: parseFloat(item.money) === 0 ? 'none' : 'block' }} key={i} >
                            <Col span={4} offset={2}> {item.paywDesc}:</Col>
                            <Col span={4}><span style={{ color: parseFloat(item.money) > 0 ? 'rgb(245, 34, 45)' : '#000', fontSize: '14px' }}>￥{parseFloat(item.money).toFixed(2)}</span>  </Col>
                            <Col span={4}><Button style={{ background: parseFloat(item.money) > 0 ? 'rgba(245, 34, 45)' : '#fff', color: parseFloat(item.money) > 0 ? '#fff' : '#000' }}>{parseFloat(item.money) > 0 ? '收' : '退'}</Button></Col>
                        </Row>
                    )}
                    <div style={{ textAlign: 'right', margin: '10px 0' }}>
                        <Button loading={payLoading} onClick={this.payvData} style={{ background: 'rgba(66,185,131,1)', color: '#fff' }}>确认</Button>
                    </div>
                </div>
                <Modal
                    title="第三方交易"
                    visible={this.state.visible}
                    closable={false}
                    footer={false}
                    maskClosable={false}
                    keyboard={false}
                >
                    <Row>
                        <Col span={8}>付款码: </Col>
                        <Col span={16}>
                            <Input ref={(input) => { this.userName = input; }} placeholder="请输入付款码" className='input' value={authcodeVal} onChange={(e) => { this.authcodeVal(e) }} onPressEnter={(e) => { this.enterInputNextFocus(e) }} />
                        </Col>
                    </Row>
                </Modal>
            </div>
        )
    }
}