//病人退费方式调整
import React from 'react';
import store from '../../store';
import '../../assets/css/system.css';
import { Popconfirm, Button, Icon, Select, Checkbox, message, Form, Divider, Spin, Table } from 'antd';
import CommonPagination from 'components/pagination/index';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import { $http } from '../../containers/config/https';
import OPRefundPayWayModal from './OPRefundPayWayModal.jsx'
const { Option } = Select;

class OPRefundPayWay extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hospitalDr: undefined,
            hospitalData: [],
            RefundPayWayArr: [],
            userInfo: {},
            // 表格数据
            tableData: [],
            showLoading: true,
            // 表格数据总条数
            total: 0,
            page: 1,
            pageSize: 10,
            languageTable1: {}, // 国际化Table1
            languageTable2: {}, // 国际化Table2
            languageData: {}, // 国际化语言包
            language: {},   // 国际化语言
            languageCode: JSON.parse(window.sessionStorage.userData).language, // 国际化语言标识
        };
    }

    componentDidMount() {
        this.tableList();
        //初始化列表数据
        this.handleQuery();
        // 组件加载完毕关闭loading
        this.setState({ showLoading: false })
        //初始化下拉框数据
        this.loadHospitalMsg();
        //原支付方式和退费方式下拉框
        this.getInitData();

    }

    // 获取主列表columns
    tableList = () => {
        var data = {
            params: [{
                "reactCode": ["OPRefundPayWay"],
                "compontName": "OPRefundPayWay",
                "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)
                        this.listAdd(filterArr.length + 1, 0, languageCode);
                    })
                }
            }
        })
    }

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

    //render 自定义项目名称
    listAdd = (i, j, languageCode) => {
        let { columns } = this.state
        columns.splice(i, j,
            {
                title: languageCode === 'CN' ? "操作" : 'Operation',
                key: 'op',
                width: '100px',
                align: "center",
                render: (text, record) => (
                    <span>
                        <span className='span' onClick={this.handleCompile.bind(this, record)}><Icon type="edit" />{languageCode === 'CN' ? "编辑" : 'Edit'}</span>
                        <Divider type="vertical" />
                        <Popconfirm
                            title={languageCode === 'CN' ? "确定要删除吗?" : 'You sure you want to delete it?'}
                            onConfirm={this.delConfirm}
                            okText={languageCode === 'CN' ? "是" : 'Yes'}
                            cancelText={languageCode === 'CN' ? "否" : 'No'}
                            onConfirm={this.handleDelete.bind(this, record)}
                        >
                            <span style={{ color: '#f00' }} className='span'><Icon type="delete" />{languageCode === 'CN' ? "删除" : 'Delete'}</span>
                        </Popconfirm>
                    </span>
                ),
            },
        )
    }
    onColumnRef = (ref) => {
        this.columnRef = ref;
    }

    //列表数据
    handleQuery = () => {
        let { page, pageSize } = this.state;
        let data = {}
        data = {
            params: [{
                hospID: this.state.hospitalId ? this.state.hospitalId : JSON.parse(window.sessionStorage.userData).hospID
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urls', this, {
            code: '05100076',
            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 })
                }
            }
        });
    }

    //删除
    handleDelete(record) {
        let data = {
            params: [{
                ID: record.ID,
                userID: JSON.parse(window.sessionStorage.userData).userID
            }]
        }
        $http.post('urlADS', this, {
            code: '05100077',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    message.success('删除成功！');
                    //刷新列表数据
                    this.handleQuery()
                }
            }
        })
    }

    //查询医院下拉
    loadHospitalMsg() {
        var data = {
            params: [{
                hospID: '', // 医院id
                logonGroupID: JSON.parse(window.sessionStorage.userData).groupID, //登录角色id
                logonHospID: JSON.parse(window.sessionStorage.userData).hospID, // 登录医院id
            }]
        }
        $http.post('urlS', this, {
            code: "01040001",
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    this.setState({
                        hospitalData: res.depDoctor,
                        asdasd: res.asd,
                        asdas: res.asd,
                    })
                    var result = res.depDoctor && res.depDoctor.some(item => {
                        if (item.id === user.hospID) {
                            return true
                        }
                    })
                    if (!result) {
                        this.setState({
                            hospitalId: undefined
                        })
                    } else {
                        this.setState({ hospitalId: user.hospID ? user.hospID : undefined })
                    }
                }
            }
        });
    }

    //支付方式及退费方式下拉框
    getInitData = () => {
        $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)} title='UnitID' key={i}>{res.RefundPayWayArr[i].Descripts}</Option>)
                    }
                    this.setState({ RefundPayWayArr: this.state.RefundPayWayArr })
                }
            },
            error: function (err) {
                this.setState({ errMsg: "数据加载失败，请重试!" });
            }
        });
    }

    //医院下拉框
    onChangeHospitalDr = (e) => {
        this.setState({
            hospitalId: e
        }, () => {
            //刷新列表数据
            this.handleQuery()
        })
    }

    //保存
    handleSubmit = (e) => {
        e.preventDefault();
        let { validateFields } = this.props.form;
        var Code = '05100079';
        validateFields({ force: true }, (err, params) => {
            if (err) {
                return;
            }
            let data = {}
            params.reFundAFlag = params.reFundAFlag ? 'Y' : 'N'
            params.reFundSFlag = params.reFundSFlag ? 'Y' : 'N'
            params.userID = JSON.parse(window.sessionStorage.userData).userID
            data = {
                params: [params]
            };
            $http.post('urlDeanlt', this, {
                code: Code,
                data: data,
                success: function (res) {
                    if (res.errorCode === '0') {
                        message.success('保存成功！')
                        //重置表单
                        this.props.form.resetFields();
                        //刷新列表数据
                        this.handleQuery()
                    }
                }
            })
        })
    }

    // 编辑
    handleCompile(record) {
        // 初始化数据
        this.setState({ flag: 'compile', userInfo: record, title: "编辑" }, () => {
            // 打开弹框
            this.modalChild.showModal(this.state.flag, record);
        });
    }

    //调用子组件的连接事件
    onModalRef = (ref) => {
        this.modalChild = ref
    }

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

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

    render() {
        let { language } = this.state
        const { getFieldDecorator } = this.props.form;
        return (
            <Spin tip="加载中..." spinning={this.state.showLoading}>
                <div>
                    <div style={{ height: '85px', lineHeight: '200px', padding: '20px 24px', }}>
                        <Form onSubmit={this.handleSubmit} layout="inline">
                            <Form.Item label={language.OPRefundPayWayHospital && language.OPRefundPayWayHospital.descripts}>
                                {getFieldDecorator("hospID", {
                                    initialValue: this.state.hospitalId
                                })(
                                    <Select showSearch optionFilterProp="title" onChange={(even) => { this.onChangeHospitalDr(even) }} style={{ width: '150px' }} placeholder={language.OPRefundPayWayHospital && language.OPRefundPayWayHospital.message}>
                                        {this.state.hospitalData && this.state.hospitalData.map(item => {
                                            return <Option key={item.id} value={item.id} title={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>
                                        })}
                                    </Select>
                                )
                                }
                            </Form.Item>
                            <Form.Item label={language.OPRefundPayWayOriginal && language.OPRefundPayWayOriginal.descripts}>
                                {getFieldDecorator("oldPayWayDR", {
                                    rules: [{ required: true, message: language.OPRefundPayWayOriginal && language.OPRefundPayWayOriginal.message }]
                                })(
                                    <Select style={{ width: '150px', marginRight: '20px' }} placeholder={language.OPRefundPayWayOriginal && language.OPRefundPayWayOriginal.message}>
                                        {this.state.RefundPayWayArr}
                                    </Select>
                                )
                                }
                            </Form.Item>
                            <Form.Item label={language.OPRefundPayWayrush && language.OPRefundPayWayrush.descripts}>
                                {getFieldDecorator("reFundAFlag", {
                                    rules: [{ required: false }], valuePropName: 'checked',
                                })(
                                    <Checkbox />
                                )
                                }
                            </Form.Item>
                            <Form.Item label={language.OPRefundPayWayObsolete && language.OPRefundPayWayObsolete.descripts}>
                                {getFieldDecorator("reFundSFlag", {
                                    rules: [{ required: false }], valuePropName: 'checked',
                                })(
                                    <Checkbox />
                                )
                                }
                            </Form.Item>
                            <Form.Item label={language.OPRefundPayWayRefund && language.OPRefundPayWayRefund.descripts}>
                                {getFieldDecorator("rPayWayDR", {
                                    rules: [{ required: true, message: language.OPRefundPayWayRefund && language.OPRefundPayWayRefund.message }]
                                })(
                                    <Select style={{ width: '150px', marginRight: '20px' }} placeholder={language.OPRefundPayWayRefund && language.OPRefundPayWayRefund.message}>
                                        {this.state.RefundPayWayArr}
                                    </Select>
                                )
                                }
                            </Form.Item>
                            <Form.Item>
                                <Button type="primary" htmlType="submit" style={{ background: 'rgba(247,128,93,1)', color: '#fff' }} >{language.OPRefundPayWaysave && language.OPRefundPayWaysave.descripts}</Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <div style={{ widht: '100%', height: '10px', background: '#f0f2f5' }}></div>
                    <div style={{ padding: 24 }}>
                        <Table
                            style={{ height: store.getState().tableHeight.y + 65 + 'px' }}
                            dataSource={this.state.tableData}
                            columns={this.state.columns}
                            className='TableA'
                            //rowClassName="editable-row"
                            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='900px'
                            compontName='OPRefundPayWay'
                            configType="C"
                            onRef={this.onColumnRef}
                            reloadData={this.tableList}
                        />
                    </div>
                    <OPRefundPayWayModal
                        onRef={this.onModalRef}
                        userInfo={this.state.userInfo}
                        hospitalId={this.state.hospitalId}
                        handelThis={this}
                        title={this.state.title}
                    />
                </div>
            </Spin>
        )
    }
}

const WrappedRegistrationForm = Form.create()(OPRefundPayWay);
export default WrappedRegistrationForm