//商户界面维护
import React from 'react';
import { Table, Popconfirm, Icon, message, Modal, Form, Divider, Select, Row, Col, Button, Input, DatePicker } from 'antd';
import { $http } from '../../containers/config/https';
import moment from 'moment';
import store from '../../store';

import CommonPagination from 'components/pagination/index';

const { Option } = Select;
const dateFormat = 'YYYY-MM-DD'; //定义全局日期格式
const formItemLayout = {    // label 和input宽度
    labelCol: { span: 8 },
    wrapperCol: { span: 14, offset: 2 },
};

class MaintainWeChatPubAccMerchant extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false, //加载状态标志
            visible: false, //弹窗显示状态标志
            motalTitle: '', //弹窗标题
            modalState: '', //弹窗点击提交时判断是否修改或增加标志
            total: 0,  // 表格数据总条数
            page: 1, //当前页数
            pageSize: 10, //每页显示条数
            merchantNo: "",
            merchantName: "",
            tableData: [],
            pubAccount: "",
            hospID: "",
            updateID: "",
            delID: "",
            hospData: [],
            pubAccountData: [],
        };
        this.columns = [
            {
                title: '公众号',
                dataIndex: 'pubAccount',
                key: 'pubAccount',
                width: '100px',
                align: "center",
            },
            {
                title: '医院',
                dataIndex: 'hosp',
                key: 'hosp',
                width: '100px',
                align: "center",
            },
            {
                title: '商户号',
                dataIndex: 'merchantNo',
                key: 'merchantNo',
                width: '100px',
                align: "center",
            },
            {
                title: '商户名称',
                dataIndex: 'merchantName',
                key: 'merchantName',
                width: '100px',
                align: "center",
            },
            {
                title: 'API密钥',
                dataIndex: 'APISecret',
                key: 'APISecret',
                width: '100px',
                align: "center",
            },
            {
                title: '收款证书名',
                dataIndex: 'sslconfiguration',
                key: 'sslconfiguration',
                width: '100px',
                align: "center",
            },
            {
                title: '退款证书名',
                dataIndex: 'refunsslconfiguration',
                key: 'refunsslconfiguration',
                width: '100px',
                align: "center",
            },
            {
                title: '操作',
                key: 'op',
                align: "center",
                width: '100px',
                render: (text, record) => (
                    <span>
                        <span className='span' onClick={() => this.showModal(record)}><Icon type="edit" />修改</span>
                        <Divider type="vertical" />
                        <Popconfirm
                            title="确定要删除吗?"
                            onConfirm={this.delConfirm}
                            okText="是"
                            cancelText="否"
                        >
                            <span style={{ color: '#f00' }} className='span' onClick={() => this.setState({ delID: record.id })}><Icon type="delete" />删除</span>
                        </Popconfirm>
                    </span>
                ),
            },
        ];
    }


    componentDidMount() {
        //初始化列表数据
        this.handleQuery();
        //公众号下拉框数据
        this.pubAccountData();
        //医院下拉框数据
        this.hospData();
    }

    //获取医院下拉框
    hospData = () => {
        let data = {
            params: [{
                hospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
                logonGroupID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).groupID : "",
                logonHospID: sessionStorage.userData ? JSON.parse(sessionStorage.userData).hospID : "",
            }],
        }
        let hospital = []
        $http.post('urlS', this, {
            code: '130963',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.result.data.length; i++) {
                        hospital.push(<Option value={String(res.result.data[i].id)} key={i + "H"} >{res.result.data[i].descripts}</Option>)
                    }
                    this.setState({ hospData: hospital })
                }
            }
        })
    }

    //获取公众号下拉框
    pubAccountData = () => {
        let data = {
            params: [{

            }],
        }
        let pubAccountData = []
        $http.post('urlS', this, {
            code: '130953',
            data: data,
            success: function (res) {
                if (+res.errorCode === 0) {
                    for (var i = 0; i < res.result.data.length; i++) {
                        pubAccountData.push(<Option value={String(res.result.data[i].id)} key={i + "P"} >{res.result.data[i].descripts}</Option>)
                    }
                    this.setState({ pubAccountData: pubAccountData })
                }
            }
        })
    }

    //初始化列表数据
    handleQuery = () => {
        let { page, pageSize, pubAccount, hospID, merchantNo, merchantName } = this.state;
        let data = {}
        data = {
            params: [{
                pubAccount: pubAccount,
                hospID: hospID,
                merchantNo: merchantNo,
                merchantName: merchantName
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: '130957',
            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 })
                }
            }
        })
    }

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

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

    //弹窗显示
    showModal = (params) => {
        if (params === 'add') {
            this.setState({
                visible: true,
                motalTitle: "新增",
                updateID: "",
            });
            this.props.form.setFieldsValue({
                'pubAccount': null,
                'hosp': null,
                'merchantNo': null,
                'merchantName': null,
                'APISecret': null,
                'sslconfiguration': null,
                'refunsslconfiguration': null
            });
        } else {
            this.setState({
                updateID: params.id,
                visible: true,
                motalTitle: "修改",
            });
            this.props.form.setFieldsValue({
                'pubAccount': params.pubAccountID.toString(),
                'hosp': params.hospID.toString(),
                'merchantNo': params.merchantNo,
                'merchantName': params.merchantName,
                'APISecret': params.APISecret,
                'sslconfiguration': params.sslconfiguration,
                'refunsslconfiguration': params.refunsslconfiguration
            });
        }
    };

    //弹窗点击取消
    handleCancel = () => {
        this.setState({ visible: false, });
    };

    //弹窗点击确定
    handleOk = () => {
        this.props.form.validateFields((err, values) => {
            if (err) {
                return;
            }
            let data = {};
            data = {
                params: [{
                    id: this.state.updateID,
                    userID: JSON.parse(window.sessionStorage.userData).userID,
                    pubAccountID: values.pubAccount,
                    hospID: values.hosp,
                    merchantNo: values.merchantNo,
                    merchantName: values.merchantName,
                    APISecret: values.APISecret,
                    sslconfiguration: values.sslconfiguration,
                    refunsslconfiguration: values.refunsslconfiguration,
                }]
            }
            $http.post('urlS', this, {
                code: '130958',
                data: data,
                success: function (res) {
                    if (+res.errorCode === 0) {
                        message.success(res.errorMessage);
                        this.handleQuery();
                        this.setState({ loading: false, visible: false });
                    }
                }
            })
        })
    };

    //删除确认
    delConfirm = (e) => {
        this.handleDel();
    }

    //删除操作
    handleDel = () => {
        let data = {
            params: [{
                id: this.state.delID,
                userID: JSON.parse(window.sessionStorage.userData).userID
            }]
        };
        $http.post('urlS', this, {
            code: "130959",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.handleQuery() // 查询
                }
            }
        });
    }

    onChangePubAccount = (e) => {
        this.setState({ pubAccount: e });
    }

    onChangeHosp = (e) => {
        this.setState({ hospID: e });
    }

    onChangeMerchantNo = (e) => {
        this.setState({ merchantNo: e.target.value })
    }

    onChangeMerchantName = (e) => {
        this.setState({ merchantName: e.target.value })
    }

    render() {
        let { pubAccountData, hospData } = this.state;
        const { getFieldDecorator } = this.props.form;
        return (
            <div>
                <div style={{ width: '100%', height: '100%' }}>
                    <Row style={{ minHeight: '80px', padding: '24px 24px 24px 24px' }}>
                        <Col span={4}>
                            <span>公众号：</span>
                            <Select style={{ width: '200px' }} allowClear placeholder="请选择公众号" onChange={this.onChangePubAccount} >
                                {pubAccountData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>医院：</span>
                            <Select style={{ width: '200px' }} allowClear placeholder="请选择医院" onChange={this.onChangeHosp} >
                                {hospData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>商户号：</span>
                            <Input allowClear placeholder="请输入商户号" style={{ width: '200px', }} onChange={this.onChangeMerchantNo} />
                        </Col>
                        <Col span={4}>
                            <span>商户名：</span>
                            <Input allowClear placeholder="请输入商户名称" style={{ width: '200px', }} onChange={this.onChangeMerchantName} />
                        </Col>
                        <Col span={4}></Col>
                        <Col span={2} style={{ textAlign: 'right' }}>
                            <Button type="primary" onClick={() => this.handleQuery()} icon="search" >查询</Button>
                        </Col>
                        <Col span={2} style={{ textAlign: 'center' }}>
                            <Button type="primary" onClick={() => this.showModal('add')} icon="plus" style={{ background: '#F7805D', color: '#FFFFFF', borderColor: '#F7805D' }} >
                                新增
                            </Button>
                            <Form layout="inline">
                                <Modal
                                    visible={this.state.visible}
                                    title={this.state.motalTitle}
                                    onOk={() => this.handleOk()}
                                    onCancel={this.handleCancel}
                                    width='600px'
                                    footer={[
                                        <Button key="back" onClick={this.handleCancel}>返回</Button>,
                                        <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOk}>提交</Button>,
                                    ]}
                                >
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item label="公众号" {...formItemLayout} >
                                                {getFieldDecorator("pubAccount", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '公众号不能为空' }]
                                                })(
                                                    <Select style={{ width: '200px' }} allowClear placeholder="请选择公众号">
                                                        {pubAccountData}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="医院" {...formItemLayout}>
                                                {getFieldDecorator("hosp", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '医院不能为空' }]
                                                })(
                                                    <Select style={{ width: '200px' }} allowClear placeholder="请选择医院">
                                                        {hospData}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="商户号" {...formItemLayout}>
                                                {getFieldDecorator("merchantNo", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '商户号不能为空' }]
                                                })(
                                                    <Input allowClear style={{ width: '200px', }} placeholder="请输入商户号"/>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="商户名称" {...formItemLayout}>
                                                {getFieldDecorator("merchantName", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '商户名称不能为空' }]
                                                })(
                                                    <Input allowClear style={{ width: '200px', }} placeholder="请输入商户名称"/>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="API密钥" {...formItemLayout}>
                                                {getFieldDecorator("APISecret", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: 'API密钥不能为空' }]
                                                })(
                                                    <Input allowClear style={{ width: '200px', }} placeholder="请输入API密钥"/>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="收款证书名" {...formItemLayout}>
                                                {getFieldDecorator("sslconfiguration", {
                                                    initialValue: null,
                                                })(
                                                    <Input allowClear style={{ width: '200px', }} placeholder="请输入API密钥"/>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="退款证书名" {...formItemLayout}>
                                                {getFieldDecorator("refunsslconfiguration", {
                                                    initialValue: null,
                                                })(
                                                    <Input allowClear style={{ width: '200px', }} placeholder="请输入API密钥"/>
                                                )}
                                            </Form.Item>
                                        </Col>
                                    </Row>
                                </Modal>
                            </Form>
                        </Col>
                    </Row>
                </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.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} />
                </div>
            </div>
        )
    }
}

const MaintainWeChatPubAccMerchantForm = Form.create()(MaintainWeChatPubAccMerchant);
export default MaintainWeChatPubAccMerchantForm;