// 病人就诊信息医嘱收费项/优惠
import React from 'react'
import { Table, Button, Form, Row, Col, Input, message, InputNumber, Select, AutoComplete } from 'antd'
import { $http } from '../../../containers/config/https';
import TipHeader from '../charges/component/TipHeader';
import '../charges/style/style.less';
import { Util } from 'tools/index';

const { TextArea } = Input;

class PatientAdmOrderCharges extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            userInfo: {},
            dataPatChar: [], // 挂号table数据
            dataCharges: [],      //医嘱收费项table数据
            dataChargesBkp: [],      //医嘱收费项table数据备份
            total: 0,
            page: 1,
            pageSize: 50,
            selectedRowKeys: [],
            limitedAmt: '',
            limitedPercent: '',
            coupon: 0,
            totalAmt: 0,    // 总价
            payAmt: undefined, // 实付金额
            orderColumns: [],
            batchRemarks: undefined, // 批量备注
        }

        this.columns = [{
            title: '挂号时间',
            dataIndex: 'admDateTime',
            width: 200,
            align: 'center',
        }, {
            title: '科室',
            dataIndex: 'admLocDesc',
            width: 100,
            align: 'center',
        }, {
            title: '医生',
            dataIndex: 'admDocDesc',
            width: 100,
            align: 'center',
        }, {
            title: '接待人',
            dataIndex: '',
            width: 100,
            align: 'center',
        }, {
            title: '诊断名称',
            dataIndex: 'diagnose',
            width: 150,
            align: 'center',
        }]
        this.selectFocus = React.createRef();

    }

    componentDidMount() {
        this.props.onRef(this);
        this.medicalInformation(this.props.admID);
        this.getOrderColumns();
    }

    getOrderColumns = () => {
        let { selectData } = this.props;
        let orderColumns = [
            // {
            //     title: '医嘱ID',
            //     dataIndex: 'detailID',
            //     width: 100,
            //     align: 'center',
            // },
            {
                title: '医嘱名称',
                dataIndex: 'medItemDesc',
                width: 100,
                align: 'center',
            },
            {
                title: '收费项代码',
                dataIndex: 'itemCode',
                width: 100,
                align: 'center',
            },
            {
                title: '收费项名称',
                dataIndex: 'itemDesc',
                width: 100,
                align: 'center',
            },
            {
                title: '医保代码',
                dataIndex: '',
                width: 100,
                align: 'center',
            },
            {
                title: '价格',
                dataIndex: 'price',
                width: 100,
                align: 'center',
            },
            {
                title: '数量',
                dataIndex: 'qty',
                width: 100,
                align: 'center',
            },
            {
                title: '金额',
                dataIndex: 'totalPrice',
                width: 100,
                align: 'center',
            },
            {
                title: '优惠金额',
                dataIndex: 'discountAmt',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    let displayDiscountAmt = data.discountAmt ? parseFloat(data.discountAmt).toFixed(2) : 0
                    let disabledflag = false;
                    if (this.state.selectedRowKeys.includes(index)) {
                        if (this.state.coupon == 0 || this.state.coupon == '') {
                            disabledflag = false
                        }
                        else {
                            disabledflag = true
                        }
                    }
                    return <InputNumber min={-999999999.0000} max={parseFloat(data.totalPrice)} style={{ width: '95%' }} id={"discountAmt-input" + index} ref={this.selectFocus}
                        value={displayDiscountAmt}
                        onChange={(val) => this.calcDiscount(index, val)}
                        disabled={
                            data.ordSelect === 'Y' ? true : disabledflag}
                    />
                }
            },
            // {
            //     title: '限定价格',
            //     dataIndex: 'limitedPrice',
            //     width: 100,
            //     align: 'center',
            //     render: (text, data, index) => {
            //         return <InputNumber min={0} max={data.price} style={{ width: '95%' }} id={"limitedPrice-input" + index} ref={this.selectFocus}
            //             value={data.limitedPrice}
            //             onChange={(val) => this.handLimitedPrice(index, val)}
            //             disabled={data.ordSelect==='Y' ? true : false}
            //         />
            //     } 
            // },
            {
                title: '限定折扣',
                dataIndex: 'limitedPercent',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    let displayLimitedPercent = data.limitedPercent ? parseFloat(data.limitedPercent).toFixed(2) : 0
                    let disabledflag = false;
                    if (this.state.selectedRowKeys.includes(index)) {
                        if (this.state.coupon == 0 || this.state.coupon == '') {
                            disabledflag = false
                        }
                        else {
                            disabledflag = true
                        }
                    }
                    return <InputNumber max={50.0000} min={0} style={{ width: '95%' }} id={"limitedPercent-input" + index} ref={this.selectFocus}
                        value={displayLimitedPercent}
                        onChange={(val) => this.handLimitedPercent(index, val)}
                        disabled={data.ordSelect === 'Y' ? true : disabledflag}
                    />
                }
            },
            {
                title: '实付(优惠后)金额',
                dataIndex: 'payAmt',
                width: 100,
                align: 'center',
                render: (text, data, index) => {
                    let displayPayAmt = data.payAmt ? parseFloat(data.payAmt).toFixed(2) : 0
                    let disabledflag = false;
                    if (this.state.selectedRowKeys.includes(index)) {
                        if (this.state.coupon == 0 || this.state.coupon == '') {
                            disabledflag = false
                        }
                        else {
                            disabledflag = true
                        }
                    }
                    return <InputNumber min={-999999999.0000} max={parseFloat(data.totalPrice)} style={{ width: '95%' }} id={"payAmt-input" + index} ref={this.selectFocus}
                        value={displayPayAmt}
                        onChange={(val) => this.handleRecordPayAmtChange(index, val)}
                        disabled={data.ordSelect === 'Y' ? true : disabledflag}
                    />
                }
            },
            {
                title: '申请理由',
                dataIndex: 'remarks',
                width: 200,
                align: 'center',
                render: (text, record, index) => {
                    if (selectData?.remarksTypeCode === 'AutoComplete') {
                        return (
                            <AutoComplete
                                allowClear
                                placeholder="请选择"
                                style={{ width: '100%' }}
                                disabled={record.ordSelect === 'Y'}
                                defaultActiveFirstOption={false}
                                dataSource={React.$SelectOptions(selectData?.remarksList || [], 'descripts')}
                                onChange={(e) => this.handleInputChange('remarks', index, e)}
                            >
                            </AutoComplete>
                        )
                    } else if (selectData?.remarksTypeCode === 'TextArea') {
                        return (
                            <TextArea
                                allowClear
                                autoSize={{ minRows: 1, maxRows: 5 }}
                                placeholder="请输入"
                                disabled={record.ordSelect === 'Y'}
                                value={record?.remarks || undefined}
                                onChange={(e) => this.handleInputChange('remarks', index, e.target.value)}
                            />
                        )
                    } else {
                        return (
                            <Select
                                style={{ width: '100%' }}
                                // mode="tags"
                                placeholder="请选择"
                                disabled={record.ordSelect === 'Y'}
                                value={record?.remarks || undefined}
                                onChange={(e) => this.handleInputChange('remarks', index, e)}
                            >
                                {React.$SelectOptions(selectData?.remarksList || [], 'descripts')}
                            </Select>
                        )
                    }
                }
            },
            {
                title: '详情描述',
                dataIndex: 'applyflagDesc',
                width: 200,
                align: 'center',
            }
        ];
        this.setState({ orderColumns });
    }

    handleInputChange = (dataIndex, index, e, type) => {
        let { dataCharges } = this.state;
        if (type === 'tags') {
            dataCharges[index][dataIndex] = e[e.length - 1];
        } else {
            dataCharges[index][dataIndex] = e;
        }
        this.setState({});
    }

    // 填写优惠价时自动勾选
    autoCheck = (index) => {
        let { selectedRowKeys } = this.state
        if (!selectedRowKeys.includes(index)) {
            selectedRowKeys.push(index)
            this.setState({ selectedRowKeys })
        }
    }

    // 计算折扣平均值
    calcDiscountAvg = () => {
        //此处只做粗略的计算，审核处还会重新计算
        let { coupon, selectedRowKeys, dataCharges, dataChargesBkp } = this.state;
        if (!coupon) coupon = 0
        let totalAmt = 0
        let len = selectedRowKeys.length;
        for (let i = 0; i < len; i++) {
            totalAmt = totalAmt + dataCharges[selectedRowKeys[i]].totalPrice
        }
        if (coupon > totalAmt) {
            coupon = totalAmt
        }

        let avgPercent = parseFloat(1 - (coupon / totalAmt)).toFixed(8)
        let discountedAmt = 0   // 已优惠金额
        let totlamterr = parseFloat(coupon)
        let lastkey = 0
        // let avg = (coupon / len).toFixed(2)
        for (let i = 0; i < len; i++) {
            let paytotalamt = parseFloat(dataCharges[selectedRowKeys[i]].modelTotalAmt)
            dataCharges[selectedRowKeys[i]].limitedPercent = avgPercent
            let price = dataCharges[selectedRowKeys[i]].price       //总价格
            // let discountedprice=(1-avgPercent)*price                //优惠价格
            let discountedprice = parseFloat((1 - avgPercent) * price).toFixed(8)                //优惠价格
            let qty = parseFloat(dataCharges[selectedRowKeys[i]].qty)
            let discountedAmt = parseFloat(discountedprice * qty).toFixed(2)
            totlamterr = totlamterr - discountedAmt
            dataCharges[selectedRowKeys[i]].discountAmt = discountedAmt;
            dataCharges[selectedRowKeys[i]].payAmt = price;
            if (paytotalamt != 0) {
                lastkey = i
            }
        }
        if (totlamterr != 0) {
            let discountAmt = dataCharges[selectedRowKeys[lastkey]].discountAmt
            discountAmt = parseFloat(discountAmt) + parseFloat(totlamterr)
            let price = dataCharges[selectedRowKeys[lastkey]].price       //总价格
            let qty = parseFloat(dataCharges[selectedRowKeys[lastkey]].qty)
            let paytotalamt = price * qty
            let limitedPercent = parseFloat(1 - (discountAmt / paytotalamt)).toFixed(8)
            dataCharges[selectedRowKeys[lastkey]].limitedPercent = limitedPercent;
            dataCharges[selectedRowKeys[lastkey]].discountAmt = discountAmt;
            dataCharges[selectedRowKeys[lastkey]].payAmt = price;
        }
        // 恢复未勾选
        for (let i = 0; i < dataChargesBkp.length; i++) {
            if (!selectedRowKeys.includes(i)) {
                dataCharges[i].discountAmt = ''
                dataCharges[i].limitedPercent = ''
            }
        }
        this.setState({ dataCharges, coupon })
    }

    calcDiscount = (index, val) => {
        let { dataCharges } = this.state;
        if (val) {
            dataCharges[index].discountAmt = val;
            dataCharges[index].limitedAmt = '';
            dataCharges[index].limitedPercent = parseFloat(1 - (val / dataCharges[index].totalPrice)).toFixed(8);
            dataCharges[index].payAmt = parseFloat(dataCharges[index].totalPrice - val).toFixed(8);
            dataCharges[index].limitedPrice = '';
            // 处理分母为0
            if (!dataCharges[index].totalPrice) {
                dataCharges[index].limitedPercent = 1
            }
            this.setState({ dataCharges }, () => this.autoCheck(index))
        }
    }

    handLimitedPercent = (index, val) => {
        let { dataCharges } = this.state;
        if (val) {
            dataCharges[index].discountAmt = (dataCharges[index].totalPrice * (1 - val)).toFixed(8);
            dataCharges[index].payAmt = (dataCharges[index].totalPrice * (val)).toFixed(8);
            dataCharges[index].limitedAmt = '';
            dataCharges[index].limitedPercent = val;
            dataCharges[index].limitedPrice = '';
            this.setState({ dataCharges }, () => this.autoCheck(index))
        }
    }

    handleRecordPayAmtChange = (index, val) => {
        let { dataCharges } = this.state;
        if (val || val == 0) {
            dataCharges[index].payAmt = val;
            dataCharges[index].limitedPercent = parseFloat((val / dataCharges[index].totalPrice)).toFixed(8);;
            dataCharges[index].discountAmt = (dataCharges[index].totalPrice - val).toFixed(8);
            dataCharges[index].limitedAmt = '';
            dataCharges[index].limitedPrice = '';
            this.setState({ dataCharges }, () => this.autoCheck(index))
        }
    }

    // 就诊信息
    medicalInformation = (admID) => {
        let { dataCharges } = this.state
        let data = {
            params: [{
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '', //医院id 
                admID: admID, //就诊id
                patID: this.props.patID
            }],
        }

        $http.post('urlS', this, {
            code: "05210003",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    this.setState({
                        dataPatChar: res.admInfo || [], // // 挂号table数据
                    }, () => this.orderCharges());
                }
            }
        });
    }

    // 医嘱收费项
    orderCharges = () => {
        let selectedRowKeys = []
        const { selectData } = this.props;
        let { page, pageSize } = this.state;
        var data = {
            params: [{
                discountSubCatID: selectData && 'discountSubCatID' in selectData ? selectData.discountSubCatID : undefined, // 医嘱子类
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
                admID: this.props.admID ? this.props.admID : '',
                locID: JSON.parse(window.sessionStorage.userData).locID || '',
                groupID: JSON.parse(window.sessionStorage.userData).groupID || ''
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }

        $http.post('urlS', this, {
            code: "05210069",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let totalAmt = 0, dataChargesBkp = []
                    for (let i = 0; i < res.total; i++) {
                        res.result[i].payAmt = (res.result[i]?.totalPrice || 0) - (res.result[i]?.discountAmt || 0).toFixed(8);
                        if (res.result[i].ordSelect != 'Y') {
                            selectedRowKeys.push(i)
                        }
                        totalAmt = totalAmt + res.result[i].totalPrice
                        let bkpObj = {
                            discountAmt: res.result[i].discountAmt,
                            limitedPercent: res.result[i].limitedPercent
                        }
                        dataChargesBkp.push(bkpObj)
                    }
                    this.setState({
                        dataCharges: res.result || [], // 挂号table数据
                        dataChargesBkp,
                        total: res.total,
                        selectedRowKeys,
                        totalAmt,
                        coupon: 0,
                        payAmt: undefined, // 实付金额
                    });
                }
            }
        });
    }

    //审批
    priceApprove = () => {
        let { remarksRequiredFlag, selectData } = this.props;
        let { selectedRowKeys, dataCharges, batchRemarks } = this.state
        let arr = []
        for (let i = 0; i < selectedRowKeys.length; i++) {
            arr.push(dataCharges[selectedRowKeys[i]])
        }
        for (let i = 0; i < arr.length; i++) {
            arr[i].remarks = arr[i]?.remarks || batchRemarks;
        };
        let saveFlag = true;
        if (remarksRequiredFlag === 'Y') {
            for (let i = 0; i < arr.length; i++) {
                if (!(arr[i] && arr[i].remarks)) {
                    saveFlag = false;
                    break;
                }
            }
        }
        if (!saveFlag) {
            message.error('申请理由不能为空！');
            return;
        }
        let data = {
            params: [{
                discountSubCatID: selectData && 'discountSubCatID' in selectData ? selectData.discountSubCatID : undefined, // 医嘱子类
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
                userID: JSON.parse(window.sessionStorage.userData).userID || '',
                admID: this.props.admID ? this.props.admID : '',
                coupon: this.state.coupon,
                applyflag: this.props.applyflag ? this.props.applyflag : '',
                selectedRowKeys: arr
            }],
        }
        $http.post('urlS', this, {
            code: "05210070",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success("操作成功！");
                    this.orderCharges();
                    this.props.closeModal();
                    this.setState({ batchRemarks: undefined });
                }
            }
        });
    }

    //取消审批
    cancelPriceApprove = () => {
        let { selectedRowKeys, dataCharges } = this.state
        var data = {
            params: [{
                hospID: JSON.parse(window.sessionStorage.userData).hospID || '',
                userID: JSON.parse(window.sessionStorage.userData).userID || '',
                admID: this.props.admID ? this.props.admID : '',
                applyflag: this.props.applyflag ? this.props.applyflag : '',
                selectedRowKeys: dataCharges
            }],
        }
        $http.post('urlS', this, {
            code: "05210071",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success("操作成功！")
                    this.orderCharges()
                    //this.props.closeModal()                    
                }
            }
        });
    }

    //单击类型事件
    onClickRow = (record) => {
        return {
            onClick: () => {
                this.setState({
                    record: record,
                    admID: record.admID
                }, () => {
                    this.orderCharges()
                })
            }
        }
    }

    setRowClassName = (record) => {
        return record.admID === this.state.admID ? 'clickRowStyle' : '';
    }

    setDiscountRowClassName = (record) => {
        return record.discountAmt != '' ? 'clickRowStyle' : '';
    }

    //数据
    // 页码改变的回调，参数是改变后的页码及每页条数
    appPageChange = (page, pageSize) => {
        this.setState({
            page: page,
            pageSize: pageSize,
        }, () => {
            // 重新调用查询方法
            this.orderCharges();
        });
    }

    // 条数改变的回调
    apponShowSizeChange = (current, size) => {
        this.setState({
            page: current,
            pageSize: size,
        }, () => {
            // 重新调用查询方法
            this.orderCharges();
        });
    }

    // 实付金额
    handlePayAmtChange = (e) => {
        const { selectedRowKeys, dataCharges } = this.state;
        let payAmt = e;
        let totalAmt = 0
        for (let i = 0; i < selectedRowKeys.length; i++) {
            totalAmt = totalAmt + dataCharges[selectedRowKeys[i]].totalPrice
        }
        if (payAmt > totalAmt) {
            payAmt = totalAmt
        }
        this.setState({ payAmt: e, coupon: (!payAmt && payAmt !== 0) ? 0 : totalAmt - payAmt }, () => {
            this.calcDiscountAvg();
        })
    }

    render() {
        const { selectedRowKeys, orderColumns, batchRemarks } = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys) => {
                this.setState({ selectedRowKeys }, () => this.calcDiscountAvg())
            },
            getCheckboxProps: record => ({
                disabled: (record.ordSelect == 'Y' ? true : false),
            }),
        };

        return (
            <div>
                <div>
                    <Row >
                        <Col span={10}>
                            <Row style={{ padding: '0 24px' }}>
                                <Col span={23} style={{ height: '230px' }} >
                                    {!Util.isEmpty(this.props.userInfo) ? <TipHeader userInfo={this.props.userInfo} /> : null}
                                    <Row style={{ marginBottom: '10px' }}>
                                        优惠抵扣金：
                                        <InputNumber
                                            min={-999999999}
                                            max={this.state.totalAmt}
                                            placeholder="输入后回车计算折扣"
                                            value={this.state.coupon}
                                            style={{ width: '150px' }}
                                            onChange={(val) => this.setState({ coupon: val }, () => this.calcDiscountAvg())}
                                            onPressEnter={this.calcDiscountAvg}
                                        />
                                        {this.props.payAmtFlag === 'Y' ? (
                                            <>
                                                实付金额：
                                                <InputNumber
                                                    min={-999999999}
                                                    max={this.state.totalAmt}
                                                    placeholder="优惠后实付金额"
                                                    value={this.state.payAmt}
                                                    style={{ width: '150px', marginLeft: '12px' }}
                                                    onChange={this.handlePayAmtChange}
                                                />
                                            </>
                                        ) : ''}
                                    </Row>
                                    <Row style={{ marginBottom: '10px' }}>
                                        <span style={{ display: 'inline-block', width: '85px', textAlign: 'right' }}>备注：</span>
                                        <TextArea
                                            allowClear
                                            style={{ width: '80%' }}
                                            autoSize={{ minRows: 1, maxRows: 2 }}
                                            placeholder="请输入"
                                            value={batchRemarks}
                                            onChange={Util.commonInputChange.bind(this, 'batchRemarks')}
                                        />
                                    </Row>
                                    <Row style={{ paddingLeft: '85px' }}>
                                        <Button type='primary' onClick={this.priceApprove}>{this.props.applyflag ? (this.props.applyflag == 'Y' ? '折扣申请' : '审批') : '审批'}</Button>
                                        <Button type='primary' onClick={this.cancelPriceApprove} style={{ marginLeft: '30px' }}>{this.props.applyflag ? (this.props.applyflag == 'Y' ? '取消申请' : '取消审批') : '取消审批'}</Button>
                                    </Row>
                                </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={14}>
                            <div className="table-operations">
                                <Row style={{ minHeight: '50px', paddingBottom: '10px', paddingLeft: '30px' }}>
                                    <Col span={23} >
                                        <Table
                                            className="outpatient-body"
                                            style={{ height: '200px' }}
                                            columns={this.columns}
                                            dataSource={this.state.dataPatChar}
                                            pagination={false}
                                            bordered={true}
                                            scroll={{ y: 160 }}
                                            onRow={this.onClickRow}
                                            rowClassName={this.setRowClassName}
                                        />
                                    </Col>
                                </Row>
                            </div>
                        </Col>
                    </Row>
                </div>
                <div style={{ background: '#f0f2f5', height: '10px', widht: '100%' }}></div>
                <div style={{ padding: 24, paddingTop: '0' }}>
                    <Row >
                        <Table
                            className="outpatient-body"
                            style={{ height: '400px', padding: 10 }}
                            columns={orderColumns}
                            pagination={false}
                            bordered={true}
                            dataSource={this.state.dataCharges}
                            scroll={{ x: 1300, y: 320 }}
                            rowSelection={rowSelection}
                            rowClassName={this.setDiscountRowClassName}
                        />
                    </Row>
                </div>
            </div>
        )
    }
}


export default Form.create()(PatientAdmOrderCharges)