import React from 'react';
import { Icon, Button, Input, Select, Spin, Table, Switch, DatePicker, message, Upload, Modal } from 'antd';
import { patentTypeList, patentStateList, provinceArr } from '../../../dataDic.js';
import { getTime, getPatentState, beforeUploadFile, companySearch, getSearchUrl } from '../../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './comprehensive.less';
import PatentAdd from './comPatentAdd.jsx';
import PatentDesc from './comPatentDesc.jsx';

const Patent = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/patentList",
            data: {
                page: pageNo || 1,
                pageSize: this.state.pagination.pageSize || null,
                serialNumber: this.state.number || null,
                patentNumber: this.state.patentNumber || null,
                patentName: this.state.patentName || null,
                locationProvince: this.state.province || null,
                uid: this.state.unitId || null,
                patentCatagory: this.state.patentType || null,
                patentState: this.state.patentState || null,
                createTime: this.state.createTime || null,
                patentApplicationDate: this.state.acceptTime || null,
                authorizedDate: this.state.authTime || null,
            },
            success: function (data) {
                if (data.error.length || !data.data || !data.data.list) {
                    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,
                        pid: thisdata.id,
                        oid: thisdata.oid,
                        uid: thisdata.uid,
                        number: thisdata.serialNumber || '',
                        patentNumber: thisdata.patentNumber || '',
                        unitName: thisdata.unitName || '',
                        patentName: thisdata.patentName || '',
                        patentCatagory: thisdata.patentCatagory || '0',
                        patentState: thisdata.patentState || '0',
                        patentField: thisdata.patentField || '0',
                        patentDes: thisdata.patentDes || '',

                        patentProryStatementUrl: thisdata.patentProryStatementUrl, //专利代理委托书
                        patentWritingUrl: thisdata.patentWritingUrl, //专利稿件
                        authorizationNoticeUrl: thisdata.authorizationNoticeUrl, //授权通知书
                        patentCertificateUrl: thisdata.patentCertificateUrl, //专利证书
                        lastYearTaxReportUrl: thisdata.lastYearTaxReportUrl, //上年度纳税表

                        patentProryStatementDownloadFileName: thisdata.patentProryStatementDownloadFileName, //专利代理委托书
                        patentWritingDownloadFileName: thisdata.patentWritingDownloadFileName, //专利稿件
                        authorizationNoticeDownloadFileName: thisdata.authorizationNoticeDownloadFileName, //授权通知书
                        patentCertificateDownloadFileName: thisdata.patentCertificateDownloadFileName, //专利证书
                        lastYearTaxReportDownloadFileName: thisdata.lastYearTaxReportDownloadFileName, //上年度纳税表

                        startTime: thisdata.patentApplicationDate,
                        endTime: thisdata.authorizedDate,
                        orgCode: thisdata.orgCode,
                        province: thisdata.locationProvince,
                        companyAddress: thisdata.locationProvince || thisdata.locationCity || thisdata.locationArea ? thisdata.locationProvince + '/' + thisdata.locationCity + '/' + thisdata.locationArea : '',
                        companyContacts: thisdata.contacts, //联系人
                        firstInventorName: thisdata.firstInventorName,
                        firstInventorNationality: thisdata.firstInventorNationality, //国籍
                        firstInventorIdNumber: thisdata.firstInventorIdNumber,   //id
                        firstInventorIsPublish: thisdata.firstInventorIsPublish, //是否公布
                        secondInventorName: thisdata.secondInventorName,
                        secondInventorNationality: thisdata.secondInventorNationality,
                        secondInventorIsPublish: thisdata.secondInventorIsPublish,
                        thirdInventorName: thisdata.thirdInventorName,
                        thirdInventorNationality: thisdata.thirdInventorNationality,
                        thirdInventorIsPublish: thisdata.thirdInventorIsPublish,
                        createTime: thisdata.createTime,   //派单日
                        author: thisdata.author, //撰写人
                        office: thisdata.office, //事务所
                        principal: thisdata.principal, //负责人
                        founder: thisdata.founder, //创建人
                        techPrincipal:thisdata.techPrincipal //技术员
                    });
                };
                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));
    },
    getOptionList() {
        this.setState({
            loading: true
        });
        $.when($.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getUnitNames",
            data: { "pid": this.state.xid },
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/getPrincipal"
        }), $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/patentStatus"
        })).done((data1, data2, data3) => {
            let _me = this;
            if (!data1[0].data) {
                if (data1[0].error.length) {
                    message.warning(data1[0].error[0].message);
                };
            } else {
                for (var item in data1[0].data) {
                    _me.state.companyOption.push(
                        <Select.Option value={item} key={item}>{data1[0].data[item]}</Select.Option>
                    )
                };
            };
            if (!data2[0].data) {
                if (data2[0].error.length) {
                    message.warning(data2[0].error[0].message);
                };
            } else {
                _me.state.adminOption = [];
                for (var item in data2[0].data) {
                    _me.state.adminOption.push(
                        <Select.Option value={item} key={item}>{data2[0].data[item]}</Select.Option>
                    )
                };
            };
            if (!data3[0].data) {
                if (data3[0].error && data3[0].error.length) {
                    message.warning(data3[0].error[0].message);
                };
            } else {
                _me.state.patentStateOption = [];
                for (var item in data3[0].data) {
                    _me.state.patentStateOption.push(
                        <Select.Option value={item} key={item}>{data3[0].data[item]}</Select.Option>
                    )
                };
            };
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            createTime: [],
            acceptTime: [],
            authTime: [],
            patentTypeOption: [],
            patentStateOption: [],
            companyOption: [],
            provinceOption: [],
            searchMore: true,
            data: [],
            loading: false,
            visible: false,
            selectedRowKeys: [],
            selectedRows: [],
            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: 'number',
                    key: 'number',
                }, {
                    title: '申请号/专利号',
                    dataIndex: 'patentNumber',
                    key: 'patentNumber',
                }, {
                    title: '事务所',
                    dataIndex: 'office',
                    key: 'office',
                }, {
                    title: '省份',
                    dataIndex: 'province',
                    key: 'province',
                }, {
                    title: '公司名称',
                    dataIndex: 'unitName',
                    key: 'unitName',
                }, {
                    title: '专利名称',
                    dataIndex: 'patentName',
                    key: 'patentName',
                }, {
                    title: '专利状态',
                    dataIndex: 'patentState',
                    key: 'patentState',
                    render: text => { return getPatentState(text) },
                }, {
                    title: '派单日',
                    dataIndex: 'createTime',
                    key: 'createTime',
                    render: text => { return getTime(text) },
                }, {
                    title: '申请日',
                    dataIndex: 'startTime',
                    key: 'startTime',
                    render: text => { return getTime(text) },
                }, {
                    title: '授权日',
                    dataIndex: 'endTime',
                    key: 'endTime',
                    render: text => { return getTime(text) },
                }, {
                    title: '创建人',
                    dataIndex: 'founder',
                    key: 'founder'
                },{
                    title: '技术员',
                    dataIndex: 'techPrincipal',
                    key: 'techPrincipal',
                }
            ],
            dataSource: []
        };
    },
    componentWillMount() {
        let _me = this;
        patentTypeList.map(function (item) {
            _me.state.patentTypeOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        patentStateList.map(function (item) {
            _me.state.patentStateOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        provinceArr.map(function (item) {
            _me.state.provinceOption.push(
                <Select.Option value={item} key={item}>{item}</Select.Option>
            )
        });
        if (window.location.search) {
            let theArr = getSearchUrl(window.location.search);
            if (theArr.length > 1) {
                let theObj = {};
                theObj.pid = theArr[0];
                theObj.uid = theArr[1];
                if (theObj.pid != 'null' && theObj.uid != 'null') {
                    this.tableRowClick(theObj);
                };
            } else if (theArr.length == 1) {
                this.state.unitId = theArr[0];
            };
        };
        this.loadData();
        this.getOptionList();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true
        });
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.number = undefined;
        this.state.patentNumber = undefined;
        this.state.province = undefined;
        this.state.unitId = undefined;
        this.state.patentType = undefined;
        this.state.patentName = undefined;
        this.state.patentState = undefined;
        this.state.createTime = [];
        this.state.acceptTime = [];
        this.state.authTime = [];
        this.state.searchKey = undefined;
        this.state.searchValue = undefined;
        this.loadData();
    },
    exportComposite() {
        window.open(globalConfig.context + "/api/admin/patent/exportComposite" +
            "?" + "serialNumber" + "=" + this.state.number +
            "&" + "patentNumber" + "=" + this.state.patentNumber +
            "&" + "patentName" + "=" + this.state.patentName +
            "&" + "locationProvince" + "=" + this.state.locationProvince +
            "&" + "uid" + "=" + this.state.unitId +
            "&" + "patentCatagory" + "=" + this.state.patentCatagory +
            "&" + "patentState" + "=" + this.state.patentState +
            "&" + "createTime" + "=" + this.state.createTime +
            "&" + "patentApplicationDate" + "=" + this.state.acceptTime +
            "&" + "author" + "=" + this.state.author);
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    searchSelect(e) {
        let _me = this;
        this.setState({
            searchValue: e.target.value
        });
        switch (_me.state.searchKey) {
            case "patentNumber":
                _me.state.patentNumber = e.target.value;
                _me.state.number = '';
                _me.state.patentName = '';
                break;
            case "serialNumber":
                _me.state.number = e.target.value;
                _me.state.patentNumber = '';
                _me.state.patentName = '';
                break;
            case "patentName":
                _me.state.patentNumber = '';
                _me.state.number = '';
                _me.state.patentName = e.target.value;
                break;
        }
    },
    delectRow() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.pid) {
                deletedIds.push(rowItem.pid)
            }
        }
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/delete",
            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));
    },
    circulation() {
        let deletedIds = [];
        for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];
            if (rowItem.pid) {
                deletedIds.push(rowItem.pid)
            }
        }
        this.setState({
            selectedRowKeys: [],
            loading: deletedIds.length > 0
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/patent/circulation",
            data: {
                ids: deletedIds,
                principal: this.state.principal,
                state: this.state.status,
                comment: this.state.comment,
                recordTimeFormattedDate: this.state.recordTime
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('保存成功！');
                this.setState({
                    loading: false,
                    visible: false
                });
            } else {
                message.warning(data.error[0].message);
            };
            this.loadData();
        }.bind(this));
    },
    showModal() {
        this.setState({
            visible: true,
            principal: undefined,
            status: undefined,
            comment: undefined,
            recordTime: undefined
        });
    },
    handleCancel() {
        this.setState({ visible: false });
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows,
                    selectedRowKeys: selectedRowKeys
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        const { MonthPicker, RangePicker } = DatePicker;
        return (
            <div className="patent-content" >
                <div className="content-title">
                    <span>专利综合管理</span>
                    <div className="patent-addNew">
                        <Upload style={{ float: 'right' }}
                            name="ratepay"
                            fileList={this.state.fileList}
                            action={globalConfig.context + "/api/admin/patent/uploadTemplate"}
                            data={{ 'sign': 'patent_prory_statement' }}
                            beforeUpload={beforeUploadFile}
                            onChange={(info) => {
                                if (info.file.status === 'done') {
                                    if (!info.file.response.error.length) {
                                        if (!info.file.response.error.length) {
                                            message.success(`${info.file.name} 文件上传成功！`);
                                        } else {
                                            message.warning(info.file.response.error[0].message);
                                            return;
                                        };
                                    } else {
                                        message.warning(info.file.response.error[0].message);
                                    };
                                } else if (info.file.status === 'error') {
                                    message.error(`${info.file.name} 文件上传失败。`);
                                };
                                this.setState({ fileList: info.fileList.slice(-1) });
                            }}
                        >
                            <Button>上传专利代理委托书模板 <Icon type="upload" /></Button>
                        </Upload>
                    </div>
                    <PatentAdd closeDesc={this.closeDesc} />
                </div>
                <div className="patent-query">
                    <Select placeholder="请选择" value={this.state.searchKey} style={{ width: 160 }} onChange={(e) => { this.setState({ searchKey: e, searchValue: '' }); }}>
                        <Select.Option value="patentNumber">专利号</Select.Option>
                        <Select.Option value="serialNumber">编号</Select.Option>
                        <Select.Option value="patentName">专利名称</Select.Option>
                    </Select>
                    <Input value={this.state.searchValue} style={{ width: 160 }} onChange={this.searchSelect} />
                    <Select placeholder="专利状态" value={this.state.patentState} style={{ width: 160 }} onChange={(e) => { this.setState({ patentState: e }); }}>{this.state.patentStateOption}</Select>
                    <span>更多搜索<Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
                    <Button style={{ marginLeft: '20px' }}
                        type="primary"
                        onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <Button type="ghost" onClick={this.exportComposite}>导出</Button>
                    <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
                        disabled={!hasSelected}
                        onClick={this.delectRow}>删除<Icon type="minus" /></Button>
                    <Button disabled={!hasSelected} style={{ marginTop: '10px' }}
                        type="ghost" onClick={this.showModal}>专利批量流转<Icon type="retweet" /></Button>
                    <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>
                        <div>
                            <span>派单日：</span>
                            <RangePicker style={{ width: '240px' }}
                                allowClear={false}
                                value={[this.state.createTime[0] ? moment(this.state.createTime[0]) : null,
                                this.state.createTime[1] ? moment(this.state.createTime[1]) : null]}
                                onChange={(date, dateString) => { this.setState({ createTime: dateString }) }} />
                            <span>申请日：</span>
                            <RangePicker style={{ width: '240px' }}
                                allowClear={false}
                                value={[this.state.acceptTime[0] ? moment(this.state.acceptTime[0]) : null,
                                this.state.acceptTime[1] ? moment(this.state.acceptTime[1]) : null]}
                                onChange={(date, dateString) => { this.setState({ acceptTime: dateString }) }} />
                            <Select placeholder="选择省份"
                                showSearch
                                filterOption={companySearch}
                                style={{ width: 100 }}
                                value={this.state.province}
                                onChange={(e) => { this.setState({ province: e }); }}>
                                {this.state.provinceOption}
                            </Select>
                            <Select placeholder="选择公司"
                                style={{ width: 200 }}
                                showSearch
                                filterOption={companySearch}
                                value={this.state.unitId}
                                onChange={(e) => { this.setState({ unitId: e }); }}>
                                {this.state.companyOption}
                            </Select>
                        </div>
                    </div>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            rowSelection={rowSelection}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <PatentDesc
                    data={this.state.RowData}
                    adminOption={this.state.adminOption}
                    patentStateOption={this.state.patentStateOption}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
                <Modal title="专利批量流转" visible={this.state.visible}
                    onCancel={this.handleCancel}
                    width='800px'
                    footer={[
                        <Button key="submit" type="primary" size="large" onClick={this.circulation}>保存</Button>,
                        <Button key="back" type="ghost" size="large" onClick={this.handleCancel}>取消</Button>,
                    ]} className="patent-desc-content">
                    <div className="clearfix">
                        <div className="widthThird">
                            <span>状态流转：</span>
                            <Select placeholder='请选择状态'
                                value={this.state.status}
                                style={{ width: 150 }}
                                onChange={(e) => { this.setState({ status: e }); }}>
                                {this.state.patentStateOption}
                            </Select>
                        </div>
                        <p className="widthThird">
                            <span>处理时间：</span>
                            <DatePicker
                                value={this.state.recordTime ? moment(this.state.recordTime) : undefined}
                                format="YYYY-MM-DD HH:mm:ss"
                                onChange={(data, dataString) => { this.setState({ recordTime: dataString }); }} />
                        </p>
                        <div className="widthThird">
                            <span>负责人：</span>
                            <Select placeholder='请填写负责人'
                                value={this.state.principal}
                                style={{ width: 150 }}
                                onChange={(e) => { this.setState({ principal: e }); }}>
                                {this.state.adminOption}
                            </Select>
                        </div>
                    </div>
                    <div>
                        <span>备注：</span>
                        <Input value={this.state.comment} placeholder='请填写备注' style={{ width: 400 }} onChange={(e) => { this.setState({ comment: e.target.value }); }} />
                    </div>
                </Modal>
            </div >
        );
    }
});

export default Patent;
