//业务类型和商户对照维护
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 MaintainHBBusTypeWeChatAccMer extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false, //加载状态标志
            visible: false, //弹窗显示状态标志
            motalTitle: '', //弹窗标题
            modalState: '', //弹窗点击提交时判断是否修改或增加标志
            total: 0,  // 表格数据总条数
            page: 1, //当前页数
            pageSize: 10, //每页显示条数
            startValue: null, //日期选择器开始时间
            endValue: null, //日期选择器结束时间
            tableData: [],
            pubAccMerchant: "",
            hospID: "",
            busTypeID: "",
            updateID: "",
            delID: "",
            hospData: [],
            pubAccMerchantData: [],
            busTypeData: [],
            startDate: null,
            endDate: null,
        };
        this.columns = [
            {
                title: '商户',
                dataIndex: 'merchantName',
                key: 'merchantName',
                width: '200px',
                align: "center",
            },
            {
                title: '医院',
                dataIndex: 'hosp',
                key: 'hosp',
                width: '150px',
                align: "center",
            },
            {
                title: '业务类型',
                dataIndex: 'busType',
                key: 'busType',
                width: '100px',
                align: "center",
            },
            {
                title: '生效日期',
                dataIndex: 'startDate',
                key: 'startDate',
                width: '100px',
                align: "center",
            },
            {
                title: '失效日期',
                dataIndex: 'endDate',
                key: 'endDate',
                width: '100px',
                align: "center",
            },
            {
                title: '创建人',
                dataIndex: 'createUser',
                key: 'createUser',
                width: '100px',
                align: "center",
            },
            {
                title: '创建日期',
                dataIndex: 'createDate',
                key: 'createDate',
                width: '100px',
                align: "center",
            },
            {
                title: '创建时间',
                dataIndex: 'createTime',
                key: 'createTime',
                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.pubAccMerchantData();
        //医院下拉框数据
        this.hospData();
        //业务类型下拉框数据
        this.busTypeData();
    }

    //获取医院下拉框
    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 })
                }
            }
        })
    }

    //获取商户下拉框
    pubAccMerchantData = () => {
        let data = {
            params: [{

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

    //获取业务类型下拉框
    busTypeData = () => {
        let data = {
            params: [{

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

    //初始化列表数据
    handleQuery = () => {
        let { page, pageSize, pubAccMerchant, busTypeID, hospID, startDate, endDate } = this.state;
        let data = {}
        data = {
            params: [{
                pubAccMerchantID: pubAccMerchant,
                hospID: hospID,
                busTypeID: busTypeID,
                startDate: startDate,
                endDate: endDate
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: '130960',
            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({
                'merchantName': null,
                'busType': null,
                'hosp': null,
                'startDate': null,
                'endDate': null,
            });
        } else {
            this.setState({
                updateID: params.id,
                visible: true,
                motalTitle: "修改",
            });
            this.props.form.setFieldsValue({
                'merchantName': params.merchantNameID.toString(),
                'hosp': params.hospID.toString(),
                'busType': params.busTypeID.toString(),
                'startDate': params.startDate ? moment(params.startDate, 'YYYY-MM-DD') : null,
                'endDate': params.endDate ? moment(params.endDate, 'YYYY-MM-DD') : null,
            });
        }
    };

    //弹窗点击取消
    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,
                    pubAccMerchantID: values.merchantName,
                    busTypeID: values.busType,
                    hospID: values.hosp,
                    startDate: values.startDate && values.startDate != "" ? moment(values.startDate).utcOffset(480).format('YYYY-MM-DD') : null,
                    endDate: values.endDate && values.endDate != "" ? moment(values.endDate).utcOffset(480).format('YYYY-MM-DD') : null,
                }]
            }
            $http.post('urlS', this, {
                code: '130961',
                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: "130962",
            data: data,
            success: function (res) {
                let errorCode = res.errorCode;
                if (errorCode === '0') {
                    message.success(res.errorMessage);
                    this.handleQuery() // 查询
                }
            }
        });
    }

    //开始日期选择器选择限制
    disabledStartDate = startValue => {
        const { endValue } = this.state;
        if (!startValue || !endValue) {
            return false;
        }
        return startValue.valueOf() > endValue.valueOf();
    };

    //失效日期选择器选择限制
    disabledEndDate = endValue => {
        const { startValue } = this.state;
        if (!endValue || !startValue) {
            return false;
        }
        return endValue.valueOf() <= startValue.valueOf();
    };

    onChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    };

    //开始日期变化
    onStartChange = value => {
        this.onChange('startValue', value);
    };

    //结束日期变化
    onEndChange = value => {
        this.onChange('endValue', value);
    };

    onChangePubAccMerchant = (e) => {
        this.setState({ pubAccMerchant: e });
    }

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

    onChangeBusType = (e) => {
        this.setState({ busTypeID: e });
    }

    onStartDateChange = value => {
        this.setState({ startDate: value })
    }

    onEndDateChange = value => {
        this.setState({ endDate: value })
    }

    render() {
        let { startValue, endValue, pubAccMerchantData, hospData, busTypeData } = 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.onChangePubAccMerchant} >
                                {pubAccMerchantData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>业务类型：</span>
                            <Select style={{ width: '180px' }} allowClear placeholder="请选择医院" onChange={this.onChangeBusType} >
                                {busTypeData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>医院：</span>
                            <Select style={{ width: '200px' }} allowClear placeholder="请选择医院" onChange={this.onChangeHosp} >
                                {hospData}
                            </Select>
                        </Col>
                        <Col span={4}>
                            <span>生效日期：</span>
                            <DatePicker
                                format={dateFormat}
                                allowClear
                                onChange={this.onStartDateChange}
                            />
                        </Col>
                        <Col span={4}>
                            <span>失效日期：</span>
                            <DatePicker
                                format={dateFormat}
                                allowClear
                                onChange={this.onEndDateChange}
                            />
                        </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("merchantName", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '商户不能为空' }]
                                                })(
                                                    <Select style={{ width: '200px' }} allowClear placeholder="请选择商户">
                                                        {pubAccMerchantData}
                                                    </Select>
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="业务类型" {...formItemLayout} >
                                                {getFieldDecorator("busType", {
                                                    initialValue: null,
                                                    rules: [{ required: true, message: '业务类型不能为空' }]
                                                })(
                                                    <Select style={{ width: '200px' }} allowClear placeholder="请选择业务类型">
                                                        {busTypeData}
                                                    </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("startDate", {
                                                    initialValue: startValue,
                                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                                })(
                                                    <DatePicker
                                                        style={{ width: '200px' }}
                                                        format={dateFormat}
                                                        disabledDate={this.disabledStartDate}
                                                        onChange={this.onStartChange}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="失效日期" {...formItemLayout}>
                                                {getFieldDecorator("endDate", {
                                                    initialValue: endValue,
                                                })(
                                                    <DatePicker
                                                        style={{ width: '200px' }}
                                                        format={dateFormat}
                                                        disabledDate={this.disabledEndDate}
                                                        onChange={this.onEndChange}
                                                    />
                                                )}
                                            </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 MaintainHBBusTypeWeChatAccMerForm = Form.create()(MaintainHBBusTypeWeChatAccMer);
export default MaintainHBBusTypeWeChatAccMerForm;