//微信公众号界面维护
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 MaintainWeChatPubAccount 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: [],
            code: "",
            descripts: "",
            updateID: "",
            delID: "",
            startDate: null,
            endDate: null,
        };
        this.columns = [
            {
                title: '代码·',
                dataIndex: 'code',
                key: 'code',
                width: '100px',
                align: "center",
            },
            {
                title: '描述',
                dataIndex: 'descripts',
                key: 'descripts',
                width: '100px',
                align: "center",
            },
            {
                title: '英文描述',
                dataIndex: 'ENDesc',
                key: 'ENDesc',
                width: '100px',
                align: "center",
            },
            {
                title: '登陆名',
                dataIndex: 'loginName',
                key: 'loginName',
                width: '100px',
                align: "center",
            },
            {
                title: '开发者ID',
                dataIndex: 'appID',
                key: 'appID',
                width: '250px',
                align: "center",
            },
            {
                title: '开发者密钥',
                dataIndex: 'appSecret',
                key: 'appSecret',
                width: '300px',
                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",
                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();
    }

    //初始化列表数据
    handleQuery = () => {
        let { page, pageSize, code, descripts, startDate, endDate } = this.state;
        let data = {}
        data = {
            params: [{
                code: code,
                descripts: descripts,
                startDate: startDate,
                endDate: endDate
            }],
            pagination: [{
                pageSize: pageSize,
                currentPage: page,
                sortColumn: 'code',
                sortOrder: 'asc'
            }]
        }
        $http.post('urlS', this, {
            code: '130950',
            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({
                'code': '',
                'descripts': '',
                'ENDesc': '',
                'loginName': '',
                'appID': '',
                'appSecret': '',
                'startDate': null,
                'endDate': null,
            });
        } else {
            console.log("params:" + params)
            this.setState({
                updateID: params.id,
                visible: true,
                motalTitle: "修改",
            });
            this.props.form.setFieldsValue({
                'code': params.code,
                'descripts': params.descripts,
                'ENDesc': params.ENDesc,
                'loginName': params.loginName,
                'appID': params.appID,
                'appSecret': params.appSecret,
                '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,
                    code: values.code,
                    descripts: values.descripts,
                    ENDesc: values.ENDesc,
                    loginName: values.loginName,
                    appID: values.appID,
                    appSecret: values.appSecret,
                    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: '130951',
                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: "130952",
            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);
    };

    onChangeCode = (e) => {
        this.setState({ code: e.target.value })
    }

    onChangeDescripts = (e) => {
        this.setState({ descripts: e.target.value })
    }

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

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

    render() {
        let { startValue, endValue } = 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>
                            <Input allowClear placeholder="请输入代码" style={{ width: '200px', }} onChange={this.onChangeCode} />
                        </Col>
                        <Col span={4}>
                            <span>描述：</span>
                            <Input allowClear placeholder="描述" style={{ width: '200px', }} onChange={this.onChangeDescripts} />
                        </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={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("code", {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '代码不能为空' }]
                                                })(
                                                    <Input allowClear placeholder="请输入代码" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="描述" {...formItemLayout}>
                                                {getFieldDecorator("descripts", {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '描述不能为空' }]
                                                })(
                                                    <Input allowClear placeholder="请输入描述" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="英文描述" {...formItemLayout}>
                                                {getFieldDecorator("ENDesc", {
                                                    initialValue: undefined
                                                })(
                                                    <Input allowClear placeholder="请输入英文描述" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="登陆名" {...formItemLayout}>
                                                {getFieldDecorator("loginName", {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '登陆名不能为空' }]
                                                })(
                                                    <Input allowClear placeholder="请输入登陆名" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="开发者ID" {...formItemLayout}>
                                                {getFieldDecorator("appID", {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '开发者ID不能为空' }]
                                                })(
                                                    <Input allowClear placeholder="请输入开发者ID" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="开发者密钥" {...formItemLayout}>
                                                {getFieldDecorator("appSecret", {
                                                    initialValue: undefined,
                                                    rules: [{ required: true, message: '开发者密钥不能为空' }]
                                                })(
                                                    <Input allowClear placeholder="请输入开发者密钥" style={{ width: '200px', }} />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="生效日期" {...formItemLayout}>
                                                {getFieldDecorator("startDate", {
                                                    initialValue: startValue,
                                                    rules: [{ required: true, message: '生效日期不能为空' }]
                                                })(
                                                    <DatePicker
                                                        format={dateFormat}
                                                        disabledDate={this.disabledStartDate}
                                                        onChange={this.onStartChange}
                                                    />
                                                )}
                                            </Form.Item>
                                        </Col>
                                        <Col span={24}>
                                            <Form.Item label="失效日期" {...formItemLayout}>
                                                {getFieldDecorator("endDate", {
                                                    initialValue: endValue,
                                                })(
                                                    <DatePicker
                                                        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 MaintainWeChatPubAccountForm = Form.create()(MaintainWeChatPubAccount);
export default MaintainWeChatPubAccountForm;