//病人账户查询
import React from 'react'
import { message, Col, Row, Input, Select, Button, Table, Modal, Card, notification } from 'antd'
import { ArraySome } from '../../tools/index';
import moment from 'moment';
import store from '../../store';
const { Option } = Select;
const { Search } = Input;
import { $http } from '../../containers/config/https'
import RangeDatePicker from 'components/rangePicker/index';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import ReadCard from '../../components/readcard/ReadCard';
import ICCardInformationModal from './../registercard/component/ICCardInformationModal'
import './style/index.less';

export default class FindDeposit extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            data: [],
            userInfo: {},
            visible: false,
            RefundPayWayArr: [],
            user: [],
            tableData: [],
            showLoading: true,
            total: 0,
            page: 1,
            pageSize: 10,
            patNo: '',
            patName: '',
            paywType: '',
            cardNo: '', // 卡号
            cardType: '',
            cardTypeData: [], // 卡类型
            userID: JSON.parse(window.sessionStorage.userData).userID,
            paywID: '',
            purPoseID: '',
            endDate: undefined,
            startDate: undefined,
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            accPurPoseArr: [],
            exportStatus: ''
        };
        this.textInput = React.createRef();
        this.columns = [
            {
                title: '交易时间',
                dataIndex: 'paywDate',
                width: 200,
                align: 'center',
                render: (text, record) => (
                    <span>
                        {record.paywDate}&nbsp;&nbsp;{record.paywTime}
                    </span>
                )
            },
            {
                title: '病人ID',
                dataIndex: 'patNo',
                width: 200,
                align: 'center'
            },
            {
                title: '证件号码',
                dataIndex: 'credNo',
                width: 200,
                align: 'center'
            },
            {
                title: '手机号码',
                dataIndex: 'mobile',
                width: 200,
                align: 'center'
            },
            {
                title: '姓名',
                dataIndex: 'name',
                width: 100,
                align: 'center'
            },
            {
                title: '性别',
                dataIndex: 'sexDesc',
                width: 100,
                align: 'center'
            },
            {
                title: '出生日期',
                dataIndex: 'birthDate',
                width: 100,
                align: 'center'
            },
            {
                title: '操作员',
                dataIndex: 'userDesc',
                width: 100,
                align: 'center'
            },
            {
                title: '交易方式',
                dataIndex: 'paywModeDesc',
                width: 100,
                align: 'center'
            },
            {
                title: '交易类型',
                dataIndex: 'paywmentTypeDesc',
                width: 100,
                align: 'center'
            },
            {
                title: '金额',
                dataIndex: 'paywAmt',
                width: 100,
                align: 'center'
            },
            {
                title: '当前账户余额',
                dataIndex: 'subBalance',
                width: 100,
                align: 'center'
            }
        ]
    }

    //初始化数据
    componentDidMount() {
        const sessionObj = sessionStorage.userData ? JSON.parse(sessionStorage.userData) : {};
        const ipconfigObj = React.$getSessionData('ipConfig');
        this.setState({ sessionObj, ipconfigObj });

        this.cardTypeList() //卡类型
        this.tableList();
        //列表数据
        this.handleQuery()
        //操作员下拉框
        this.getUserData()
        //支付方式下拉框
        this.getPayWayData()
        this.accPurPose()
    }

    componentWillUnmount() {
        // 组件销毁前将静止让setState修改state的状态
        this.setState = (state, callback) => { return; }
    }

    //操作员下拉框
    getUserData = () => {
        var data = {
            params: [{
                "hospID": JSON.parse(window.sessionStorage.userData).hospID, //医院id 
                "locTypeCode": "C"
            }]
        }
        $http.post("urlS", this, {
            code: '05210023',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.user) {
                    for (var i = 0; i < res.user.length; i++) {
                        this.state.user.push(<Option value={String(res.user[i].id)} key={i + "U"}>{res.user[i].descripts}</Option>)
                    }
                    this.setState({ user: this.state.user })
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试！" })
            }
        })
    }
    //支付方式下拉框
    getPayWayData = () => {
        $http.post("urlS", this, {
            code: '05100078',
            data: { params: [] },
            success: function (res) {
                if (+res.errorCode === 0 && res.RefundPayWayArr) {
                    for (var i = 0; i < res.RefundPayWayArr.length; i++) {
                        this.state.RefundPayWayArr.push(<Option value={String(res.RefundPayWayArr[i].ID)} key={i}>{res.RefundPayWayArr[i].Descripts}</Option>)
                    }
                    this.setState({ RefundPayWayArr: this.state.RefundPayWayArr })
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }

    //支付方式下拉框
    accPurPose = () => {
        $http.post("urlS", this, {
            code: '05100408',
            data: { params: [] },
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    let accPurPoseArr = []
                    for (var i = 0; i < res.result.length; i++) {
                        accPurPoseArr.push(<Option value={String(res.result[i].id)} key={i}>{res.result[i].descripts}</Option>)
                    }
                    this.setState({ accPurPoseArr: accPurPoseArr })
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }

    // 回车查询
    patNodownE = (e) => {
        if (e.keyCode === 13) {
            this.handleQuery()
        }
    }

    //列表数据
    handleQuery = () => {
        let { patNo, patName, paywType, userID, paywID, endDate, startDate, page, pageSize, purPoseID } = this.state;
        var data = {
            params: [{
                "patNo": patNo || '',
                "patName": patName || '',
                "paywType": paywType || '',
                "userID": userID || '',
                "paywID": paywID || '',
                "startDate": startDate || '',
                "endDate": endDate || '',
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "purPoseCode": purPoseID || ''
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100090',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.result) {
                    for (var i = 0; i < res.result.length; i++) {
                        res.result[i].key = i;
                    }
                    this.setState({ tableData: res.result.Data, total: res.result.TotalCount, loading: false })
                } else {
                    this.setState({ tableData: [], total: 0, loading: false })
                }
            }
        })
    }
    // 调用公共组件的连接事件
    onRef = (ref) => {
        this.child = ref
    }

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

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

    endChange(date) {
        this.setState({
            endDate: date,
        })
    }

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

    handleModal() {
        // 初始化数据
        this.setState({ visible: true, });
    }
    // 查询条件 --- 病人信息·
    patNo = (e) => {
        this.setState({ patNo: e.target.value });
    }
    // 查询条件 --- 姓名·
    patName = (e) => {
        this.setState({ patName: e.target.value });
    }
    // 查询条件 --- 交易类型·
    paywType = (e) => {
        this.setState({ paywType: e });
    }
    // 查询条件 --- 操作员·
    userID = (e) => {
        this.setState({ userID: e });
    }
    // 查询条件 --- 支付方式·
    paywID = (e) => {
        this.setState({ paywID: e });
    }
    purPose = (e) => {
        this.setState({ purPoseID: e });
    }
    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["FindDeposit"],
                "compontName": "FindDeposit",
                "type": "C"
            }]
        }
        $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]
        })
    }

    // 查询条件 --- 类型·
    cardType = (e) => {
        this.setState({ cardType: e });
    }

    // 查询条件 --- 卡号
    cardNo = (e) => {
        this.setState({ cardNo: e.target.value });
    }

    // 读卡 --- 根据卡号取病人信息
    handleReadCard = (value, event) => {
        if (event.keyCode) {
            this.searchUser('cardNo'); // 重新调用查询接口
            return false
        }
        this.readCard.PayByCard('', (json) => {
            if (json.errorCode === '0') {
                this.setState({ patNo: json && json.patInfo ? json.patInfo.patNo : '', cardNo: json.cardNo, personalData: json.value }, () => {
                    this.setState({ visible: true, userInfo: this.state.personalData });
                })
            } else {
                console.log(this.state.personalData)
            }

        })
    }

    // 读卡
    searchUser = (type) => {
        var data;
        let { cardType, cardNo, patNo, cardTypeData } = this.state
        if (!type) {   // 查询全部
            data = {
                params: [{
                    "number": patNo || '', // 登记号/身份证号
                    "cardTypeID": cardType,   //卡类型id
                    "cardNo": cardNo,    //卡号
                }]
            }
        }

        if (type === 'patNo') {
            data = {
                params: [{
                    "number": patNo || '', // 登记号/身份证号
                    "cardTypeID": "",   //卡类型id
                    "cardNo": "",    //卡号
                }]
            }

            if (patNo === '') {
                return false
            }
        }

        if (type === 'cardNo') {
            data = {
                params: [{
                    "number": '', // 登记号/身份证号
                    "cardTypeID": cardType || '',     //卡类型id
                    "cardNo": cardNo || '', //卡号
                }]
            }

            if (cardNo === '') {
                return false
            }
            if (cardType === '') {
                message.error('请选择卡类型')
                return false
            }


            let cardTypeFilter = cardTypeData.filter(function (item) {
                return item.id == cardType;
            })

            let zeroLength = cardTypeFilter[0].cardLength

            if (zeroLength && zeroLength != '' && parseFloat(zeroLength) != 0) {
                this.setState({
                    cardNo: ArraySome.addPreZero(cardNo, zeroLength)
                })
                data = {
                    params: [{
                        "number": '', // 登记号/身份证号
                        "cardTypeID": cardType || '',     //卡类型id
                        "cardNo": ArraySome.addPreZero(cardNo, zeroLength) || '', //卡号
                    }]
                }
            }
        }

        $http.post('urlS', this, {
            code: "03040004",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {

                    this.setState({
                        patNo: res.data.patNo || '',  // ID
                    });
                } else {
                    this.clearnFile()  // 清空 
                }
            }
        });
    }

    //清空
    clearnFile = () => {
        this.setState({
            cardNo: '',
            patNo: '',
        });
    }

    //卡类型
    cardTypeList = () => {
        var data = {
            params: [{
                cardTypeFlag: 1,
            }]
        }

        $http.post('urlS', this, {
            code: "03030005",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    let cardDeffault = res.cardType.filter((item) => {
                        return item.defaultFlag === 'Y';
                    })
                    this.setState({
                        cardType: cardDeffault[0].id, // 默认卡
                        cardTypeData: res.cardType,  // 用户数据
                    });
                }
            }
        });
    }

    //延时执行
    sleep = (millisecond) => {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve()
            }, millisecond)
        })
    };

    // 导出
    exportFun = async () => {
        //导出状态
        this.setState({
            exportStatus: true,
            loading: true
        });
        let { sessionObj, ipconfigObj } = this.state;
        let { patNo, patName, paywType, userID, paywID, endDate, startDate, page, pageSize, purPoseID } = this.state;
        let StartDate = new Date();

        let data = {
            params: [{
                queryParams: {
                    params: [{
                        "patNo": patNo || '',
                        "patName": patName || '',
                        "paywType": paywType || '',
                        "userID": userID || '',
                        "paywID": paywID || '',
                        "startDate": startDate || '',
                        "endDate": endDate || '',
                        "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                        "purPoseCode": purPoseID || ''
                    }],
                    pagination: [{
                        pageSize: pageSize,
                        currentPage: page,
                        sortColumn: 'code',
                        sortOrder: 'asc'
                    }],
                    code: '05100090',
                    session: [{
                        userID: sessionObj.userID,
                        locID: sessionObj.locID,
                        groupID: sessionObj.groupID,
                        hospID: sessionObj.hospID,
                        sessionID: sessionObj.sessionID,
                        hospCode: sessionObj.hospCode,
                        language: sessionObj.language,
                        hostName: ipconfigObj?.hostName || '',
                        ipv4: ipconfigObj?.ipv4 || '',
                        ipv6: ipconfigObj?.ipv6 || '',
                        mac: ipconfigObj?.mac || ''
                    }]
                },
                queryCode: '05100090',
                componentCode: 'FindDeposit'
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }],
            session: [{
                userID: sessionObj.userID,
                locID: sessionObj.locID,
                groupID: sessionObj.groupID,
                hospID: sessionObj.hospID,
                sessionID: sessionObj.sessionID,
                hospCode: sessionObj.hospCode,
                language: sessionObj.language,
                hostName: ipconfigObj?.hostName || '',
                ipv4: ipconfigObj?.ipv4 || '',
                ipv6: ipconfigObj?.ipv6 || '',
                mac: ipconfigObj?.mac || ''
            }]
        };
        await this.sleep(1000); //延时，按钮效果
        const resObj = await React.$asyncPost(this, "11020007", data);
        if (resObj) {
            let errorCode = resObj.errorCode;
            if (+errorCode === 0) {
                let downLoadUrl = resObj.result.downloadURL;
                //异步--消息提醒
                if (downLoadUrl === '') {
                    this.exportNotification(); //提示栏
                    store.dispatch({
                        type: 'downloadTask',
                        value: {
                            timeStamp: new Date().getTime(),
                            startDate: moment(new Date()).format('YYYY-MM-DD'),
                            endDate: moment(new Date()).format('YYYY-MM-DD'),
                        }
                    })
                } else { //同步-直接取到链接后下载
                    window.open(downLoadUrl, '_parent')
                }

                this.setState({
                    exportStatus: false,
                    loading: false
                });
            } else {
                this.setState({
                    exportStatus: false,
                    loading: false
                });
                message.error(resObj.errorMessage)
            }
        }
    };

    //右上角提示栏
    exportNotification = () => {
        const msgValue = (<p>数据正在导出，导出完成后可在右上角<span style={{ color: 'red' }}>↗</span><span style={{ fontWeight: 'bold' }}>【导出任务列表】</span>中下载</p>);
        notification.info({
            message: '导出中..',
            description: msgValue,
            placement: 'topRight',
            style: {
                top: 30,
            },
        });
    };

    render() {
        let { language } = this.state
        return (
            <div style={{ width: '100%', height: '100%', background: '#F5F7FE' }} className='hosptial-adm-body'>
                <Card bodyStyle={{ padding: 10 }} style={{ width: '20%', float: 'left', height: store.getState().tableHeight.y + 236 }}>
                    <ReadCard ref={r => this.readCard = r} />
                    <Col span={25} className='common-col-ul'>
                        <Select allowClear style={{ width: '100px', margin: '0 15px 0 0' }} placeholder="请选择" value={this.state.cardType}
                            onChange={(event) => { this.cardType(event) }}  >
                            <Option value=''>请选择</Option>
                            {this.state.cardTypeData.map(item => <Option title={item.descripts + '^' + item.descriptsSPCode} key={item.id} value={item.id}  >{item.descripts}</Option>)}
                        </Select>
                        <Search maxLength={50} ref={(input) => { this.cardNoInput = input; }} className='search' style={{ width: '235px' }}
                            allowClear placeholder="请输入卡号" disabled={this.state.disabledInput} value={this.state.cardNo} enterButton="读卡"
                            onChange={(event) => { this.cardNo(event) }} onSearch={this.handleReadCard} />
                    </Col>

                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <span className='common-span-ui'> {language.FindDepositpatientinformation && language.FindDepositpatientinformation.descripts}：</span>
                        <Input placeholder={language.FindDepositpatientinformation && language.FindDepositpatientinformation.message} value={this.state.patNo}
                            onChange={(event) => { this.patNo(event) }} onKeyUp={(e) => { this.patNodownE(e) }} style={{ width: '80%' }} />
                    </Col>

                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <span className='common-span-ui'>{language.FindDepositpaymentmethod && language.FindDepositpaymentmethod.descripts}：</span>
                        <Select style={{ width: '80%' }} allowClear placeholder="请选择支付方式" value={this.state.paywID} className='common-right-ui'
                            onChange={(event) => { this.paywID(event) }}>
                            {this.state.RefundPayWayArr}
                        </Select>
                    </Col>
                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <span className='common-span-ui'>{language.FindDepositpurPose && language.FindDepositpurPose.descripts}：</span>
                        <Select style={{ width: '80%' }} allowClear placeholder="请选择用途" value={this.state.purPoseID} className='common-right-ui'
                            onChange={(event) => { this.purPose(event) }}>
                            {this.state.accPurPoseArr}
                        </Select>
                    </Col>
                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <span className='common-span-ui'>{language.FindDeposittransactiontype && language.FindDeposittransactiontype.descripts}：</span>
                        <Select style={{ width: '80%' }} placeholder="请选择交易类型" value={this.state.paywType} className='common-right-ui'
                            onChange={(event) => { this.paywType(event) }}>
                            <Option value='P'>充值</Option>
                            <Option value='R'>退款</Option>
                            <Option value='A'>消费</Option>
                            <Option value=''>全部</Option>
                        </Select>
                    </Col>

                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <span className='common-span-ui'>{language.FindDepositoperator && language.FindDepositoperator.descripts}：</span>
                        <Select style={{ width: '80%' }} allowClear placeholder="请选择操作员" className='common-right-ui'
                            value={this.state.userID} onChange={(event) => { this.userID(event) }}>
                            {this.state.user}
                        </Select>
                    </Col>

                    <Col span={25} className='common-col-ul' style={{ marginTop: 10 }}>
                        <div style={{ width: '34%' }} className='common-span-ui'>{'操作日期：'}</div>
                        <RangeDatePicker format='YYYY-MM-DD' startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                    </Col>

                    {/**sdas */}
                    <Col span={25} style={{ marginTop: 10 }}>
                        <Button type='primary' style={{ width: '100%' }} onClick={() => { this.setState({ page: 1, pageSize: 10 }, () => { this.handleQuery() }) }}>
                            {language.FindDepositInquire && language.FindDepositInquire.descripts}</Button>
                    </Col>
                </Card>

                <Card className="table-body-height" bodyStyle={{ padding: 10 }} style={{ width: '79.5%', float: 'right' }}>
                    <Col span={25} style={{ marginBottom: 10 }}>
                        <Button type='primary' style={{ width: '100px' }} onClick={() => { this.exportFun() }}>
                            {language.FindDepositExport && language.FindDepositExport.descripts}</Button>
                    </Col>
                    <Table
                        style={{ height: store.getState().tableHeight.y + 140 }}
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        className='TableA'
                        //rowClassName="editable-row"
                        pagination={false}
                        scroll={{ x: 900, y: store.getState().tableHeight.y + 90 }}
                        bordered
                        loading={this.state.loading}
                    />
                    <CommonPagination size="small" current={this.state.page} total={this.state.total} search='search'
                        onShowSizeChange={this.apponShowSizeChange} complete={true} dataSource={this.state.tableData}
                        onChange={this.appPageChange} />
                    <ColumnAuthoritysModel
                        clientWidth='900px'
                        compontName='FindDeposit'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.tableList}
                    />
                </Card>
                <Modal
                    visible={this.state.visible}
                    okText="确定"
                    onOk={this.handleCancel}
                    onCancel={this.handleCancel}
                    cancelText="确认"
                    width='1200px'
                    style={{ maxHeight: '800px', overflow: 'auto', padding: 0 }}
                    title="IC卡信息"
                >
                    <ICCardInformationModal onRef={this.onRef} userInfo={this.state.userInfo} />
                </Modal>
            </div>
        )
    }
}