import React from 'react';
import { Icon, Button, Input, Spin, Table, message, Radio, Select, Modal, Upload } from 'antd';
import { beforeUploadFile, newDownloadFile } from '../../tools.js';
import './standard.less';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';

const StandardDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    handleOk() {
        this.setState({
            loading: true,
        });
        if (!this.state.standardName || !this.state.standardNumber || !this.state.year) {
            message.warning('请输入正确信息！');
            this.setState({
                loading: false
            });
            return;
        };
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/developStandard",
            data: {
                id: this.props.data.id,
                standardName: this.state.standardName,
                standardNumber: this.state.standardNumber,
                year: this.state.year,
                standardLevel: this.state.standardLevel,
                participateWay: this.state.participateWay,
                enclosureUrl: this.state.enclosureUrl
            },
            success: function (data) {
                if (data.data) {
                    this.setState({
                        id: data.data.id,
                        standardName: data.data.standardName,
                        standardNumber: data.data.standardNumber,
                        standardLevel: data.data.standardLevel,
                        participateWay: data.data.participateWay,
                        enclosureUrl: data.data.enclosureUrl
                    });
                } else if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                };
            }.bind(this),
        }).done(function (data) {
            if (!data.error.length) {
                message.success('保存成功！');
                this.setState({
                    loading: false,
                    visible: false
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.props.closeDesc(false, true);
        }.bind(this));
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    componentWillMount() {
        const Option = Select.Option;
        const d = new Date();
        const thisYear = d.getFullYear();
        let theOption = [];
        for (let i = thisYear; i >= 1950; i--) {
            theOption.push(<Option key={i.toString()}>{i}</Option>)
        };
        this.state.yearOption = theOption;
    },
    componentWillReceiveProps(nextProps) {
        if (!this.state.visible && nextProps.showDesc) {
            this.state.fileList = [];
            this.state.enclosureUrl = undefined;
            if (nextProps.data) {
                this.state.standardName = nextProps.data.standardName;
                this.state.standardNumber = nextProps.data.standardNumber;
                this.state.year = nextProps.data.year;
                this.state.standardLevel = nextProps.data.standardLevel;
                this.state.participateWay = nextProps.data.participateWay;
                this.state.enclosureUrl = nextProps.data.enclosureUrl;
            };
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        if (this.props.data) {
            return (
                <div className="admin-desc">
                    <Modal maskClosable={false} title="企业参与国家标准或行业标准制定情况明细" visible={this.state.visible} onCancel={this.handleCancel}
                        width='400px' footer={[
                            <Button key="submit" type="primary" size="large" loading={this.state.loading} onClick={this.handleOk}>确认</Button>,
                            <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>取消</Button>
                        ]}
                        className="admin-desc-content">
                        <div>
                            <p>标准名称:</p>
                            <Input defaultValue={this.props.data.standardName} value={this.state.standardName}
                                onChange={(e) => { this.setState({ standardName: e.target.value }); }} />
                        </div>
                        <div>
                            <p>标准编号:</p>
                            <Input value={this.state.standardNumber}
                                onChange={(e) => { this.setState({ standardNumber: e.target.value }); }} />
                        </div>
                        <div>
                            <p>制定时间:</p>
                            <Select
                                placeholder="请选择年份"
                                value={this.state.year}
                                onChange={(e) => { this.setState({ year: e }); }}
                                style={{ width: 120 }}>
                                {this.state.yearOption}
                            </Select>
                        </div>
                        <div>
                            <p>标准级别:</p>
                            <Radio.Group value={this.state.standardLevel} onChange={(e) => { this.setState({ standardLevel: e.target.value }) }}>
                                <Radio value={0}>国家</Radio>
                                <Radio value={1}>行业</Radio>
                            </Radio.Group>
                        </div>
                        <div>
                            <p>参与方式:</p>
                            <Radio.Group value={this.state.participateWay} onChange={(e) => { this.setState({ participateWay: e.target.value }) }}>
                                <Radio value={0}>主持</Radio>
                                <Radio value={1}>参与</Radio>
                            </Radio.Group>
                        </div>
                        <div className="hrSituation-roster">
                            <Upload
                                name="ratepay"
                                action={globalConfig.context + "/api/user/cognizance/uploadStandard"}
                                data={{ 'sign': 'standard', 'uid': this.props.uid }}
                                beforeUpload={beforeUploadFile}
                                fileList={this.state.fileList}
                                onChange={(info) => {
                                    if (info.file.status !== 'uploading') {
                                        console.log(info.file, info.fileList);
                                    }
                                    if (info.file.status === 'done') {
                                        if (!info.file.response.error.length) {
                                            message.success(`${info.file.name} 文件上传成功！`);
                                        } else {
                                            message.warning(info.file.response.error[0].message);
                                            return;
                                        };
                                        this.state.enclosureUrl = info.file.response.data;
                                    } else if (info.file.status === 'error') {
                                        message.error(`${info.file.name} 文件上传失败。`);
                                    };
                                    this.setState({ fileList: info.fileList.slice(-1) });
                                }}
                            >
                                <Button><Icon type="upload" /> 上传标准制定附件 </Button>
                            </Upload>
                            <p style={{ marginTop: '10px' }}>{this.state.enclosureUrl ? <a onClick={newDownloadFile.bind(null, this.props.data.id, 'standard', '/api/user/cognizance/downloadStandard')}>标准定制附件</a> : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传！</span>}</p>
                        </div>
                    </Modal>
                </div>
            );
        } else {
            return <div></div>
        }
    },
});

const Standard = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/standard",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                standardName: this.state.standardName,
                standardNumber: this.state.standardNumber,
                standardLevel: this.state.standardLevel,
                participateWay: this.state.participateWay
            },
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        this.state.ButtonDisabled = true;
                    }
                    return;
                };
                for (let i = 0; i < data.data.list.length; i++) {
                    let thisdata = data.data.list[i];
                    this.state.data.push({
                        key: i + 1,
                        id: thisdata.id,
                        uid: thisdata.uid,
                        standardName: thisdata.standardName,
                        standardNumber: thisdata.standardNumber,
                        year: thisdata.year,
                        enclosureUrl: thisdata.enclosureUrl,
                        standardLevel: thisdata.standardLevel,
                        participateWay: thisdata.participateWay,
                        createTime: thisdata.createTime,
                        createTimeFormattedDate: thisdata.createTimeFormattedDate
                    });
                };
                this.state.pagination.current = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
                this.setState({
                    dataSource: this.state.data,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            columns: [
                {
                    title: '编号',
                    dataIndex: 'key',
                    key: 'key'
                }, {
                    title: '标准名称',
                    dataIndex: 'standardName',
                    key: 'standardName'
                }, {
                    title: '标准编号',
                    dataIndex: 'standardNumber',
                    key: 'standardNumber'
                }, {
                    title: '制定时间',
                    dataIndex: 'year',
                    key: 'year'
                }, {
                    title: '标准级别',
                    dataIndex: 'standardLevel',
                    key: 'standardLevel',
                    render: text => {
                        switch (text) {
                            case 0:
                                return "国家";
                            case 1:
                                return "行业";
                        }
                    }
                }, {
                    title: '参与方式',
                    dataIndex: 'participateWay',
                    key: 'participateWay',
                    render: text => {
                        switch (text) {
                            case 0:
                                return "主持";
                            case 1:
                                return "参与";
                        }
                    }
                }
            ],
            dataSource: []
        };
    },
    componentWillMount() {
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    delectRow() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.id) {
                deletedIds.push(rowItem.id)
            }
        }
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/deleteStandard",
            data: {
                ids: deletedIds
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('删除成功！');
                this.setState({
                    loading: false,
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.standardName = undefined;
        this.state.standardNumber = undefined;
        this.state.standardLevel = undefined;
        this.state.participateWay = undefined;
        this.loadData();
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        }
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="user-content" >
                <div className="content-title">
                    <span>标准制定情况汇总</span>
                </div>
                <div className="user-search">
                    <Input placeholder="标准名称" value={this.state.standardName}
                        onChange={(e) => { this.setState({ standardName: e.target.value }); }} />
                    <Input placeholder="标准编号" value={this.state.standardNumber}
                        onChange={(e) => { this.setState({ standardNumber: e.target.value }); }} />
                    <Select placeholder="标准级别" style={{ width: 200 }}
                        value={this.state.standardLevel}
                        onChange={(e) => { this.setState({ standardLevel: e }) }}>
                        <Select.Option value="0" >国家</Select.Option>
                        <Select.Option value="1" >行业</Select.Option>
                    </Select>
                    <Select placeholder="参与方式" style={{ width: 200 }}
                        value={this.state.participateWay}
                        onChange={(e) => { this.setState({ participateWay: e }) }}>
                        <Select.Option value="0" >主持</Select.Option>
                        <Select.Option value="1" >参与</Select.Option>
                    </Select>
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <p>
                        <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                            disabled={this.state.ButtonDisabled}
                            onClick={this.tableRowClick}>添加<Icon type="plus" /></Button>
                        <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                            disabled={!hasSelected}
                            onClick={this.delectRow}>删除<Icon type="minus" /></Button>
                    </p>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            rowSelection={rowSelection}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <StandardDesc data={this.state.RowData} showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default Standard;