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, Form,Spin,InputNumber, Table,Select, Switch, message, DatePicker,Upload,Modal} from 'antd';
import {getNewOrderType,beforeUploadFile} from '@/tools';
import {newOrderType} from '@/dataDic';
import { exportExcel } from 'xlsx-oc';
const FormItem = Form.Item;


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
        });
        let orderN = Number(this.state.orderType);
        let time = new Date(),
            year = time.getFullYear(),
            month = time.getMonth()+1,
            mon1 = this.state.releaseDate.length?this.state.releaseDate[0].replace(/-/g,''):'',
            mon2 = this.state.releaseDate.length?this.state.releaseDate[1].replace(/-/g,''):'';
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/bonus/orderReportList",
            data: {
                pageNo: pageNo || 1,
                pageSize:this.state.pagination.pageSize,
                saleName: this.state.signName,//客户名称
                departmentId:this.state.departmenttList,
                type:orderN>=0?orderN+1:'',
                month: mon1||Number(year+''+(month<10?('0'+month):month)),
                month1: mon2||Number((month+1>12?year+1:year)+''+(month+1>12?'01':(month+1)<10?'0'+(month+1):(month+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,
                            id:thisdata.id,
                            mid:thisdata.mid,
                            deptName:thisdata.deptName,
                            type:thisdata.type,
                            saleName:thisdata.saleName,
                            proofCount:thisdata.proofCount,
                            amount:thisdata.amount
                        });
                    };
                }
                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: 'id',
                    key: 'id',
                },
                {
                    title: '订单部门',
                    dataIndex: 'deptName',
                    key: 'deptName',
                },
                {
                    title: '订单类型',
                    dataIndex: 'type',
                    key: 'type',
                    render:text=>{
                        return getNewOrderType(text)
                    },
                },
                {
                    title: '签单人员',
                    dataIndex: 'saleName',
                    key: 'saleName',
                },
                {
                    title: '签单数量',
                    dataIndex: 'proofCount',
                    key: 'proofCount',
                },
                {
                    title: '累计签单金额(万)',
                    dataIndex: 'amount',
                    key: 'amount',
                },
                {
                    title:'修改单量',
                    dataIndex:'dl',
                    key:'d1',
                    render:(text,recard)=>{
                        return <Button onClick={(e)=>{e.stopPropagation();this.modify(recard)}}>修改单量</Button>
                    }
                }
            ],
            dataSource: [],
            searchTime: [,]
        }
    },
    //修改单量
    modify(recard){
        this.setState({
            boHuiVisible:true,
            recard,
            result:recard.proofCount,
            amount:recard.amount
        })
    },
    bohuiOk(){
        this.setState({
            boHuiVisible:false
        })
        this.loadData(this.state.page);
    },
    boHuiCancel(){
        this.setState({
            boHuiVisible:false
        })
    },
    boHuiSubmit(e){
        e.preventDefault();
        var resType = typeof this.state.result;
        if(resType != 'number'){
            message.warning('请填写校对信息');
            return false;
        };
        var amountType = typeof this.state.amount;
        if(amountType != 'number'){
            message.warning('请填写金额');
            return false;
        };
        this.setState({
            loading:true
        });
        const recard = this.state.recard;
        var api = '/api/admin/bonus/updateProof';
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + api,
            data: {
                id:recard.mid,
                amount:this.state.amount,
                proofCount:this.state.result
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('修改单量成功');
                this.bohuiOk();
            } else {
                message.warning(data.error[0].message);
            };
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    componentWillMount() {
        this.loadData();
        this.departmentList();
    },
    search() {
        this.loadData();
    },
    reset() {
        this.state.signName='';
        this.state.releaseDate = [];
        this.state.departmenttList=undefined;
        this.state.orderType=undefined;
        this.loadData();
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    loadExcel(){
        window.location.href=globalConfig.context+"/api/admin/bonus/downOrderModelExcel";
    },
    //导出exec
    exec(){
        let orderN = Number(this.state.orderType);
        let time = new Date(),
            year = time.getFullYear(),
            month = time.getMonth()+1,
            mon1 =   this.state.releaseDate.length?this.state.releaseDate[0].replace(/-/g,''):'',
            mon2 =   this.state.releaseDate.length?this.state.releaseDate[1].replace(/-/g,''):'';
        let data = {
            departmentId:this.state.departmentId,
            saleName: this.state.signName,
            type:orderN>=0?orderN+1:'',
            month: mon1||Number((year+''+month)),
            month1: mon2||Number((month+1>12?year+1:year)+''+(month+1>12?'01':month+1)),
        }
        window.location.href=(globalConfig.context+'/api/admin/bonus/exportOrderData?'+$.param(data));
    },
    render() {
        const { RangePicker } = DatePicker;
        let departmentArr = this.state.departmentArr || [];
        const recard = this.state.recard || {};
        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>
                    <span>起止时间 :</span>
                    <RangePicker
                        format="YYYY-MM"
                        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 }); }} />
                    <Button type="primary" onClick={this.search} style={{marginLeft:'10px'}}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <div style={{float:'right'}}>
                    {/*<Button type="primary" onClick={this.loadExcel} style={{margin:'0 10px'}}>下载导入模板</Button>
                    <Upload
                            action={globalConfig.context + "/api/admin/bonus/uploadOrderExcel"}
                            data={{ 'sign': '' }}
                            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} 文件上传成功!`);
                                        this.loadData();
                                    } 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'}}>导出到excel</Button>
                    </div>

                </div>
                <div className="patent-table clearfix" id="table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                            bordered
                            size="small"
                            />
                    </Spin>
                </div>
                <Modal maskClosable={false} visible={this.state.boHuiVisible}
                        width="400px"
                        title='修改单量'
                        footer=''
                        onOk={this.boHuiOk}
                        onCancel={this.boHuiCancel}
                >
                    <Form layout="horizontal" onSubmit={this.boHuiSubmit}>
			                <Spin spinning={this.state.loading}>
                                <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} label={<span><strong style={{color:'#f00'}}>*</strong>单量校对结果</span>}>
                                    <InputNumber min={0} max={1} placeholder="输入单量"
                                        value={this.state.result}
                                        onChange={(e)=>{this.setState({result:e})}}
                                    />
                                </FormItem>
                                <FormItem labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} label={<span><strong style={{color:'#f00'}}>*</strong>金额</span>}>
                                    <InputNumber min={0} max={9999} placeholder="金额"
                                        value={this.state.amount}
                                        onChange={(e)=>{this.setState({amount:e})}}
                                    />
                                    <span> 万元</span>
                                </FormItem>
                                <FormItem wrapperCol={{ span: 12, offset:8 }}>
                                    <Button type="primary" htmlType="submit"  style={{marginRight:20}}>修改</Button>
                                    <Button type="default" onClick={()=>{this.boHuiCancel()}}>取消</Button>
                                </FormItem>
                            </Spin>
                        </Form>
                </Modal>
        </div> )
    }
})

export default Order;