import React from 'react';
import { Table, Input, Popconfirm, Icon, message, Form, Divider, Select, Row, Col, Button } from 'antd';
import { $http } from '../../containers/config/https';
import moment from 'moment';
import store from '../../store';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { ArraySome } from '../../tools/index';
import ReadCard from '../../components/readcard/ReadCard';
import RangeDatePicker from 'components/rangePicker/index';
import './charges/style/style.less';

const { Option } = Select;
const { Search } = Input;
const dateFormat = 'YYYY-MM-DD'; //定义全局日期格式


class VATInvoice extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false, //加载状态标志
            visible: false, //弹窗显示状态标志
            tableData: [], // 表格数据
            total: 0,  // 表格数据总条数
            page: 1, //当前页数
            pageSize: 10, //每页显示条数

            endDate: undefined,
            startDate: undefined,
            userID: undefined,  //操作员
            patNo: '', //病人信息
            paywID: undefined, //查询条件 --- 支付方式
            cardNo: '', // 查询条件 --- 卡号
            cardType: '', //查询条件 --- 卡类型
            invoiceNumber: '', //查询条件 --- 发票号
            ifInvoice: undefined, //查询条件 --- 是否开票
            admReason: undefined, //查询条件 --- 结算类型
            cardTypeData: [], //卡类型数据
            RefundPayWayArr: [], //结算类型数据
            user: [], //操作员数据
            RefundPayWayArr: [], //支付方式数据

            columns: [],
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
            intId: '', // intIdID
            VATValue: '',
        };

    }

    componentDidMount() {
        this.tableList();
        //初始化列表数据
        this.handleQuery();
        //支付方式下拉框
        this.getPayWayData();
        //操作员下拉框
        this.getUserData();
        //卡类型
        this.cardTypeList()
        //结算类型
        this.getAdmReasonData()
    }

    //render 自定义项目名称
    listAdd = (i, j, languageCode) => {
        let { columns } = this.state
        columns.splice(i, j,
            {
                title: languageCode === 'CN' ? "操作" : 'Operation',
                key: 'op',
                align: "center",
                render: (text, record) => (
                    <span>
                        <span className='span' onClick={() => this.save(record)}><Icon type="edit" />{languageCode === 'CN' ? "保存" : 'Save'}</span>
                    </span>
                ),
            },
        )
    }
    onColumnRef = (ref) => {
        console.log(ref)
        this.columnRef = ref;
    }
    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["VATInvoice"],
                "compontName": "VATInvoice",
                "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 => {
                        if (item.dataIndex === "VATNo") {
                            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: (text, record) => (
                                    <div onClick={() => this.intId(record)} onBlur={() => this.intId(record)}>
                                        <Input className={this.state.intId === record.key ? '' : 'inputInvoiceInfomation'} disabled={this.state.intId === record.key ? false : true} style={{ background: '#fff', cursor: 'pointer' }} value={record.VATNo} onChange={(event) => this.VATNoChange(event, record)} />
                                    </div>
                                ),
                            }
                        } 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({
                        columns: filterArr,
                        languageTable1: res.result.B || {},  // 国际化Table1
                        languageTable2: res.result.C || {},  // 国际化Table2
                        languageData: res.result.language || {},  // 国际化语言包
                    }, () => {
                        this.LanCNEN(this.state.languageCode)
                        this.listAdd(filterArr.length + 1, 0, languageCode);
                    })
                }
            }
        })
    }

    intId = (record) => {
        if (!record) {
            return
        }
        this.setState({
            intId: record.key
        })

    }

    //发票信息变化
    VATNoChange = (e, record) => {
        let val = e.target.value
        let key = record.key
        let { tableData } = this.state
        tableData.map((item, i) => {
            if (item.key === key) {
                item.VATNo = val
            }
        })
        this.setState({
            VATValue: val,
            tableData: tableData
        })


    }

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

    //初始化列表数据
    handleQuery = () => {
        let { patNo, userID, paywID, endDate, startDate, page, pageSize, admReason, invoiceNumber, ifInvoice } = this.state;
        var data = {
            params: [{
                "number": patNo || '',
                "userID": userID || '',
                "paywID": paywID || '',
                "admReason": admReason || '',
                "ifInvoice": ifInvoice || '',
                "invNo": invoiceNumber || '',
                "startDate": startDate || '',
                "stopDate": endDate || '',
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100270',
            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 })
                }
            }
        })
    }

    //保存信息
    save = (record) => {
        var data = {
            params: [{
                "invID": record.invID || '',
                "patID": record.patNo || '',
                "invAmount": record.invAmount || '',
                "footFlag": record.footFlag || '',
                "invPatAmount": record.invPatAmount || '',
                "invDiscAmount": record.invDiscAmount || '',
                "invShareAmount": record.invShareAmount || '',
                "invInsuranceAmount": record.insuranceAmount || '',
                "invType": 'V',
                "userID": JSON.parse(window.sessionStorage.userData).userID || '',
                "hospID": JSON.parse(window.sessionStorage.userData).hospID,
                "invNo": record.VATNo || '',
                "invStatusID": record.invStatusID || '',
            }],
        }
        $http.post('urls', this, {
            code: '05100271',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success(res.errorMessage);
                    this.handleQuery();
                }
            }
        })
    }

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

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

    //操作员下拉框
    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: "数据加载失败，请重试!" });
            }
        });
    }

    //结算类型
    getAdmReasonData = () => {
        // var data = {
        //     params: [{
        //         hospID: JSON.parse(window.sessionStorage.userData).hospID, //医院id 
        //     }]
        // }
        // $http.post("urlS", this, {
        //     code: '05100129',
        //     data: data,
        //     success: function (res) {
        //         if (+res.errorCode === 0 && res.data) {
        //             for (var i = 0; i < res.data.length; i++) {
        //                 this.state.AdmReasonArr.push(<Option value={String(res.data[i].id)} key={i + "A"}>{res.data[i].descripts}</Option>)
        //             }
        //             this.setState({ AdmReasonArr: this.state.AdmReasonArr })
        //         }
        //     },
        //     error: function (err) {
        //         this.setState({ errMsg: this.state.languageCode === "CN" ? "数据加载失败，请重试！" : 'Data loading failed, please try again' })
        //     }
        // })

        var data = {
            params: [{
                hospID: JSON.parse(window.sessionStorage.userData).hospID, //医院id 
            }]
        }
        let admReaConDr = []
        $http.post("urlS", this, {
            code: '05100246',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0 && res.AdmReaConArr) {
                    for (var i = 0; i < res.AdmReaConArr.length; i++) {
                        admReaConDr.push(<Option key={res.AdmReaConArr[i].ID} value={String(res.AdmReaConArr[i].ID)} >{res.AdmReaConArr[i].AdmReaCon}</Option>)
                    }
                    this.setState({ AdmReasonArr: admReaConDr })
                }
            },
            error: function (err) {
                this.setState({ errMsg: this.state.languageCode === "CN" ? "数据加载失败，请重试！" : 'Data loading failed, please try again' })
            }
        })
    }

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

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

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

    // 读卡 --- 根据卡号取病人信息
    handleReadCard = (value, event) => {
        if (event.keyCode) {
            this.searchUser('cardNo'); // 重新调用查询接口
            return false
        }
        let { cardType } = this.state;
        this.readCard.ReadCard(cardType, "R", (json) => {
            let patNo = json && json.patInfo ? json.patInfo.patNo : ''
            this.setState({ patNo , cardNo: json.cardNo }, () => {

                //this.searchUser('cardNo'); // 重新调用查询接口
                if (patNo)
                {
                    this.searchUser('patNo'); // 重新调用查询接口
                }else{
                    this.searchUser('cardNo'); // 重新调用查询接口
                }
            })
        })
    }

    // 读卡
    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
                    }, () => {
                        this.handleQuery() // 信息
                    });

                } 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,  // 用户数据
                    });
                }
            }
        });
    }

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

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

    // 查询条件 --- 操作员·
    userID = (e) => {
        this.setState({ userID: e });
    }
    // 查询条件 --- 支付方式·
    paywID = (e) => {
        this.setState({ paywID: e });
    }

    // 查询条件 --- 病人信息·
    patNo = (e) => {
        this.setState({ patNo: e.target.value });
    }

    // 查询条件 --- 发票号·
    invoiceChange = (e) => {
        this.setState({ invoiceNumber: e.target.value });
    }

    // 查询条件 --- 是否开票·
    ifInvoice = (e) => {
        this.setState({ ifInvoice: e });
    }

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

    render() {
        let { language, languageCode } = this.state;
        return (
            <div>
                <ReadCard ref={r => this.readCard = r} />
                <div style={{ width: '100%', height: '100%' }}>
                    <Row style={{ minHeight: '80px', padding: '24px 24px 24px 24px' }}>
                        <Col span={3}>
                            卡类型：
                            <Select allowClear style={{ width: '120px', margin: '12px 0px 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>
                        </Col>
                        <Col span={4}>
                            <Search maxLength={50} ref={(input) => { this.cardNoInput = input; }} className='search' style={{ width: '95%', margin: '12px 0px 0 0' }} allowClear placeholder="请输入卡号" disabled={this.state.disabledInput} value={this.state.cardNo} enterButton="读卡" onChange={(event) => { this.cardNo(event) }} onSearch={this.handleReadCard} /> {/* onKeyUp={(e) => { this.handleReadCarddownE(e, 'cardNo'); }}*/}
                        </Col>
                        <Col span={5}>
                            人员标识：<Input placeholder="病人ID/身份证号码" style={{ width: '245px', margin: '12px 0px 0 0' }} value={this.state.patNo} onChange={(event) => { this.patNo(event) }} onKeyUp={(e) => { this.patNodownE(e) }} />
                        </Col>
                        <Col span={4}>
                            支付方式：<Select style={{ width: '175px', margin: '12px 0px 0 0' }} allowClear placeholder="请选择支付方式" value={this.state.paywID} onChange={(event) => { this.paywID(event) }}>
                                {this.state.RefundPayWayArr}
                            </Select>
                        </Col>
                        <Col span={3}>
                            操作员：<Select style={{ width: '130px', margin: '12px 0px 0 0' }} allowClear placeholder="请选择操作员" value={this.state.userID} onChange={(event) => { this.userID(event) }}>
                                {this.state.user}
                            </Select>
                        </Col>
                        <Col span={5}>
                            <div style={{ margin: '12px 0px 0px 0px' }}>
                                <RangeDatePicker label='收费日期：' format='YYYY-MM-DD' width={260} startChange={this.startChange.bind(this)} endChange={this.endChange.bind(this)} />
                            </div>
                        </Col>
                        <Col span={4}>
                            结算类型：<Select style={{ width: '175px', margin: '12px 0px 0 0' }} allowClear placeholder="请选择结算类型" value={this.state.admReason} onChange={(event) => { this.admReason(event) }}>
                                {this.state.AdmReasonArr}
                            </Select>
                        </Col>
                        <Col span={4}>
                            是否开票：<Select style={{ width: '175px', margin: '12px 0px 0 0' }} allowClear placeholder="请选择方式" value={this.state.ifInvoice} onChange={(event) => { this.ifInvoice(event) }}>
                                <Option value='1'>开票</Option>
                                <Option value='2'>未开票</Option>
                                <Option value='3'>全部</Option>
                            </Select>
                        </Col>
                        <Col span={5}>
                            发票号：<Input placeholder="请输入发票号" style={{ width: '220px', margin: '12px 15px 0 0' }} value={this.state.invoiceNumber} onChange={(event) => { this.invoiceChange(event) }} />
                        </Col>
                        <Col span={2} style={{ textAlign: 'left', margin: '12px 0px 0 0' }}>
                            <Button type="primary" onClick={() => this.handleQuery()} icon="search" >查询</Button>
                        </Col>
                    </Row>
                </div>
                <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                <div style={{ padding: 24 }}>
                    <Table
                        dataSource={this.state.tableData}
                        columns={this.state.columns}
                        pagination={false}
                        scroll={{ x: 900, y: store.getState().tableHeight.y }}
                        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='800px'
                        compontName='VATInvoice'
                        configType="C"
                        onRef={this.onColumnRef}
                        reloadData={this.tableList}
                    />
                </div>
            </div>
        )
    }
}


const VATInvoiceForm = Form.create()(VATInvoice);
export default VATInvoiceForm;
