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 './techAchievement.less';
import { orderStatusList } from '../../dataDic.js';
import { befoFile, getSearchUrl, getOrderStatus, companySearch } from '../../tools.js';
import BatchImport from './batchImport';
import throttle from '../../throttle.js';

const AchievementDetail = 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/achievementOrderLog",
            data: {
                achievementOrderId: 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/updateAchievementOrder',
            data: {
                id: this.props.data.id,
                achievementId: this.props.data.achievementId,
                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,
                paymentId: this.state.paymentId,
                paymentType: this.state.paymentType,
                paymentValue: this.state.paymentValue,
                transferPrice: this.state.transferPrice,
            }
        }).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.paymentId = nextProps.data.paymentId;
            this.state.paymentType = nextProps.data.paymentType;
            this.state.paymentValue = nextProps.data.paymentValue;
            this.state.transferPrice = nextProps.data.transferPrice;
            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='800px'
                        footer={null}
                        title="订单详情"
                        className="demand-order-content">
                        <Spin spinning={this.state.loading}>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>订单编号：</Col>
                                <Col span={9}>{theData.serialNumber}</Col>
                                <Col span={3} style={{textAlign:'right'}}>订单状态：</Col>
                                <Col span={9}>{getOrderStatus(theData.status)}</Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>成果编号：</Col>
                                <Col span={9}>{theData.achievementSerialNumber}</Col>
                                <Col span={3} style={{textAlign:'right'}}>成果名称：</Col>
                                <Col span={9}>{theData.name}</Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>成果状态：</Col>
                                <Col span={9}>{(() => {
                                    if (theData.deletedSign == 1) {
                                        return "已删除"
                                    } else if (theData.auditStatus != 3) {
                                        return "已下架"
                                    } else {
                                        return "正常"
                                    }
                                })()}</Col>
                                <Col span={3} style={{textAlign:'right'}}>订单所有人：</Col>
                                <Col span={9}>{theData.theName}</Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>接单时间：</Col>
                                <Col span={9}>{theData.createTimeFormattedDate}</Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>订单金额：</Col>
                                <Col span={9}>
                                    {theData.bargainingMode == 0 ? <div>
                                        <span>价格面议</span>
                                    </div> : <InputNumber
                                            value={this.state.transferPrice}
                                            onChange={(e) => { this.setState({ transferPrice: e }) }} />}
                                    <span> 万元</span>
                                </Col>
                                <Col span={3} style={{textAlign:'right'}}>支付金额：</Col>
                                <Col span={9}>
                                    <InputNumber style={{ width: '160px' }}
                                        value={this.state.paymentValue}
                                        onChange={(e) => { this.setState({ paymentValue: e }) }} />
                                    <span> 元</span>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>支付方式：</Col>
                                <Col span={9}>
                                    <Input
                                        value={this.state.paymentType}
                                        onChange={(e) => { this.setState({ paymentType: e.target.value }) }} />
                                </Col>
                                <Col span={3} style={{textAlign:'right'}}>订单流水：</Col>
                                <Col span={9}>
                                    <Input value={this.state.paymentId}
                                        onChange={(e) => { this.setState({ paymentId: e.target.value }) }} />
                                </Col>
                            </Row>
                            <p>订单状态流转记录</p>
                            <Table columns={this.state.columns}
                                dataSource={this.state.dataSource}
                                pagination={false} />
                            <Row style={{ marginTop: '20px' }}>
                                <Col span={3} style={{textAlign:'right'}}>状态：</Col>
                                <Col span={9}>
                                    <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={3} style={{textAlign:'right'}}>时间：</Col>
                                <Col span={9}>
                                    <DatePicker style={{ width: '150px' }}
                                        showTime
                                        format="YYYY-MM-DD HH:mm:ss"
                                        placeholder="选择支付时间"
                                        value={this.state.recordTime ? moment(this.state.recordTime, "YYYY-MM-DD HH:mm:ss") : undefined}
                                        onChange={(t, str) => {
                                            this.setState({ recordTime: t });
                                        }} />
                                </Col>
                            </Row>
                            <Row>
                                <Col span={3} style={{textAlign:'right'}}>备注：</Col>
                                <Col span={20}>
                                    <Input value={this.state.comment} onChange={(e) => { this.setState({ comment: e.target.value }); }} />
                                </Col>
                            </Row>
                            <Row>
                                <Col span={3}></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 AchievementOrderList = 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,  //线索单/意向单编号
                            achievementId: thisdata.achievementId, //科技需求ID
                            createTime: thisdata.createTime,
                            status: thisdata.status, 	//线索单/意向单状态
                            paymentvalue: thisdata.paymentvalue,
                            name: thisdata.name, //成果名称,
                            achievementSerialNumber: thisdata.achievementSerialNumber, //科技成果编号
                            deletedSign: thisdata.deletedSign, 	//科技成果删除标记
                            auditStatus: thisdata.auditStatus, 	//科技成果审核状态 	//个人用户名称
                            theName: thisdata.username || thisdata.unitName,
                            uid: thisdata.uid,	//个人用户ID
                            createTimeFormattedDate: thisdata.createTimeFormattedDate,	//接单时间
                            paymentId: thisdata.paymentId,
                            paymentTime: thisdata.paymentTime,
                            paymentTimeFormattedDate: thisdata.paymentTimeFormattedDate,
                            paymentType: thisdata.paymentType,
                            paymentValue: thisdata.paymentValue,
                            transferPrice: thisdata.transferPrice
                        });
                    };
                    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));
    },
    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),
            });
        };
    },
    getInitialState () {
        return {
            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: 'achievementSerialNumber',
                    key: 'achievementSerialNumber',
                }, {
                    title: '订单所有人',
                    dataIndex: 'theName',
                    key: 'theName',
                }, {
                    title: '订单状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (text, record) => { return getOrderStatus(text); }
                }, {
                    title: '订单金额',
                    dataIndex: 'paymentValue',
                    key: 'paymentValue',
                }, {
                    title: '接单时间',
                    dataIndex: 'createTimeFormattedDate',
                    key: 'createTimeFormattedDate',
                }
            ],
            dataSource: [],
        };
    },
    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;
        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 = undefined;
            this.state.searchData = [];
            this.loadData(null, nextProps['data-listApiUrl']);
        };
    },
    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.uid = undefined;
        this.state.searchName = undefined;
        this.state.status = undefined;
        this.loadData();
    },
    render () {
        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}
                        style={{ width: 200 }}
                        value={this.state.searchName}
                        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} class="no-all-select"
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            style={{
                               cursor: 'pointer',
                            }}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <AchievementDetail
                    data={this.state.RowData}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} />
            </div >
        );
    }
});

export default AchievementOrderList;
