import React from 'react';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import '@/manageCenter/financialManage/distribute/public.less';
import {  Button, Input, Spin, Table,Select, Switch, message, DatePicker,Upload} from 'antd';
import {getNewOrderType,beforeUploadFile} from '@/tools';
import {newOrderType} from '@/dataDic';
import { exportExcel } from 'xlsx-oc';

const Order = React.createClass({
    departmentList() {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/organization/selectSuperId",
			data: {},
			success: function(data) {
                let thedata = data.data;
				let theArr=[];
				if(!thedata) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
				}else{
					thedata.map(function(item,index){
						theArr.push({
							key:index,
							name:item.name,
							id:item.id,
						})
					})
				}
				this.setState({
					departmentArr:theArr,
				})
			}.bind(this),
			}).always(function() {
				this.setState({
					loading: false
				});
			}.bind(this));
	},
    loadData(pageNo) {
        this.state.data = [];
        this.setState({
            page:pageNo,
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/order/listAllSettlement",
            data: {
                pageNo: pageNo || 1,
                pageSize:999,
                signName: this.state.signName,//客户名称
                departmentId:this.state.departmenttList,
                orderType:this.state.orderType,
                startDate: this.state.releaseDate[0],
                endDate: this.state.releaseDate[1],
            },
            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+1,
		                    orderNo: thisdata.orderNo,
                            department:thisdata.department,
                            orderType:thisdata.orderType,
                            signName:thisdata.signName,  
                            signNumber:thisdata.signNumber,
                            signTotalAmount:thisdata.signTotalAmount
                        });
                    };
                }
                this.state.pagination.current = data.data.pageNo;
                this.state.pagination.total = data.data.totalCount;
                if(data.data&&data.data.list&&!data.data.list.length){
					this.state.pagination.current=0
					this.state.pagination.total=0
				}
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            searchMore: true,
            releaseDate: [],
            RowData:{},
            selectedRowKeys: [],
            selectedRows: [],
            proofData:{},
            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: 'key',
                    key: 'key',  
                    width:100 
                },
                {
                    title: '订单部门',
                    dataIndex: 'department',
                    key: 'department',
                    width:200
                }, 
                {
                    title: '订单类型',
                    dataIndex: 'orderType',
                    key: 'orderType',
                    render:text=>{
                        return getNewOrderType(text)
                    },
                    width:200
                },
                {
                    title: '签单人员',
                    dataIndex: 'signName',
                    key: 'signName',
                    width:200
                },
                {
                    title: '签单数量',
                    dataIndex: 'signNumber',
                    key: 'signNumber',
                    width:200
                },
                {
                    title: '累计签单金额(万)',
                    dataIndex: 'signTotalAmount',
                    key: 'signTotalAmount',
                    width:200
                },
            ],
            dataSource: [],
            searchTime: [,]
        }
    },
    componentWillMount() {
        this.loadData();
        this.departmentList();
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.signName='';
        this.state.releaseDate = [];
        this.state.departmenttList=undefined;
        this.state.orderType='';
        this.loadData();
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    //导出exec
    exec(){
        var _headers = [{ k: 'key', v: '序号' }, { k: 'department', v: '订单部门' },
            { k: 'orderType', v: '订单类型' }, { k: 'signName', v: '签单人员' },{k:'signNumber',v:'签单数量'},{k:'signTotalAmount',v:'累计签单金额'}]
        exportExcel(_headers,this.state.dataSource,'订单统计报表.xlsx');
    },
    render() { 
        const { RangePicker } = DatePicker;
        let departmentArr = this.state.departmentArr || [];
        return ( <div className="user-content">
            <div className="content-title">
                <span>订单统计报表</span>
                </div>
                <div className="user-search">
                    <Select placeholder="部门机构"
                        style={{ width: 150 ,marginRight:10}}
                        value={this.state.departmenttList}
                        onChange={(e) => { this.setState({ departmenttList: e }) }}>
                        {
                            departmentArr.map(function (item) {
                                    return <Select.Option key={item.id} >{item.name}</Select.Option>
                            })
                        }
                    </Select>
                    <Input placeholder="签单人员"
                        value={this.state.signName}
                        onChange={(e) => { this.setState({ signName: e.target.value }); }} /> 
                    <Select placeholder="订单类型"
                        style={{ width: 150 ,marginRight:10}}
                        value={this.state.orderType}
                        onChange={(e) => { this.setState({ orderType: e }) }}>
                        {
                            newOrderType.map(function (item) {
                                    return <Select.Option key={item.value} >{item.key}</Select.Option>
                            })
                        }
                    </Select>   
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <div style={{float:'right'}}>
                    <Upload
                            action={globalConfig.context + "/api/admin/achievement/uploadTemplate"}
                            data={{ 'sign': 'achievement_template' }}
                            beforeUpload={beforeUploadFile}
                            showUploadList={false}
                            onChange={(info) => {
                                if (info.file.status !== 'uploading') {
                                    
                                }
                                if (info.file.status === 'done') {
                                    if (!info.file.response.error.length) {
                                        message.success(`${info.file.name} 文件上传成功！`);
                                    } else {
                                        message.warning(info.file.response.error[0].message);
                                        return;
                                    };
                                } else if (info.file.status === 'error') {
                                    message.error(`${info.file.name} 文件上传失败。`);
                                };
                            }} >
                            <Button>导入年度销售数据</Button>
                        </Upload>
                        <Button type="primary" onClick={this.exec} style={{margin:'0 10px'}}>导出到exec</Button>
                    </div>
                    <span>更多搜索<Switch defaultChecked={false} onChange={this.searchSwitch.bind(this)} /></span>
                    <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>
                        <span>起止时间 :</span>
                        <RangePicker
                            value={[this.state.releaseDate[0] ? moment(this.state.releaseDate[0]) : null,
                            this.state.releaseDate[1] ? moment(this.state.releaseDate[1]) : null]}
                            onChange={(data, dataString) => { this.setState({ releaseDate: dataString }); }} />
                    </div>
                </div>
                <div className="patent-table clearfix" id="table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            scroll={{y:500}}
                            pagination={false}
                            />
                    </Spin>
                </div>
        </div> )
    }
})
 
export default Order;