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

const HonorListDescFrom = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false
        };
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.spinState(true);
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + "/api/user/cognizance/disposeHonor",
                    data: {
                        id: this.props.data.id,
                        name: values.name,
                        issuingMechanism: values.issuingMechanism,
                        year: values.year,
                        //issuingTimeFormattedDate: values.issuingTimeFormattedDate.format("YYYY-MM-DD"),
                        enclosureUrl: this.state.enclosureUrl
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.clickOk();
                        this.props.spinState(false);
                        this.props.form.resetFields();
                    } else {
                        message.warning(data.error[0].message);
                        this.props.spinState(false);
                    }
                }.bind(this));
            }
        });
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.props.form.resetFields();
        };
    },
    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;
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const theData = this.props.data;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form onSubmit={this.handleSubmit} className="activityCost-form" >
                <div className="clearfix">
                    <FormItem
                        {...formItemLayout}
                        label="名称"
                    >
                        {getFieldDecorator('name', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.name
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="获取时间"
                    >
                        {getFieldDecorator('year', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.year
                        })(
                            <Select
                                placeholder="请选择年份"
                                style={{ width: 80 }}>
                                {this.state.yearOption}
                            </Select>
                            )}
                        <span> 年</span>
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="发证机构"
                    >
                        {getFieldDecorator('issuingMechanism', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.issuingMechanism
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="hrSituation-roster">
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/user/cognizance/uploadHonor"}
                        data={{ 'sign': 'honor' }}
                        beforeUpload={beforeUploadFile}
                        showUploadList={false}
                        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} 文件上传失败。`);
                            }
                        }}
                    >
                        <Button><Icon type="upload" /> 企业相关资质证书 </Button>
                    </Upload>
                    <p style={{ marginTop: '10px' }}>{theData.enclosureUrl ? <a onClick={newDownloadFile.bind(null, theData.id, 'honor', '/api/user/cognizance/downloadHonor')}>{theData.enclosureDownloadFileName}</a> : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传！</span>}</p>
                </div>
                <FormItem style={{ marginTop: '20px' }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                    <Button type="ghost" style={{ marginLeft: '20px' }} onClick={this.props.closeModal}>取消</Button>
                </FormItem>
            </Form >
        );
    },
}));

const HonorListDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false
        };
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showDesc
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleOk() {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    spinChange(e) {
        this.setState({
            loading: e
        });
    },
    render() {
        return (
            <div className="patent-addNew">
                <Spin spinning={this.state.loading} className='spin-box'>
                    <Modal title="企业荣誉及其他证明材料" visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='800px'
                        footer=''
                    >
                        <HonorListDescFrom
                            data={this.props.data}
                            spinState={this.spinChange}
                            visible={this.state.visible}
                            closeModal={this.handleCancel}
                            clickOk={this.handleOk} />
                    </Modal>
                </Spin>
            </div>
        );
    },
});

const HonorList = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/honorList",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize
            }
        }).done((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,
                    id: thisdata.id,
                    uid: thisdata.uid,
                    name: thisdata.name,
                    year: thisdata.year,
                    issuingTime: thisdata.issuingTime,
                    enclosureUrl: thisdata.enclosureUrl,
                    enclosureDownloadFileName: thisdata.enclosureDownloadFileName,
                    enclosure: [thisdata.id, thisdata.enclosureDownloadFileName],
                    issuingTimeFormattedDate: thisdata.issuingTimeFormattedDate,
                    issuingMechanism: thisdata.issuingMechanism
                });
            };
            this.state.pagination.current = data.data.pageNo;
            this.state.pagination.total = data.data.totalCount;
            this.setState({
                dataSource: this.state.data,
                pagination: this.state.pagination
            });
        }).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: 'name',
                    key: 'name'
                }, {
                    title: '获取时间',
                    dataIndex: 'year',
                    key: 'year'
                }, {
                    title: '发证机构',
                    dataIndex: 'issuingMechanism',
                    key: 'issuingMechanism'
                }, {
                    title: '相关附件',
                    dataIndex: 'enclosure',
                    key: 'enclosure',
                    render: (text) => {
                        return <a onClick={newDownloadFile.bind(null, text[0], 'honor', '/api/user/cognizance/downloadHonor')}>{text[1]}</a>
                    }
                }
            ],
            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/deleteHonor",
            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.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">
                    <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>
                <HonorListDesc data={this.state.RowData}
                    showDesc={this.state.showDesc} closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default HonorList;