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

const CenterListDescFrom = 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/admin/disposeCenterDetail",
                    data: {
                        id: this.props.data.id,
                        cid: this.props.cid,
                        projectName: values.projectName,
                        projectTimeFormattedDate: values.projectTimeFormattedDate.format("YYYY-MM-DD"),
                        institution: values.institution,
                        termStartTimeFormattedDate: values.termTimeFormattedDate[0].format("YYYY-MM-DD"),
                        termEndTimeFormattedDate: values.termTimeFormattedDate[1].format("YYYY-MM-DD"),
                        protocolUrl: this.state.protocolUrl
                    }
                }).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();
            this.state.fileList = [];
        };
    },
    render() {
        const FormItem = Form.Item;
        const { getFieldDecorator } = this.props.form;
        const { RangePicker } = DatePicker;
        const theData = this.props.data;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
        };
        const _me = this;
        return (
            <Form onSubmit={this.handleSubmit} className="activityCost-form">
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="时间"
                    >
                        {getFieldDecorator('projectTimeFormattedDate', {
                            rules: [{ type: 'object', required: true, message: '此项为必填项!' }],
                            initialValue: theData.projectTimeFormattedDate ? moment(theData.projectTimeFormattedDate) : null
                        })(
                            <DatePicker />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="项目名称"
                    >
                        {getFieldDecorator('projectName', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.projectName
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="期限"
                    >
                        {getFieldDecorator('termTimeFormattedDate', {
                            rules: [{ type: 'array', required: true, message: '此项为必填项!' }],
                            initialValue: theData.termStartTimeFormattedDate && theData.termEndTimeFormattedDate ? [moment(theData.termStartTimeFormattedDate), moment(theData.termEndTimeFormattedDate)] : [null, null]
                        })(
                            <RangePicker />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="科研院所"
                    >
                        {getFieldDecorator('institution', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.institution
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="hrSituation-roster">
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/admin/uploadProtocol"}
                        data={{ 'sign': 'protocol', '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.protocolUrl = 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' }}>{theData.protocolUrl ?
                        <span className="download-file">
                            <a onClick={newDownloadFile.bind(null, this.props.data.id, 'protocol', '/api/admin/downloadProtocol')}>{theData.protocolDownloadFileName}</a>
                            <a onClick={() => {
                                var newTab = window.open('about:blank'); getPreview(theData.id, 'techCenterDetail', 'protocol', function (data) { newTab.location.href = data; });
                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /></a>
                        </span>
                        : <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 CenterListDesc = 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 maskClosable={false} title="产学研情况详情" visible={this.state.visible}
                        onOk={this.handleOk} onCancel={this.handleCancel}
                        width='800px'
                        footer=''
                    >
                        <CenterListDescFrom
                            visible={this.state.visible}
                            cid={this.props.cid}
                            uid={this.props.uid}
                            data={this.props.data}
                            spinState={this.spinChange}
                            closeModal={this.handleCancel}
                            clickOk={this.handleOk} />
                    </Modal>
                </Spin>
            </div>
        );
    },
});

const CenterList = React.createClass({
    loadOrgTechCenterDetail(uid) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/center",
            data: {
                uid: uid || this.props.data.uid
            }
        }).done((data) => {
            let theData = data.data;
            if (!theData) {
                if (data.error.length) {
                    message.warning(data.error[0].message);
                };
                theData = {};
            };
            this.state.cid = theData.id;
            this.state.foundingTime = theData.foundingTimeFormattedDate;
            this.state.principal = theData.principal;
            this.state.systemCatalog = theData.systemCatalog;
            this.state.systemUrl = theData.systemUrl;
            this.state.systemDownloadFileName = theData.systemDownloadFileName;
            this.state.centerName = theData.centerName;
            this.state.comment = theData.comment;
            this.loadData();
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
        let _me = this;
        getProportion(this.props.data.uid, function (data) { _me.setState({ proportion: data }); });
    },
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/centerDetail",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                cid: this.state.cid
            }
        }).done((data) => {
            if (!data.data || !data.data.list) {
                if (data.error.length) {
                    message.warning(data.error[0].message);
                }
                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,
                    cid: thisdata.cid,
                    projectTimeFormattedDate: thisdata.projectTimeFormattedDate,
                    projectName: thisdata.projectName,
                    protocolDownloadFileName: thisdata.protocolDownloadFileName,
                    protocolUrl: thisdata.protocolUrl,
                    protocol: [thisdata.id, thisdata.protocolDownloadFileName],
                    institution: thisdata.institution,
                    termTimeFormattedDate: [thisdata.termStartTimeFormattedDate, thisdata.termEndTimeFormattedDate],
                    termStartTimeFormattedDate: thisdata.termStartTimeFormattedDate,
                    termEndTimeFormattedDate: thisdata.termEndTimeFormattedDate
                });
            };
            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: 'projectTimeFormattedDate',
                    key: 'projectTimeFormattedDate'
                }, {
                    title: '项目名称',
                    dataIndex: 'projectName',
                    key: 'projectName'
                }, {
                    title: '期限',
                    dataIndex: 'termTimeFormattedDate',
                    key: 'termTimeFormattedDate',
                    render: (text) => {
                        return text[0] + ' - ' + text[1];
                    }
                }, {
                    title: '科研院所',
                    dataIndex: 'institution',
                    key: 'institution'
                }, {
                    title: '协议附件',
                    dataIndex: 'protocol',
                    key: 'protocol',
                    render: (text) => {
                        return <a onClick={newDownloadFile.bind(null, text[0], 'protocol', '/api/admin/downloadProtocol')}>{text[1]}</a>
                    }
                }
            ],
            dataSource: []
        };
    },
    componentWillMount() {
        this.loadOrgTechCenterDetail();
    },
    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/admin/deleteOrgTechCenterDetail",
            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();
        };
    },
    saveCenterDetail() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/disposeCenter",
            data: {
                uid: this.props.data.uid,
                id: this.state.cid,
                principal: this.state.principal,
                systemUrl: this.state.systemUrl,
                systemCatalog: this.state.systemCatalog,
                foundingTimeFormattedDate: this.state.foundingTime,
                comment: this.state.comment,
                centerName: this.state.centerName
            }
        }).done((data) => {
            if (!data.error.length) {
                message.success('保存成功！');
                this.loadOrgTechCenterDetail();
            } else {
                message.warning(data.error[0].message);
            };
            this.setState({
                loading: false,
            });
        });
    },
    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>
                    <span className="proportion"> 是否已完成：</span>
                    <Switch
                        checked={this.state.proportion && this.state.proportion.institution == 1 ? true : false}
                        checkedChildren={'已完成'}
                        unCheckedChildren={'未完成'}
                        onChange={(e) => {
                            e ? this.state.proportion.institution = 1 : this.state.proportion.institution = 0;
                            saveProportion(this.state.proportion.id, this.props.data.uid, 'institution', this.state.proportion.institution);
                            this.setState({ proportion: this.state.proportion });
                        }} />
                </div>
                <div className="clearfix">
                    <div className="orgTech-item">
                        <span>研发部门名称: </span>
                        <Input
                            value={this.state.centerName}
                            onChange={(e) => { this.setState({ centerName: e.target.value }); }}
                        />
                        <span>成立时间: </span>
                        <DatePicker
                            allowClear={false}
                            value={this.state.foundingTime ? moment(this.state.foundingTime) : undefined}
                            onChange={(date, dateString) => { this.setState({ foundingTime: dateString }); }}
                        />
                        <span>负责人: </span>
                        <Input
                            value={this.state.principal}
                            onChange={(e) => { this.setState({ principal: e.target.value }); }}
                        />
                    </div>
                    <div className="orgTech-item">
                        <span>制度目录: </span>
                        <Input type='textarea' rows={6}
                            value={this.state.systemCatalog}
                            onChange={(e) => { this.setState({ systemCatalog: e.target.value }); }}
                        />
                    </div>
                    <div className="orgTech-item">
                        <span>备注: </span>
                        <Input type='textarea' rows={3}
                            value={this.state.comment}
                            onChange={(e) => { this.setState({ comment: e.target.value }); }}
                        />
                    </div>
                </div>
                <div className="half-item">
                    <p>制度上传: (上传 zip 或者 rar 文件)</p>
                    <div style={{ margin: '10px 0' }}>
                        <Upload
                            name="ratepay"
                            action={globalConfig.context + "/api/admin/uploadInstitution"}
                            data={{ 'sign': 'institution', 'uid': this.props.data.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.systemUrl = 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.systemUrl ? <a onClick={newDownloadFile.bind(null, this.state.cid, 'institution', '/api/admin/downloadInstitution')}>{this.state.systemDownloadFileName}</a> : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传！</span>}</p>
                    </div>
                </div>
                <Button type='primary' onClick={this.saveCenterDetail} style={{ marginBottom: '10px' }}>保存</Button>
                <div className="content-title">
                    <span>产学研情况</span>
                </div>
                <div className="user-search">
                    <p>
                        <Button style={{ background: "#ea0862", border: "none", color: "#fff" }}
                            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>
                <CenterListDesc
                    cid={this.state.cid}
                    uid={this.props.data.uid}
                    data={this.state.RowData}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default CenterList;