import React from 'react';
import { Icon, Modal, message, Spin, Steps, Input, Select, Upload, DatePicker, Button, Table } from 'antd';
import './comprehensive.less';
import ajax from 'jquery/src/ajax/xhr.js';
import moment from 'moment';
import $ from 'jquery/src/ajax';
import { patentTypeList, patentStateList, industryList } from '../../../dataDic.js';
import { getBase64, beforeUpload, getPatentState, getTime, newDownloadFile, getPreview, companySearch } from '../../../tools.js';

class Avatar extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            imageUrl: ''
        }
    }
    handleChange(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.props.urlData(info.file.response.data);
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 文件上传失败。`);
        };
        this.setState({ fileList: info.fileList.slice(-1) });
    }
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.fileList = [];
        };
    }
    render() {
        return (
            <Upload className="upload-file"
                name="avatar"
                fileList={this.state.fileList}
                action={this.props.name == "patent_prory_statement" ? globalConfig.context + "/api/admin/patent/uploadProry" : globalConfig.context + "/api/admin/patent/upload"}
                data={{ 'sign': this.props.name, 'uid': this.props.uid, 'id': this.props.id }}
                beforeUpload={beforeUpload}
                onChange={this.handleChange.bind(this)}
            >
                <Button><Icon type="upload" /> 点击上传 </Button>
            </Upload>
        );
    }
};

const PatentDesc = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            patentTypeOption: [],
            patentFieldOption: [],
            industryOption: [],
            stateTable: [],
            stateColumns: [{
                title: '申请状态',
                dataIndex: 'state',
                key: 'state',
                render: (text) => { return getPatentState(text) }
            }, {
                title: '处理时间',
                dataIndex: 'recordTimeFormattedDate',
                key: 'recordTimeFormattedDate',
            }, {
                title: '负责人',
                dataIndex: 'principal',
                key: 'principal',
            }, {
                title: '操作人',
                dataIndex: 'operator',
                key: 'operator',
            }, {
                title: '备注',
                dataIndex: 'comment',
                key: 'comment',
            }]
        };
    },
    loadData(uid) {
        this.setState({
            loading: true
        });
        $.when($.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/detail",
            data: { "pid": this.state.xid },
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/logs",
            data: { "pid": this.state.xid }
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/lastYearTax",
            data: { "uid": uid || this.props.data.uid, "sign": "last_year_ratepay" }
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/getAuthor"
        })).done((data1, data2, data3, data4) => {
            let _me = this;
            if (!data1[0].data) {
                if (data1[0].error.length) {
                    message.warning(data1[0].error[0].message);
                };
            } else {
                this.state.data = data1[0].data;
                this.state.firstInventorName = data1[0].data.firstInventorName;
                this.state.firstInventorIdNumber = data1[0].data.firstInventorIdNumber;
                this.state.secondInventorName = data1[0].data.secondInventorName;
                this.state.thirdInventorName = data1[0].data.thirdInventorName;
                this.state.patentDes = data1[0].data.patentDes;
                this.state.patentName = data1[0].data.patentName;
                this.state.patentNumber = data1[0].data.patentNumber;
                this.state.office = data1[0].data.office;
                this.state.patentCatagory = data1[0].data.patentCatagory;
                this.state.patentState = data1[0].data.patentState;
                this.state.patentField = data1[0].data.patentField;
                this.state.contacts = data1[0].data.contacts;
                this.state.author = data1[0].data.author;
                this.state.uid = data1[0].data.uid;
                this.state.id = data1[0].data.id;
            };
            if (!data2[0].data) {
                if (data2[0].error.length) {
                    message.warning(data2[0].error[0].message);
                };
            } else {
                _me.state.stateTable = [];
                data2[0].data.map(function (item) {
                    _me.state.stateTable.push({
                        comment: item.comment,
                        id: item.id,
                        operator: item.operator,
                        pid: item.pid,
                        principal: item.principal,
                        recordTime: item.recordTime,
                        recordTimeFormattedDate: item.recordTimeFormattedDate,
                        state: item.state,
                    });
                });
            };
            if (!data3[0].data) {
                if (data3[0].error.length) {
                    message.warning(data3[0].error[0].message);
                };
            } else {
                this.state.lastYearTaxReportId = data3[0].data.id
            };
            let theArr = [];
            if (!data4[0].data) {
                if (data4[0].error.length) {
                    message.warning(data4[0].error[0].message);
                };
            } else {
                for (var item in data4[0].data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data4[0].data[item]}</Select.Option>
                    )
                };
                this.setState({
                    authorOption: theArr
                });
            };
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getContactsList(theUid) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getContacts",
            data: {
                uid: theUid || this.state.uid
            },
            success: function (data) {
                let theOption = [];
                if (data.error.length || !data.data) {
                    return;
                };
                for (let item in data.data) {
                    let theData = data.data[item];
                    theOption.push(
                        <Select.Option value={item} key={theData}>{theData}</Select.Option>
                    );
                };
                this.setState({
                    contactsOption: theOption
                });
            }.bind(this),
        });
    },
    getOption() {
        let _me = this;
        _me.state.patentTypeOption = [];
        _me.state.industryOption = [];
        patentTypeList.map(function (item) {
            _me.state.patentTypeOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        industryList.map(function (item) {
            _me.state.industryOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleOk() {
        this.setState({
            visible: true,
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/update",
            data: {
                "id": this.state.xid,
                "uid": this.state.uid,
                "patentNumber": this.state.patentNumber,
                "patentName": this.state.patentName,
                "patentCatagory": this.state.patentCatagory,
                "patentField": this.state.patentField,
                "patentDes": this.state.patentDes,
                "contacts": this.state.contacts,
                "office": this.state.office,
                "patentWritingUrl": this.state.patentWritingUrl,
                "authorizationNoticeUrl": this.state.authorizationNoticeUrl,
                "patentCertificateUrl": this.state.patentCertificateUrl,
                "patentProryStatementUrl": this.state.patentProryStatementUrl,
                "pState": this.props.data.patentState,
                "firstInventorName": this.state.firstInventorName,
                "firstInventorIdNumber": this.state.firstInventorIdNumber,
                "secondInventorName": this.state.secondInventorName,
                "thirdInventorName": this.state.thirdInventorName,
                "state": this.state.patentStateAdd,
                "recordTimeFormattedDate": this.state.recordTime,
                "principal": this.state.adminName,
                "comment": this.state.comment,
                "author": this.state.author
            }
        }).done(function (data) {
            if (data.error && !data.error.length) {
                message.success('保存成功！');
                this.props.closeDesc(false, true);
            } else {
                message.warning(data.error[0].message);
            }
        }.bind(this)).always(function () {
            this.setState({
                loading: false,
            });
        }.bind(this));
    },
    checkPatentProcess() {
        if (this.state.patentStateAdd || this.state.adminName || this.state.recordTime) {
            if (this.state.patentStateAdd && this.state.adminName && this.state.recordTime)
            { this.handleOk() } else {
                message.warning("请填写完整的状态流转信息！");
                return;
            }
        } else {
            this.handleOk()
        };
    },
    componentWillMount() {
        this.getOption();
    },
    componentWillReceiveProps(nextProps) {
        this.state.patentStateAdd = undefined;
        this.state.adminName = undefined;
        this.state.recordTime = undefined;
        this.state.comment = undefined;
        if (nextProps.data && !this.state.visible && nextProps.showDesc) {
            this.state.xid = nextProps.data.id;
            this.loadData(nextProps.data.uid);
            this.getContactsList(nextProps.data.uid);
        };
        this.state.visible = nextProps.showDesc;
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    getPatentWritingUrl(e) {
        this.state.patentWritingUrl = e;
    },
    getAuthorizationNoticeUrl(e) {
        this.state.authorizationNoticeUrl = e;
    },
    getPatentCertificateUrl(e) {
        this.state.patentCertificateUrl = e;
    },
    getPatentProryStatementUrl(e) {
        this.state.patentProryStatementUrl = e;
    },
    render() {
        const Step = Steps.Step;
        const theData = this.state.data;

        if (this.state.data) {
            return (
                <div className="patent-desc">
                    <Spin spinning={this.state.loading} className='spin-box'>
                        <Modal maskClosable={false} title="专利详情" visible={this.state.visible}
                            onOk={this.checkPatentProcess} onCancel={this.handleCancel}
                            width='1000px'
                            footer={[
                                <Button key="submit" type="primary" size="large" onClick={this.checkPatentProcess}>保存</Button>,
                                <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>取消</Button>,
                            ]}
                            className="patent-desc-content">
                            <div>
                                <p className="widthHalf"><span>公司名称：</span>{theData.unitName}</p>
                                <div className="widthHalf">
                                    <span>联系人：</span>
                                    <Select placeholder="选择联系人"
                                        style={{ width: 200 }}
                                        value={this.state.contacts}
                                        onChange={(e) => { this.setState({ contacts: e }); }} >
                                        {this.state.contactsOption}
                                    </Select>
                                </div>
                            </div>
                            <p>专利状态流转记录：</p>
                            <Table
                                style={{ margin: '10px 0', background: "#eee" }}
                                pagination={false}
                                dataSource={this.state.stateTable}
                                columns={this.state.stateColumns} />
                            <div className="clearfix" style={{ paddingLeft: '4px', paddingTop: '20px', background: "#eee" }}>
                                <div className="widthHalf">
                                    <span>状态流转：</span>
                                    <Select placeholder='请选择状态'
                                        value={this.state.patentStateAdd}
                                        style={{ width: 150 }}
                                        onChange={(e) => { this.setState({ patentStateAdd: e }); }}>
                                        {this.props.patentStateOption}
                                    </Select>
                                </div>
                                <div className="widthHalf">
                                    <span>处理时间：</span>
                                    <i>
                                        <DatePicker
                                            value={this.state.recordTime ? moment(this.state.recordTime) : undefined}
                                            format="YYYY-MM-DD HH:mm:ss"
                                            onChange={(data, dataString) => { this.setState({ recordTime: dataString }); }} />
                                    </i>
                                </div>
                                <div className="widthHalf">
                                    <span>负责人：</span>
                                    <Select placeholder='请填写负责人'
                                        value={this.state.adminName}
                                        showSearch
                                        filterOption={companySearch}
                                        style={{ width: 200 }}
                                        onChange={(e) => { this.setState({ adminName: e }); }}>
                                        {this.props.adminOption}
                                    </Select>
                                </div>
                                <div className="widthHalf">
                                    <span>备注：</span>
                                    <Input value={this.state.comment} placeholder='请填写备注' onChange={(e) => { this.setState({ comment: e.target.value }); }} />
                                </div>
                            </div>
                            <div>
                                <p className="widthHalf"><span>事务所：</span><Input value={this.state.office} onChange={(e) => { this.setState({ office: e.target.value }); }} /></p>
                            </div>
                            <div>
                                <p className="widthHalf"><span>编号：</span>{theData.serialNumber}</p>
                                <p className="widthHalf"><span>申请号/专利号：</span><Input value={this.state.patentNumber} onChange={(e) => { this.setState({ patentNumber: e.target.value }); }} /></p>
                            </div>
                            <div>
                                <p className="widthHalf"><span>专利名称：</span><Input value={this.state.patentName} onChange={(e) => { this.setState({ patentName: e.target.value }); }} /></p>
                                <div className="widthHalf"><span>专利类型：</span>
                                    <Select value={this.state.patentCatagory}
                                        style={{ width: 260 }}
                                        onChange={(e) => { this.setState({ patentCatagory: e }); }}>
                                        {this.state.patentTypeOption}
                                    </Select>
                                </div>
                            </div>
                            <div>
                                <p className="widthHalf"><span>专利状态：</span>{getPatentState(theData.patentState)}</p>
                                <div className="widthHalf"><span>所属行业：</span>
                                    <Select
                                        value={this.state.patentField}
                                        style={{ width: 260 }}
                                        onChange={(e) => { this.setState({ patentField: e }); }}>
                                        {this.state.industryOption}
                                    </Select>
                                </div>
                            </div>
                            <div>
                                <span>专利简介：</span>
                                <Input type="textarea"
                                    placeholder="多行输入"
                                    value={this.state.patentDes}
                                    onChange={(e) => { this.setState({ patentDes: e.target.value }); }}
                                    rows={6} />
                            </div>
                            <div>
                                <p>第一发明人：</p>
                                <p className="widthThird">
                                    <span>姓名：</span>
                                    <Input
                                        style={{ width: 150 }}
                                        value={this.state.firstInventorName}
                                        onChange={(e) => { this.setState({ firstInventorName: e.target.value }); }} />
                                </p>
                                <p className="widthThird">
                                    <span>身份证：</span>
                                    <Input
                                        style={{ width: 150 }}
                                        value={this.state.firstInventorIdNumber}
                                        onChange={(e) => { this.setState({ firstInventorIdNumber: e.target.value }); }} />
                                </p>
                                <p className="widthThird"><span>国籍：</span>中国</p>
                            </div>
                            <div style={theData.secondInventorName === '' ? { display: 'none' } : {}}>
                                <p>第二发明人：</p>
                                <p className="widthThird">
                                    <span>姓名：</span>
                                    <Input
                                        style={{ width: 150 }}
                                        value={this.state.secondInventorName}
                                        onChange={(e) => { this.setState({ secondInventorName: e.target.value }); }} />
                                </p>
                                <p className="widthThird"><span>国籍：</span>中国</p>
                            </div>
                            <div style={theData.thirdInventorName === '' ? { display: 'none' } : {}}>
                                <p>第三发明人：</p>
                                <p className="widthThird">
                                    <span>姓名：</span>
                                    <Input
                                        style={{ width: 150 }}
                                        value={this.state.thirdInventorName}
                                        onChange={(e) => { this.setState({ thirdInventorName: e.target.value }); }} />
                                </p>
                                <p className="widthThird"><span>国籍：</span>中国</p>
                            </div>
                            <div className="clearfix">
                                <div>材料管理：
                                    {theData.patentWritingUrl ?
                                        <p className="download-file">
                                            <a onClick={newDownloadFile.bind(null, this.state.xid, "patent_writing", "/api/admin/patent/download")}>专利稿件</a>
                                            {theData.confirmState == '0' ?
                                                <Button onClick={this.confirmButton}>确认稿件</Button> : <span></span>
                                            }
                                            <a onClick={() => {
                                                var newTab = window.open('about:blank'); getPreview(this.state.data.id, 'patent', 'patent_writing', function (data) { newTab.location.href = data; });
                                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /> </a>
                                        </p> :
                                        <p><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />专利稿件未上传</p>
                                    }
                                    {theData.authorizationNoticeUrl ?
                                        <p className="download-file">
                                            <a onClick={newDownloadFile.bind(null, this.state.xid, "authorization_notice", "/api/admin/patent/download")}>授权通知书</a>
                                            <a onClick={() => {
                                                var newTab = window.open('about:blank'); getPreview(this.state.data.id, 'patent', 'authorization_notice', function (data) { newTab.location.href = data; });
                                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /> </a>
                                        </p> :
                                        <p><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />授权通知书未上传</p>
                                    }
                                    {theData.patentCertificateUrl ?
                                        <p className="download-file">
                                            <a onClick={newDownloadFile.bind(null, this.state.xid, "patent_certificate", "/api/admin/patent/download")}>专利证书</a>
                                            <a onClick={() => {
                                                var newTab = window.open('about:blank'); getPreview(this.state.data.id, 'patent', 'patent_certificate', function (data) { newTab.location.href = data; });
                                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /> </a>
                                        </p> :
                                        <p><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />专利证书未上传</p>
                                    }
                                    {theData.patentProryStatementUrl ?
                                        <p className="download-file">
                                            <a onClick={newDownloadFile.bind(null, this.state.xid, "patent_prory_statement", "/api/admin/patent/download")}>专利代理委托书</a>
                                            <a onClick={() => {
                                                var newTab = window.open('about:blank'); getPreview(this.state.data.id, 'patent', 'patent_prory_statement', function (data) { newTab.location.href = data; });
                                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /> </a>
                                        </p> :
                                        <p><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />专利代理委托书未上传</p>
                                    }
                                    {this.state.lastYearTaxReportId ?
                                        <p className="download-file">
                                            <a onClick={newDownloadFile.bind(null, this.state.lastYearTaxReportId, "last_year_ratepay", "/api/admin/patent/downloadRatepay")}>上年度纳税报表</a>
                                            <a onClick={() => {
                                                var newTab = window.open('about:blank'); getPreview(this.state.lastYearTaxReportId, 'patent', 'last_year_ratepay', function (data) { newTab.location.href = data; });
                                            }}><Icon style={{ fontSize: '16px' }} type="eye-o" /> </a>
                                        </p> :
                                        <p><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />上年度纳税报表未上传</p>
                                    }
                                </div>
                                <Avatar visible={this.state.visible} urlData={this.getPatentWritingUrl} name='patent_writing' uid={theData.uid} id={theData.id} />
                                <Avatar visible={this.state.visible} urlData={this.getAuthorizationNoticeUrl} name='authorization_notice' uid={theData.uid} id={theData.id} />
                                <Avatar visible={this.state.visible} urlData={this.getPatentCertificateUrl} name='patent_certificate' uid={theData.uid} id={theData.id} />
                                <Avatar visible={this.state.visible} urlData={this.getPatentProryStatementUrl} name='patent_prory_statement' uid={theData.uid} id={theData.id} />
                            </div>
                            <div className="avatar-text"><span>专利稿件上传</span><span>授权通知书上传</span><span>专利证书上传</span><span>专利代理委托书上传</span></div>
                            <div className="widthHalf">
                                <span>撰写人：</span>
                                <Select
                                    style={{ width: 150 }}
                                    value={this.state.author}
                                    onChange={(e) => { this.setState({ author: e }); }} >
                                    {this.state.authorOption}
                                </Select>
                            </div>
                        </Modal>
                    </Spin>
                </div>
            );
        } else {
            return <div></div>
        }
    },
});
export default PatentDesc;