import React from 'react';
import { Icon, Button, Input, Select, Spin, Table, DatePicker, message, Cascader, Switch, Modal } from 'antd';
import { copyrightStateList } from '../../../dataDic.js';
import { provinceSelect, getProvince } from '../../../NewDicProvinceList';
import { getTime, companySearch, getCopyrightState, getInUrgentTime, getVacations, getSearchUrl } from '../../../tools.js';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import PatentAdd from './comPatentAdd.jsx';
import PatentChange from './comPatentChange.jsx';

import moment from 'moment';
import './copyright.less';

const copyright = React.createClass({
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/copyright/list",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                province: this.state.province ? this.state.province[0] : undefined,
                uid: this.state.unitName,
                contractId: this.state.contractId,
                copyrightName: this.state.copyrightName,
                status: this.state.searchStatus,
                createTime: this.state.createTime,
                acceptTime: this.state.acceptTime
            },
            success: function (data) {
                this.state.data = [];
                if (!data.data || !data.data.list) {
                    message.warning(data.error[0].message);
                } else {
                    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,
                            province: thisdata.province,
                            unitName: thisdata.unitName,
                            serialNumber: thisdata.serialNumber,
                            contractNumber: thisdata.contractNumber,
                            createTime: thisdata.createTime,
                            acceptTime: thisdata.acceptTime,
                            principal: thisdata.principal,
                            contact: thisdata.contact,
                            copyrightName: thisdata.copyrightName,
                            copyrightNumber: thisdata.copyrightNumber,
                            status: thisdata.status,
                            comment: thisdata.comment,
                            workIssue: thisdata.workIssue,
                            outsource: thisdata.outsource,
                            inUrgent: thisdata.inUrgent,
                            expectTime: [thisdata.acceptTime, thisdata.inUrgent],
                            authorizedDate: thisdata.authorizedDate,
                            fisrtContact: thisdata.fisrtContact,
                            secondContact: thisdata.secondContact,
                            thirdContact: thisdata.thirdContact,
                            authorizedDateFormattedDate: thisdata.authorizedDateFormattedDate,
                            createTimeFormattedDate: thisdata.createTimeFormattedDate,
                            acceptTimeFormattedDate: thisdata.acceptTimeFormattedDate,
                            founder: thisdata.founder,
                            techPrincipal: thisdata.techPrincipal
                        });
                    };
                };
                this.state.pagination.defaultCurrent = 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));
    },
    getAuthorList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/copyright/getPrincipal",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                    return;
                };
                let _me = this;
                for (var item in data.data) {
                    _me.state.authorOption.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getSalesmanList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/salesman",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                    return;
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    salesmanOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getCompanyList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getUnitNames",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    return;
                };
                let _me = this;
                for (var item in data.data) {
                    _me.state.companyOption.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getStateList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/copyright/status",
            success: function (data) {
                let _me = this;
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        return;
                    };
                };
                _me.state.statusOption = [];
                for (var item in data.data) {
                    _me.state.statusOption.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            visible: false,
            RowData: {},
            stateOption: [],
            companyOption: [],
            authorOption: [],
            consultantOption: [],
            data: [],
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            showAdd: false,
            showDesc: false,
            searchMore: true,
            createTime: [],
            acceptTime: [],
            authTime: [],
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
            vacations: [],
            dataSource: []
        };
    },
    getContractList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/contract/serialNumber",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    return;
                };
                let theArr = [];
                for (let i = 0; i < data.data.length; i++) {
                    let item = data.data[i];
                    theArr.push(
                        <Select.Option value={item.contractId} key={item.contractId}>{item.serialNumber}</Select.Option>
                    );
                };
                this.setState({
                    contractListOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    componentWillMount() {
        let _me = this;
        copyrightStateList.map(function (item) {
            _me.state.stateOption.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.getAuthorList();
        this.getSalesmanList();
        this.getCompanyList();
        this.getStateList();
        this.getContractList();
        getVacations(function (data) { _me.setState({ vacations: data }); });
        if (window.location.search) {
            let theObj = getSearchUrl(window.location.search);
            if (theObj.rid) {
                theObj.id = theObj.rid;
                if (theObj.rid != 'null' && theObj.uid != 'null') {
                    this.tableRowClick(theObj);
                };
            } else {
                if (theObj.uid) {
                    this.state.unitName = theObj.uid;
                } else if (theObj.contractId) {
                    this.state.contractId = theObj.contractId;
                };
            };
        };
        this.loadData();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        if(index!=undefined){
        	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/copyright/delete",
            data: {
                id: 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();
        };
    },
    addClick() {
        this.setState({
            showAdd: true
        });
    },
    closeAdd(e, s) {
        this.state.showAdd = e;
        if (s) {
            this.loadData();
        };
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.province = undefined;
        this.state.unitName = undefined;
        this.state.copyrightName = undefined;
        this.state.searchStatus = undefined;
        this.state.contractId = undefined;
        this.state.createTime = [];
        this.state.acceptTime = [];
        this.state.authTime = [];
        this.loadData();
    },
    circulation() {
        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/copyright/circulation",
            data: {
                ids: deletedIds,
                principal: this.state.principal,
                status: 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 columns = [
            {
                title: '编号',
                dataIndex: 'serialNumber',
                key: 'serialNumber',
            }, {
                title: '省份',
                dataIndex: 'province',
                key: 'province',
                render: text => { return getProvince(text); }
            }, {
                title: '合同编号',
                dataIndex: 'contractNumber',
                key: 'contractNumber',
            }, {
                title: '公司名称',
                dataIndex: 'unitName',
                key: 'unitName',
            }, {
                title: '认证状态',
                dataIndex: 'status',
                key: 'status',
                render: (text) => { return getCopyrightState(text) }
            }, {
                title: '软著名称',
                dataIndex: 'copyrightName',
                key: 'copyrightName',
            }, {
                title: '加急天数',
                dataIndex: 'inUrgent',
                key: 'inUrgent',
                render: (text) => {
                    switch (text) {
                        case 0:
                            return '不加急(45个工作日)';
                        case 3:
                            return '3个工作日';
                        case 5:
                            return '5个工作日';
                        case 10:
                            return '6-10个工作日';
                        case 15:
                            return '11-15个工作日';
                        case 20:
                            return '16-20个工作日';
                        case 25:
                            return '21-25个工作日';
                        case 30:
                            return '26-30个工作日';
                        case 35:
                            return '31-35个工作日';
                    }
                }
            }, {
                title: '负责人',
                dataIndex: 'principal',
                key: 'principal',
            }, {
                title: '派单日',
                dataIndex: 'createTimeFormattedDate',
                key: 'createTimeFormattedDate',
            }, {
                title: '受理日',
                dataIndex: 'acceptTimeFormattedDate',
                key: 'acceptTimeFormattedDate',
            }, {
                title: '下证时间',
                dataIndex: 'expectTime',
                key: 'expectTime',
                render: (text, record) => {
                    if (record.authorizedDate) {
                        return record.authorizedDateFormattedDate
                    } else {
                        if (text[0]) {
                            if (text[1]) {
                                return getTime(getInUrgentTime(moment(text[0]), text[1], this.state.vacations)) + '(预计)'
                            } else {
                                return getTime(getInUrgentTime(moment(text[0]), 45, this.state.vacations)) + '(预计)'
                            }
                        };
                    }
                }
            }, {
                title: '创建人',
                dataIndex: 'founder',
                key: 'founder'
            }
        ];
        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="foster-box">
                <div className="foster-content">
                    <div className="content-title">
                        <span>软著申请管理</span>
                    </div>
                    <div className="foster-query">
                        <Cascader placeholder="选择省份"
                            style={{ width: 100, marginTop: "-4px" }}
                            value={this.state.province}
                            options={provinceSelect()}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ province: e }) }} />
                        <Select placeholder="选择公司"
                            style={{ width: 200 }}
                            value={this.state.unitName}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ unitName: e }) }}>
                            {this.state.companyOption}
                        </Select>
                        <Input style={{ width: 160 }}
                            placeholder="请输入软著名称"
                            value={this.state.copyrightName}
                            onChange={(e) => { this.setState({ copyrightName: e.target.value }); }} />
                        <Select placeholder="选择合同编号"
                            style={{ width: 120 }}
                            value={this.state.contractId}
                            showSearch
                            filterOption={companySearch}
                            onChange={(e) => { this.setState({ contractId: e }) }}>
                            {this.state.contractListOption}
                        </Select>
                        <Select style={{ width: 120 }}
                            value={this.state.searchStatus}
                            onChange={(e) => { this.setState({ searchStatus: e }) }}
                            placeholder="选择一个状态">{this.state.stateOption}</Select>
                        <span>更多搜索  <Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
                        <Button type="primary" onClick={this.search}>搜索</Button>
                        <Button onClick={this.reset}>重置</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' } : {}}>
                            <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 }) }} />
                        </div>
                    </div>
                    <div className="foster-table">
                        <Spin spinning={this.state.loading}>
                            <Table columns={columns}
                                rowSelection={rowSelection}
                                dataSource={this.state.dataSource}
                                pagination={this.state.pagination}
                                onRowClick={this.tableRowClick} />
                        </Spin>
                    </div>
                    <PatentChange
                        data={this.state.RowData}
                        authorOption={this.state.authorOption}
                        statusOption={this.state.statusOption}
                        showDesc={this.state.showDesc}
                        closeDesc={this.closeDesc} />
                    <Modal maskClosable={false} 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.statusOption}
                                </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.authorOption}
                                </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 >
            </div>
        );
    }
});

export default copyright;


// <PatentAdd
//     companyOption={this.state.companyOption}
//     salesmanOption={this.state.salesmanOption}
//     onClick={this.addClick}
//     closeAdd={this.closeAdd} />