import React from 'react';
import { AutoComplete, Icon, Button, Input, InputNumber, Select, Spin, Table, message, Modal, Row, Col, DatePicker } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './techDemand.less';
import { orderStatusList } from '../../dataDic.js';
import { befoFile, getSearchUrl, getOrderStatus, companySearch } from '../../tools.js';
import BatchImport from './batchImport';
import throttle from '../../throttle.js';

const DemandDetail = React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            columns: [
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: text => { return getOrderStatus(text) }
                }, {
                    title: '操作时间',
                    dataIndex: 'recordTimeFormattedDate',
                    key: 'recordTimeFormattedDate',
                }, {
                    title: '管理员',
                    dataIndex: 'operator',
                    key: 'operator',
                }, {
                    title: '备注',
                    dataIndex: 'comment',
                    key: 'comment',
                }
            ],
            dataSource: [],
        };
    },
    loadLogs(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/portal/order/demandOrderLog",
            data: {
                demandOrderId: id
            },
            success: function (data) {
                let theArr = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.length; i++) {
                        let thisdata = data.data[i];
                        theArr.push({
                            key: i,
                            recordTime: thisdata.recordTime,
                            status: thisdata.status,
                            comment: thisdata.comment,
                            operator: thisdata.operator,
                            recordTimeFormattedDate: thisdata.recordTimeFormattedDate
                        });
                    };
                };
                this.setState({
                    dataSource: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    handleSubmit(e) {
        //keyword长度判断
        if (this.state.orderStatus || this.state.comment || this.state.recordTime) {
            if (this.state.orderStatus && this.state.comment && this.state.recordTime) {
            } else {
                message.warning('请填写完整的状态流转记录！');
                return;
            };
        };
        this.setState({
            loading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/portal/order/updateDemandOrder',
            data: {
                id: this.props.data.id,
                demandId: this.props.data.demandId,
                enclosureUrl: this.props.data.enclosureUrl,
                status: this.state.orderStatus || this.props.data.status,
                recordTimeFormattedDate: this.state.recordTime ? this.state.recordTime.format("YYYY-MM-DD HH:mm:ss") : undefined,
                comment: this.state.comment,
                intentionMoney: this.state.intentionMoney * 10000,
                contractMoney: this.state.contractMoney * 10000,
                commission: this.state.commission * 10000,
                serviceMoney: this.state.serviceMoney * 10000,
            }
        }).done(function (data) {
            this.setState({
                loading: false
            });
            if (!data.error.length) {
                message.success('保存成功！');
                this.handleOk();
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    handleOk(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    componentWillReceiveProps(nextProps) {
        if (!this.state.visible && nextProps.showDesc && nextProps.data) {
            this.loadLogs(nextProps.data.id);
            this.state.intentionMoney = nextProps.data.intentionMoney;
            this.state.contractMoney = nextProps.data.contractMoney;
            this.state.commission = nextProps.data.commission;
            this.state.serviceMoney = nextProps.data.serviceMoney;
            this.state.orderStatus = undefined;
            this.state.comment = undefined;
            this.state.recordTime = undefined;
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        let theData = this.props.data;
        if (theData) {
            return (
                <div className="patent-desc">
                    <Modal maskClosable={false} visible={this.state.visible}
                        onOk={this.checkPatentProcess} onCancel={this.handleCancel}
                        width='900px'
                        footer={null}
                        title="订单详情"
                        className="demand-order-content">
                        <Spin spinning={this.state.loading}>
                            <Row>
                                <Col span={2}>订单编号：</Col>
                                <Col span={10}>{theData.serialNumber}</Col>
                                <Col span={2}>订单状态：</Col>
                                <Col span={10}>{getOrderStatus(theData.status)}</Col>
                            </Row>
                            <Row>
                                <Col span={2}>需求编号：</Col>
                                <Col span={10}>{theData.demandSerialNumber}</Col>
                                <Col span={2}>需求名称：</Col>
                                <Col span={10}>{theData.name}</Col>
                            </Row>
                            <Row>
                                <Col span={2}>需求状态：</Col>
                                <Col span={10}>{(() => {
                                    if (theData.deletedSign == 1) {
                                        return "已删除"
                                    } else if (theData.auditStatus != 3) {
                                        return "已下架"
                                    } else {
                                        return "正常"
                                    }
                                })()}</Col>
                                <Col span={2}>订单所有人：</Col>
                                <Col span={10}>{theData.theName}</Col>
                            </Row>
                            <Row>
                                <Col span={2}>相关附件：</Col>
                                <Col span={10}>
                                    {theData.enclosureUrl ?
                                        <span className="download-file">
                                            <a onClick={() => { window.open(globalConfig.context + '/api/admin/portal/order/downloadDemandOrder?id=' + theData.id) }}>科技需求订单文件</a>
                                        </span>
                                        : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传！</span>}
                                </Col>
                                <Col span={2}>接单时间：</Col>
                                <Col span={10}>{theData.createTimeFormattedDate}</Col>
                            </Row>
                            <Row>
                                <Col span={2}>意向金：</Col>
                                <Col span={10}>
                                    <InputNumber
                                        value={this.state.intentionMoney}
                                        onChange={(e) => { this.setState({ intentionMoney: Math.round(e * 10000) / 10000 }) }} />
                                    <span> 万元</span>
                                </Col>
                                <Col span={2}>合同金：</Col>
                                <Col span={10}>
                                    <InputNumber
                                        value={this.state.contractMoney}
                                        onChange={(e) => { this.setState({ contractMoney: Math.round(e * 10000) / 10000 }) }} />
                                    <span> 万元</span>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={2}>佣金：</Col>
                                <Col span={10}>
                                    <InputNumber
                                        value={this.state.commission}
                                        onChange={(e) => { this.setState({ commission: Math.round(e * 10000) / 10000 }) }} />
                                    <span> 万元</span>
                                </Col>
                                <Col span={2}>服务金：</Col>
                                <Col span={10}>
                                    <InputNumber
                                        value={this.state.serviceMoney}
                                        onChange={(e) => { this.setState({ serviceMoney: Math.round(e * 10000) / 10000 }) }} />
                                    <span> 万元</span>
                                </Col>
                            </Row>
                            <p>订单状态流转记录</p>
                            <Table columns={this.state.columns}
                                dataSource={this.state.dataSource}
                                pagination={false} />
                            <Row style={{ marginTop: '20px' }}>
                                <Col span={2}>状态：</Col>
                                <Col span={10}>
                                    <Select style={{ width: 160 }}
                                        value={this.state.orderStatus}
                                        onChange={(e) => { this.setState({ orderStatus: e }); }}>
                                        {(() => {
                                            let theArr = [];
                                            orderStatusList.map(function (item, i) {
                                                theArr.push(<Select.Option key={item.value}>{item.key}</Select.Option>)
                                            });
                                            return theArr;
                                        })()}
                                    </Select>
                                </Col>
                                <Col span={2}>时间：</Col>
                                <Col span={10}>
                                    <DatePicker
                                        value={this.state.recordTime || null}
                                        onChange={(e) => { this.setState({ recordTime: e }); }} />
                                </Col>
                            </Row>
                            <Row>
                                <Col span={2}>备注：</Col>
                                <Col span={20}>
                                    <Input value={this.state.comment} onChange={(e) => { this.setState({ comment: e.target.value }); }} />
                                </Col>
                            </Row>
                            <Row>
                                <Col span={2}></Col>
                                <Col span={20}>
                                    <Button style={{ marginRight: '20px' }} type="primary" onClick={this.handleSubmit}>保存</Button>
                                    <Button className="set-submit" type="ghost" onClick={this.handleCancel}>取消</Button>
                                </Col>
                            </Row>
                        </Spin>
                    </Modal>
                </div>
            );
        } else {
            return <div></div>
        }
    },
});

const DemandOrderList = React.createClass({
    loadData(pageNo, apiUrl) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (apiUrl || this.props['data-listApiUrl']),
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                status: this.state.status,
                username: ((apiUrl || this.props['data-listApiUrl']).indexOf('org') != -1) ? null : this.state.searchName,
                unitName: ((apiUrl || this.props['data-listApiUrl']).indexOf('org') != -1) ? this.state.searchName : null
            },
            success: function (data) {
                let theArr = [];
                if (!data.data || !data.data.list) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        theArr.push({
                            key: i,
                            id: thisdata.id,  //线索单/意向单ID
                            serialNumber: thisdata.serialNumber,  //线索单/意向单编号
                            demandId: thisdata.demandId, //科技需求ID
                            createTime: thisdata.createTime,
                            enclosureUrl: thisdata.enclosureUrl,
                            status: thisdata.status, 	//线索单/意向单状态
                            intentionMoney: thisdata.intentionMoney / 10000, 	//意向金
                            contractMoney: thisdata.contractMoney / 10000, 	//合同金
                            commission: thisdata.commission / 10000, 	//佣金
                            serviceMoney: thisdata.serviceMoney / 10000, 	//服务金
                            name: thisdata.name, //需求名称,
                            demandSerialNumber: thisdata.demandSerialNumber, //科技需求编号
                            deletedSign: thisdata.deletedSign, 	//科技需求删除标记
                            auditStatus: thisdata.auditStatus, 	//科技需求审核状态
                            theName: thisdata.username || thisdata.unitName, 	//个人用户名称
                            uid: thisdata.uid,	//个人用户ID
                            createTimeFormattedDate: thisdata.createTimeFormattedDate,	//接单时间
                        });
                    };
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                }
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            selectedRowKeys: [],
            selectedRows: [],
            searchData: [],
            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: 'serialNumber',
                    key: 'serialNumber',
                }, {
                    title: '需求名称',
                    dataIndex: 'name',
                    key: 'name',
                }, {
                    title: '需求编号',
                    dataIndex: 'demandSerialNumber',
                    key: 'demandSerialNumber',
                }, {
                    title: '订单所有人',
                    dataIndex: 'theName',
                    key: 'theName',
                }, {
                    title: '订单状态',
                    dataIndex: 'auditStatus',
                    key: 'auditStatus',
                    render: (text, record) => {
                        if (record.deletedSign == 1) {
                            return "已删除"
                        } else if (record.auditStatus != 3) {
                            return "已下架"
                        } else {
                            return "正常"
                        }
                    }
                }, {
                    title: '流程状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (text, record) => { return getOrderStatus(text); }
                }, {
                    title: '意向金(万元)',
                    dataIndex: 'intentionMoney',
                    key: 'intentionMoney',
                }, {
                    title: '合同金(万元)',
                    dataIndex: 'contractMoney',
                    key: 'contractMoney',
                }, {
                    title: '佣金(万元)',
                    dataIndex: 'commission',
                    key: 'commission',
                }, {
                    title: '服务金(万元)',
                    dataIndex: 'serviceMoney',
                    key: 'serviceMoney',
                }, {
                    title: '接单时间',
                    dataIndex: 'createTimeFormattedDate',
                    key: 'createTimeFormattedDate',
                }
            ],
            dataSource: [],
        };
    },
    handleSearch(e) {
        if (this.props['data-detailApiUrl'].indexOf('org') != -1) {
            $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/achievement/orgOwner",
                data: { name: e },
                success: function (data) {
                    let theArr = [];
                    let theObj = {};
                    if (!data.data) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        };
                    } else if (!$.isEmptyObject(data.data)) {
                        data.data.map(function (item) {
                            theArr.push(item.unitName);
                            theObj[item.unitName] = item.uid;
                        });
                    };
                    this.setState({
                        searchData: theArr,
                        dataSourceObj: theObj
                    });
                }.bind(this),
            });
        } else {
            $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/achievement/userOwner",
                data: { name: e },
                success: function (data) {
                    let theArr = [];
                    let theObj = {};
                    if (!data.data) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        };
                    } else if (!$.isEmptyObject(data.data)) {
                        for (let item in data.data) {
                            theArr.push(data.data[item]);
                            theObj[data.data[item]] = item;
                        };
                    };
                    this.setState({
                        dataSource: theArr,
                        dataSourceObj: theObj
                    });
                }.bind(this),
            });
        };
    },
    componentWillMount() {
        this.state.therottleSearch = throttle(this.handleSearch, 1000, { leading: false }).bind(this);
        let theArr = [], typeArr = [];
        orderStatusList.map(function (item) {
            theArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });
        this.state.demandTypeOption = typeArr;
        this.state.orderStatusOption = theArr;
        // if (window.location.search) {
        //     let theObj = getSearchUrl(window.location.search);
        //     if (theObj.rid) {
        //         theObj.id = theObj.rid;
        //         if (theObj.rid != 'null') {
        //             this.tableRowClick(theObj);
        //         };
        //     };
        // };
        this.loadData();
    },
    componentWillReceiveProps(nextProps) {
        if (this.props['data-listApiUrl'] != nextProps['data-listApiUrl']) {
            this.state.selectedRowKeys = [];
            this.state.selectedRows = [];
            this.state.status = undefined;
            this.state.searchName = null;
            this.state.searchData = [];
            this.loadData(null, nextProps['data-listApiUrl']);
        };
    },
    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/demand/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));
    },
    addClick() {
        this.state.RowData = {};
        this.setState({
            showDesc: true
        });
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.searchName = undefined;
        this.state.status = undefined;
        this.state.sert
        this.loadData();
    },
    render() {
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.splice(-1),
                    selectedRowKeys: selectedRowKeys.splice(-1)
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        return (
            <div className="user-content" >
                <div className="content-title">
                    {this.props['data-listApiUrl'].indexOf('org') == -1 ? <span>个人需求订单管理</span> : <span>组织需求订单管理</span>}
                </div>
                <div className="user-search">
                    <Select placeholder="选择状态" style={{ width: 160 }}
                        value={this.state.status}
                        onChange={(e) => { this.setState({ status: e }) }}>
                        {this.state.orderStatusOption}
                    </Select>
                    <AutoComplete
                        dataSource={this.state.searchData}
                        value={this.state.searchName}
                        style={{ width: 200 }}
                        onSearch={this.state.therottleSearch}
                        placeholder="输入订单所有人名称"
                        onChange={(e) => {
                            this.setState({ searchName: e });
                        }} />
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            //rowSelection={rowSelection}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <DemandDetail
                    data={this.state.RowData}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default DemandOrderList;

// <Button style={{ background: "#3fcf9e", border: "none", color: "#fff" }}
//                         disabled={!hasSelected}
//                         onClick={this.delectRow}>删除<Icon type="minus" /></Button>