// 住院费用清单
import React from 'react';
import { Select, Row, Col, Button, Table, Modal, Card, Switch, message } from 'antd';
import { $loopPrint } from '../../lodop/Common/Print';
import { $http } from 'containers/config/https';
import { Util } from 'tools/index';
import store from 'store';
import TipHeader from './component/TipHeader'
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import PubilcTablePagination from "../../common/PubilcTablePagination";
import './style/style.less'

// 组件const
const { Option } = Select;

export default class ListOfHospitalizationExpenses extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            userInfo: {}, // 用户数据
            dataTableTop: [], // table数据 上列表table
            dataTable1: [], // table数据 主列表table
            dataTable2: [], // table数据 折扣记账系数配置列表
            dataTable3: [], // table数据 不属于折扣内明细
            selectListData1: [],
            selectListData2: [],
            selectListData3: [],
            totalTop: 0,
            pageTop: 1,
            pageSizeTop: 200,
            StartDateTop: undefined,  // //开始日期
            EndDateTop: undefined,  // //结束日期
            StartDate1: undefined,  // //开始日期
            EndDate1: undefined,  // //结束日期
            cardType: '', // 卡类型
            cardTypeData: [], // 卡类型
            cardNo: '', // 卡号
            patNo: '',
            select1: '',
            select2: '',
            select3: '',
            nameNo: '',
            execID: [],
            ordID: '',
            modalShow: false,
            columnsTop: [],
            columns1: [],
            selectedRowKeys: [],
            money: {},
            bqType: '',
            jsType: '',
            bqData: [],
            jsTypeData: [],
            time1: '1',
            allMoney: 0,
            accSubStatus: {}, //账户状态
            userPayData: {}, //账户状态
            patBillID: '',
            mark: '0',
            listArr: [],
            selectType: [],
            selectData: [],
            selectedRows: [],
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            ColumnAuthority: '',
            loading: false,
            propsAdmID: "",
            span: {},
            orderSpan: {},
            detailVisible: false,
            page: 1,
            pageSize: 20,
            total: 0,
            modifyFormData: [],
            modalRowData: {}
        }
        this.columns1 = [{ title: '项目名称*规格', dataIndex: 'descripts', align: "center", width: 100, key: '1' },
        { title: '住院费用类型', dataIndex: 'icDesc', align: "center", width: 200, key: '2' },
        { title: '单价', dataIndex: 'unitPrice', align: "center", width: 100, key: '3' },
        { title: '数量', dataIndex: 'qty', align: "center", width: 100, key: '4' },
        { title: '总金额', dataIndex: 'patAmt', align: "center", width: 100, key: '5' },
        { title: '单位', dataIndex: 'unitDesc', align: "center", width: 100, key: '6' },
        { title: '自费比例', dataIndex: 'payDateTime', align: "center", width: 100, key: '7' },
        { title: '自费金额', dataIndex: 'payDateTime', align: "center", width: 100, key: '8' },
        { title: '计费科室', dataIndex: 'recLocID', align: "center", width: 100, key: '9' },
        { title: '操作员', dataIndex: 'createUserDesc', align: "center", width: 100, key: '10' },
        { title: '计费时间', dataIndex: 'billDate', align: "center", width: 100, key: '11' },
        ]
    }

    componentDidMount() {
        this.setState({
            userInfo: this.props.userInfo || {},
            patBillID: this.props.patBillID || ''
        }, () => {
            this.state.patBillID && this.tableData()
            this.selectData()
        })
        this.ordList1() //国际化
    }

    static getDerivedStateFromProps(nextProps, prevState) {
        //该方法内禁止访问this
        if (nextProps.admID !== prevState.propsAdmID) {
            //通过对比nextProps和prevState，返回一个用于更新状态的对象
            return {
                propsAdmID: nextProps.admID
            }
        }
        return null
    }

    componentDidUpdate(prevProps, prevState) {
        // console.log(prevProps, prevState)
        if (prevProps.admID !== this.state.propsAdmID) {
            this.setState({ propsAdmID: prevProps.admID }, () => {
                this.tableData();
                this.selectData()
            })
        }
    }

    // 费用类型table
    ordList1 = () => {
        let data = {
            params: [{
                "reactCode": ["ListOfHospitalizationExpenses"],
                "compontName": "ListOfHospitalizationExpenses",
                "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
                    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 => {
                        if (item.dataIndex == 'icDesc') {
                            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,
                                render: (value, data, index) => {
                                    if (index === 0) {
                                        this.state.span = {};
                                    }
                                    const obj = {
                                        children: value,
                                        props: {}
                                    }
                                    if (Util.isEmpty(this.state.span[data.icID])) {
                                        obj.props.rowSpan = this.state.orderSpan[data.icID];
                                        this.state.span[data.icID] = 1;
                                    } else {
                                        obj.props.rowSpan = 0;
                                    }
                                    return obj;
                                },
                            }
                        } else {
                            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({
                        columns1: filterArr, // 费用类型table
                        languageData: res.result.language || {},  // 国际化语言包
                        modifyFormData: res?.result?.formData || []
                    }, () => {
                        // this.columns1(this.state.columns1)
                        this.LanCNEN(this.state.languageCode)
                    })
                }
            }
        });
    }

    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

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

    tableData = () => {
        this.setState({ loading: true });
        let data = {
            params: [this.state.selectType || ''],
            patBillID: this.state.patBillID || '',
            mark: this.state.mark || '',
            admID: this.state.propsAdmID ? this.state.propsAdmID : "",
            pagination: [{
                pageSize: this.state.pageSizeTop,
                currentPage: this.state.pageTop,
            }]
        }
        $http.post('urlS', this, {
            code: "05100239",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let orderSpan = {};
                    let resC = res.result.dataArr
                    for (var i = 0; i < resC.length; i++) {
                        resC[i].key = i;
                    }

                    resC && resC.map(item => {
                        orderSpan[item.icID] = Util.isEmpty(orderSpan[item.icID]) ? 1 : orderSpan[item.icID] + 1;
                    })
                    this.setState({
                        loading: false,
                        dataTable1: resC, // 列表数据
                        orderSpan: orderSpan,
                        patBillAmtAll: res.result.patBillAmtAll, // 账单总金额
                        patAmtAll: res.result.patAmtAll, // 当前总金额
                        totalTop: res.result.totalCount,
                    });
                } else {
                    this.setState({
                        loading: false,
                        dataTable1: [], // 列表数据
                        patBillAmtAll: '', // 账单总金额
                        patAmtAll: '', // 当前总金额
                        totalTop: 0,
                    })
                }
            },
            error: function () {
                this.setState({ loading: true });
            }
        });
    }

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

    onChangeTop = (page, pageSize) => {
        this.setState({ pageTop: page, pageSizeTop: pageSize }, () => {
            // 重新调用查询方法
            this.tableData();
        })
    }

    // 条数改变的回调
    onShowSizeChangeTop = (current, size) => {
        this.setState({ pageTop: 1, pageSizeTop: size }, () => {
            // 重新调用查询方法
            this.tableData();
        })

    }

    onChangeSwitch = (checked) => {
        if (checked) {
            this.setState({ mark: '0' }, () => {
                this.tableData();
            })
        } else {
            this.setState({ mark: '1' }, () => {
                this.tableData();
            })
        }

    }

    selectType = (e) => {
        this.setState({
            selectType: e, //账户状态
        }, () => {
            this.tableData();
        });
    }

    selectData = () => {
        var data = {
            params: [{
                "patBillID": this.state.patBillID || '',
                "admID": this.state.propsAdmID ? this.state.propsAdmID : "",
            }],
        }
        $http.post('urlS', this, {
            code: "05100248",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {

                    this.setState({
                        selectData: res.result || [], //账户状态
                    });
                }
            }
        });
    }

    //打印清单
    PrintXYPrescButtom = () => {
        let { userInfo } = this.state
        // if (selectType == "") {
        //     window.open("http://172.18.100.87:18080/demo/reportJsp/showReport.jsp?rpx=HospOfListing.rpx&patBillID=" + (this.state.patBillID || '') + "&mark=" + (this.state.mark || 0) + "&patNo=" + (userInfo.patNo || '') + "&name=" + (userInfo.patName || '') + "&sex=" + (userInfo.patSexDesc || ''))
        // } else {
        //     message.error('请打印全部')
        // }
        let data = {}
        data = {
            params: [{
                "patBillID": this.state.patBillID || '',
                "mark": this.state.mark || 0,
                "patNo": userInfo.patNo || '',
                "name": userInfo.name || '',
                "sex": userInfo.patSexDesc || '',
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "user": JSON.parse(window.sessionStorage.userData).userID,
                "admID": this.state.propsAdmID ? this.state.propsAdmID : "",
            }]
        }
        $http.post('urls', this, {
            code: '05100370',
            data: data,
            success: function (res) {
                $loopPrint('', res.result);
            }
        })
    }

    //打印清单
    exportButtom = () => {
        let { userInfo } = this.state
        // if (selectType == "") {
        //     window.open("http://172.18.100.87:18080/demo/reportJsp/showReport.jsp?rpx=HospOfListing.rpx&patBillID=" + (this.state.patBillID || '') + "&mark=" + (this.state.mark || 0) + "&patNo=" + (userInfo.patNo || '') + "&name=" + (userInfo.patName || '') + "&sex=" + (userInfo.patSexDesc || ''))
        // } else {
        //     message.error('请打印全部')
        // }
        let data = {}
        data = {
            params: [{
                "patBillID": this.state.patBillID || '',
                "mark": this.state.mark || 0,
                "patNo": userInfo.patNo || '',
                "name": userInfo.name || '',
                "sex": userInfo.patSexDesc || '',
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "user": JSON.parse(window.sessionStorage.userData).userID,
                "admID": this.state.propsAdmID ? this.state.propsAdmID : "",
            }]
        }
        $http.post('urls', this, {
            code: '05100346',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    window.open(res.result);
                }
            }
        })
    }

    //数据导 出
    // DataoutputPresc = () => {
    //     let { userInfo, mark, selectType } = this.state
    //     window.open("http://172.18.100.87:18080/demo/reportJsp/showReport.jsp?rpx=HospOfListing.rpx&&patBillID=" + (this.state.patBillID || '') + "&mark=" + (this.state.mark || 0) + "&patNo=" + (userInfo.patNo || '') + "&name=" + (userInfo.patName || '') + "&sex=" + (userInfo.patSexDesc || ''))
    // }

    selectRowKeys(selectedRowKeys, selectedRows) {
        this.setState({
            selectedRowKeys: selectedRowKeys,
            selectedRows: selectedRows
        })
    }

    // 双击行
    handleQuantityDetail = record => {
        if (record?.detailFlag === 'Y') {
            this.setState({ modalRowData: record }, () => {
                this.modalRef && this.modalRef.modifyVisible(true);
            })
        } else {
            this.setState({ detailVisible: true, chargeItem: record.chargeItem }, () => {
                this.getTableColumns()
                this.handleQuery()
            })
        }
    }

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

    // 获取列表columns
    getTableColumns = async () => {
        try {
            let data = {
                params: [{
                    compontName: "IPOrderItemExecDetails",
                    type: 'C',
                }]
            }
            let res = await React.$asyncPost(this, '01040073', data);
            let filterColumn = res.result && 'C' in res.result && Array.isArray(res.result.C) ? JSON.parse(JSON.stringify(res.result.C)).filter(function (item) { return item.display !== 'N' }) : [];

            this.setState({
                columns: filterColumn,
                totalWidth: parseInt(res.totalWidth)
            })
        } catch (error) {
            console.log(error)
        }
    }

    // 查询住院费用清单项目执行明细
    handleQuery = () => {
        let data = {
            params: [{
                chargeItem: this.state.chargeItem,
                admID: this.state.propsAdmID
            }],
            pagination: [{
                pageSize: this.state.pageSize,
                currentPage: this.state.page,
                sortColumn: 'Date',
                sortOrder: 'desc'
            }]
        };
        $http.post('urlS', this, {
            code: '05100245',
            data: data,
            success: (res) => {
                if (res.errorCode === "0") {
                    this.setState({
                        total: res.result.total,
                        tableData: res.result.rows,
                    });
                } else {
                    this.setState({
                        total: 0,
                        tableData: []
                    });
                }

            }
        });
    }

    // 修改明细信息
    handleModalSave = async values => {
        try {
            let { modalRowData } = this.state;
            let data = {
                params: [{
                    ...values,
                    id: modalRowData?.chargeItem || modalRowData?.id || ''
                }]
            }
            let res = await React.$asyncPost(this, '05210095', data);
            message.success(res.errorMessage ? res.errorMessage : '保存成功');
            this.modalRef && this.modalRef.modifyVisible(false, 'Y');
            this.setState({ modalRowData: {} }, () => {
                this.tableData();
            });
        } catch (error) {
            console.log(error)
        }
    }

    render() {
        const { loading, modifyFormData, modalRowData } = this.state;
        const title = `费用清单 （账单金额：￥${this.state.patBillAmtAll || '0'})`;
        let isPersonalInformation = this.props.isPersonalInformation ? this.props.isPersonalInformation : "true";
        let tabsHeight = store.getState().tableHeight.y + 50;
        // 组件所需参数
        const param = {
            // 表头配置
            columns: this.state.columns,
            // 表格数据
            data: this.state.tableData,
            // 数据总条数
            total: this.state.total,
            // 数据页数
            page: this.state.page,
            y: tabsHeight * 0.7,
            // 表格的宽度
            width: this.state.totalWidth,
            height: tabsHeight * 0.78,
            pageSize: this.state.pageSize,
            componentName: "IPOrderItemExecDetails"
        }
        return (
            <div>
                <div>
                    <Modal
                        key="quantityDetail"
                        width="61vw"
                        title="数量明细"
                        footer={null}
                        visible={this.state.detailVisible}
                        onCancel={() => this.setState({ detailVisible: false })}
                        className="opl-doctor-advice"
                        bodyStyle={{ height: tabsHeight * 0.9 }}
                        destroyOnClose
                    >
                        <PubilcTablePagination
                            param={param}
                            compilePage={this.compilePage}
                            getColumns={this.getTableColumns}
                        />
                    </Modal>
                </div>
                <div style={{ display: isPersonalInformation === "false" ? "none" : "block" }}>
                    <TipHeader userInfo={this.state.userInfo} key={this.state.userInfo.patID + this.state.userInfo.accTSubID} />
                </div>
                <Row>
                    <Col span={24}>
                        <Card style={{ width: '100%', padding: '0' }} className='pd0' title={title}  >
                            <div>
                                <Row>
                                    <Col span={24}>
                                        <Row style={{ minHeight: '50px', padding: '0 24px 10px 24px' }}>
                                            <Col span={24}>
                                                住院费用类型: <Select showSearch optionFilterProp="seachprop" allowClear style={{ width: '260px', margin: '12px 15px 0 0' }} placeholder="请选择" value={this.state.selectType} onChange={(event) => { this.selectType(event) }} >
                                                    {this.state.selectData.map(item => <Option seachprop={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                                                </Select>
                                                按项目汇总显示: <Switch style={{ margin: '0 15px' }} defaultChecked onChange={(e) => this.onChangeSwitch(e)} />
                                                <Button onClick={() => this.tableData()} style={{ margin: '12px 15px 0 0', background: 'rgba(255,255,255,1)' }}>查询</Button>
                                                <Button onClick={() => this.PrintXYPrescButtom()} style={{ margin: '12px 15px 0 0', background: 'rgba(255,255,255,1)' }}>打印</Button>
                                                <Button onClick={() => this.exportButtom()} style={{ margin: '12px 15px 0 0', background: 'rgba(255,255,255,1)' }}>导出</Button>
                                                <span>当前总金额：￥{this.state.patAmtAll || '0'}</span>
                                            </Col>
                                        </Row>
                                    </Col>
                                    <Col span={24}>
                                        <Table
                                            pagination={false}
                                            bordered
                                            loading={loading}
                                            scroll={{ y: store.getState().tableHeight.y - 110, x: 1100 }}
                                            columns={this.state.columns1}
                                            dataSource={this.state.dataTable1}
                                            className="table-body-height"
                                            onRow={(record) => {
                                                return {
                                                    onDoubleClick: () => {
                                                        this.handleQuantityDetail(record)
                                                    },
                                                };
                                            }}
                                        />
                                        <ColumnAuthoritysModel
                                            clientWidth='900px'
                                            compontName='ListOfHospitalizationExpenses'
                                            configType="C"
                                            onRef={this.onColumnRef}
                                            reloadData={() => {
                                                this.ordList1()
                                            }}
                                        />
                                        <CommonPagination
                                            loading={loading}
                                            size="large"
                                            current={this.state.pageTop}
                                            total={this.state.totalTop}
                                            search='search'
                                            pageSize='200'
                                            onShowSizeChange={this.onShowSizeChangeTop.bind(this)} complete={true} dataSource={this.state.dataTable1}
                                            onChange={this.onChangeTop.bind(this)} />
                                    </Col>
                                </Row>
                            </div >
                        </Card>
                    </Col>
                </Row>
                {/* 修改明细数据 */}
                <PublicModalFormHooks
                    width="500px"
                    idField="chargeItem"
                    title="明细信息修改"
                    onRef={ref => this.modalRef = ref}
                    formData={modifyFormData}
                    rowData={modalRowData}
                    handleSave={this.handleModalSave}
                />
            </div>
        )
    }
};