//账单查询门诊个人
import React from 'react'
import { Table, Button, Modal, message } from 'antd'
import moment from 'moment';
import { $http } from '../../../containers/config/https'
import InvRecordDeposit from './InvRecordDeposit'
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import store from 'store';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $loopPrint } from '../../lodop/Common/Print.js';
import '../charges/style/style.less'

const dateFormat = 'YYYY-MM-DD' || undefined;

export default class OPOutpatientPersonal extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            StartDate: moment(new Date, dateFormat).subtract(1, 'days'),
            EndDate: moment(new Date, dateFormat).subtract(1, 'days'),
            userInfo: {},
            // 表格数据
            tableData: [],
            showLoading: true,
            // 表格数据总条数
            total: 0,
            page: 1,
            pageSize: 10,
            selectedRowKeys: [],
            selectedRows: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            columns: []
        }
        // this.columns = [
        //     {
        //         title: '结算时间',
        //         dataIndex: 'footDateTime',
        //         width: 200,
        //         align: 'center',
        //     },
        //     {
        //         title: '应收金额',
        //         dataIndex: 'normalAmt',
        //         width: 100,
        //         align: 'center',
        //     },
        //     {
        //         title: '退款金额',
        //         dataIndex: 'refundAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '支付方式',
        //         dataIndex: 'payInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '正常发票数量',
        //         dataIndex: 'normalInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '正常发票金额',
        //         dataIndex: 'normalInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '作废发票数量',
        //         dataIndex: 'abortInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '作废发票金额',
        //         dataIndex: 'abortInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '红冲发票数量',
        //         dataIndex: 'strikeInvNum',
        //         width: 100,
        //         align: 'center'
        //     },
        //     {
        //         title: '红冲发票金额',
        //         dataIndex: 'strikeInvAmt',
        //         width: 100,
        //         align: 'center'
        //     },
        // ]
    }

    //初始化数据
    componentDidMount() {
        this.tableList("OPOutpatientPersonal", "OPOutpatientPersonal");
        this.handleQuery()

    }

    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }
    // 获取主列表columns
    tableList = (reactCode, compontName) => {
        var data = {
            params: [{
                "reactCode": [reactCode],
                "compontName": compontName,
                "type": "C"
            }]
        }
        console.log(1, data)
        $http.post('urlS', this, {
            code: '01040073',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    let resC = res.result.C
                    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
                        })
                    }
                    let arr = res.result && resC.length > 0 ? JSON.parse(JSON.stringify(resC)).map(item => {
                        return {
                            align: item.align,
                            widthNum: parseInt(item.width),
                            width: item.width,
                            dataIndex: item.dataIndex,
                            title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>,
                            display: item.display,
                            key: item.seqNo
                        }
                    }) : '';
                    let filterArr = arr.filter(function (item) { return item.display === 'Y' });
                    this.setState({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                    })
                }
            }
        })
    }

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

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

    // 条数改变的回调
    apponShowSizeChange = (current, size) => {
        this.setState({
            page: current,
            pageSize: size,
        }, () => {
            // 重新调用查询方法
            this.handleQuery();
        });
    }
    // //打印结账单  不用
    // print = () => {
    //     let { StartDate, EndDate } = this.state
    //     let hospID = JSON.parse(window.sessionStorage.userData).hospID
    //     let userID = JSON.parse(window.sessionStorage.userData).userID
    //     let data = []
    //     data = {
    //         params: [{
    //             "hospID": hospID,
    //             "userID": userID,
    //             "startDate": StartDate ? moment(StartDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
    //             "endDate": EndDate ? moment(EndDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
    //             "name":"FindOutpatientPersonalPrint.rpx"
    //         }]
    //     }
    //     $http.post('urls', this, {
    //         code: '05210053',
    //         data: data,
    //         success: function (res) {
    //             if (+res.errorCode === 0) {
    //                 window.open(res.result);
    //             }
    //         }
    //     })

    // }
    /**
     * 注释：
     * @ByGJG 选中打印
     * Create 2022-3-28
     */
    printData = () => {
        let { tableData, printDate, selectedRows } = this.state;
        var arr = []
        if (selectedRows.length == 0) {
            message.error("您没有选中需打印的数据！");
            return;
        }
        for (var i = 0; i < selectedRows.length; i++) {
            arr.push(selectedRows[i].ID)
            console.log(arr, "arr")
        }
        var strs = ""
        for (var i = 0; i < arr.length; i++) {
            var str = arr[i]
            console.log(str, "str")
            if (strs === "") {
                strs = str
            } else {
                strs = strs + "," + str
            }
            // var strs =strs+str+","
            console.log(strs, "字符")

        }
        let data = []
        data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "userID": JSON.parse(window.sessionStorage.userData).userID,
                "IDStr": strs,
                "startDate": this.state.StartDate || '',
                "endDate": this.state.EndDate || '',
                "type": "O",
            }]
        }
        $http.post('urls', this, {
            code: '05100406',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    $loopPrint('', res.result);
                }
            }
        })
    }
    //基础数据
    handleQuery = () => {
        let { page, pageSize, StartDate, EndDate } = this.state;
        let data = {}
        data = {
            params: [{
                "userID": JSON.parse(window.sessionStorage.userData).userID,
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "startDate": StartDate ? moment(StartDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
                "endDate": EndDate ? moment(EndDate).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD'),
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100137',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    let len = res.result.Data.length
                    var arr = []
                    console.log("res.result.Data", res.result.Data)
                    for (var i = 0; i < res.result.Data.length; i++) {
                        res.result.Data[i].key = i;
                        arr.push(i);
                    }

                    this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false, selectedRowKeys: arr, selectedRows: res.result.Data })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }
    // 时间
    onChangeTime = (date, dateString) => {
        this.setState({
            StartDate: dateString[0],    //开始日期
            EndDate: dateString[1],  //结束日期
        })
    }

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

    endChange(date) {
        this.setState({
            EndDate: date,
        })
    }
    // 撤销结账
    revokeFoot = () => {
        let data = {
            params: [{ type: 'U' }]
        }
        $http.post('urls', this, {
            code: '05100356',
            data: data,
            success: function (res) {
                if (+res.errorCode == 0) {
                    message.success("撤销结账成功！");
                    this.handleQuery()
                }
            }
        })
    }

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

    redireBack = (record) => {
        this.setState({ userInfo: record, visible: true, });
    }


    // 调用子组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }
    // 提供修改page和pageSize的回调函数
    compilePage(page, pageSize) {
        // 修改page，或者pageSize
        this.setState({ page: page, pageSize: pageSize }, () => {
            // 重新调用查询方法
            this.handleQuery();
        })
    }
    // 显示分页总条数
    showTotal(total) {
        return `共 ${total} 条`;
    }
    // 条数改变的回调
    onShowSizeChange = (current, size) => {
        this.compilePage(1, size);
    }
    // 页码改变的回调，参数是改变后的页码及每页条
    onChange = (page, pageSize) => {
        this.compilePage(page, pageSize);
    }
    render() {
        let { language, languageCode } = this.state
        const rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({ selectedRowKeys: selectedRowKeys, selectedRows: selectedRows })
            },
            selectedRowKeys: this.state.selectedRowKeys,
        };
        return (
            <div className="outpatient-body">
                <div style={{ padding: '16px 24px' }}>
                    {/* 选择日期: <RangePicker onChange={this.onChangeTime} 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)]} /> */}
                    <span style={{ display: 'inline-block', marginRight: '24px' }}>
                        <RangeDatePicker
                            label={(language.OPOutpatientPersonalselectDate && language.OPOutpatientPersonalselectDate.descripts) + '：'}
                            format='YYYY-MM-DD'
                            width={290}
                            startDate={this.state.StartDate}
                            endDate={this.state.EndDate}
                            startChange={this.startChange.bind(this)}
                            endChange={this.endChange.bind(this)}
                        />
                    </span>
                    <Button style={{ marginRight: '46px' }} type="primary" onClick={this.handleQuery}>{language.OPOutpatientPersonalquery && language.OPOutpatientPersonalquery.descripts}</Button>
                    <Button style={{ marginRight: '20px' }} type="primary" onClick={this.revokeFoot} >{'撤销上次结账'}</Button>
                    <Button onClick={() => this.printData()}>{language.OPOutpatientPersonalprint && language.OPOutpatientPersonalprint.descripts}</Button>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div className="table-body-height" style={{ padding: 24 }}>
                    <Table
                        style={{ height: store.getState().tableHeight.y + 81 + 'px' }}
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        className='TableA'
                        rowSelection={rowSelection}
                        pagination={false}
                        bordered
                        scroll={{ y: store.getState().tableHeight.y + 36 }}
                        loading={this.state.loading}
                        onRow={
                            record => {
                                return {
                                    onDoubleClick: event => {
                                        this.redireBack(record)
                                    }
                                }
                            }
                        }
                    />
                    <ColumnAuthoritysModel
                        clientWidth='900px'
                        compontName='OPOutpatientPersonal'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={() => { this.tableList("OPOutpatientPersonal", "OPOutpatientPersonal") }}
                    />
                    <CommonPagination
                        size="small"
                        current={this.state.page}
                        total={this.state.total}
                        search='search'
                        onShowSizeChange={this.onShowSizeChange.bind(this)}
                        complete={true}
                        dataSource={this.state.tableData}
                        onChange={this.onChange.bind(this)}
                    />
                    <Modal className="Monitor" title={languageCode === "CN" ? '收费明细' : 'Charge Detail'} visible={this.state.visible} onCancel={this.handleCancel} width='1200px' footer={[<Button key="back" onClick={this.handleCancel}>确认</Button>]}>
                        <InvRecordDeposit onRef={this.onRef} userInfo={this.state.userInfo} key={this.state.userInfo.ID} flag='modal' />
                    </Modal>
                </div>
            </div>
        )
    }
}