import React,{Component} from 'react';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './public.less';
import { Button,Form, Input, Spin, Table, Select,Switch, message, DatePicker, Modal } from 'antd';
import OrderDesc from '../orderDetail/orderDesc'
import Receivable from './receivable';
import Assign from '@/manageCenter/publicComponent/assign';
import {getLiquidationStatus,getNewOrderStatus,getProcessStatus,getApproval} from '@/tools';
const FormItem = Form.Item;

const ShouKuang = 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({
            selectedRowKeys:[],
            selectedRowKey:[],
            page:pageNo,
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,     
            url: globalConfig.context + "/api/admin/financial/financeList", 
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                buyerName: this.state.nameSearch,//客户名称
                orderNo:this.state.orderNoSearch,
                startTime: this.state.releaseDate[0],
                endTime: this.state.releaseDate[1],
                departmentId:this.state.departmenttList,
				processStatus:this.state.processStatus
            },
            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,
		                    orderNo: thisdata.orderNo,
		                    orderType:thisdata.orderType,
		                    orderStatus:thisdata.orderStatus,
		                    sellerName:thisdata.sellerName,
							processStatus:thisdata.processStatus,
		                    liquidationStatus:thisdata.liquidationStatus,
		                    approval:thisdata.approval,
		                    buyerName:thisdata.buyerName,
                            actuallyTotalAmount:thisdata.actuallyTotalAmount,
                            signTime:thisdata.signTime,
                            companyId:thisdata.companyId,
                            companyName:thisdata.companyName,
                            buyerId:thisdata.buyerId,
                            buyerName:thisdata.buyerName,
                            contractNo:thisdata.contractNo,
                            createTime:thisdata.createTime,
                        });
                    };
                }
                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({
                    totalPage:data.data.totalPage,
                    dataSource: theArr,
                    pagination: this.state.pagination
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getInitialState() {
        return {
            searchMore: true,
            assignVisibleX:false,
			assignVisibleY:false,
            releaseDate: [],
            assignDataX:[],
			assignDataY:[],
            totalPage:0,
            boHuivisible:false,
            selectedRowKeys: [],
            selectedRows: [],
            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: 'orderNo',
                    key: 'orderNo',
                },
                {
                    title: '签单日期',
                    dataIndex: 'signTime',
                    key: 'signTime',
                },
                {
                    title: '下单日期',
                    dataIndex: 'createTime',
                    key: 'createTime',
                },
                {
                    title: '已收款(万元)',
                    dataIndex: 'actuallyTotalAmount',
                    key: 'actuallyTotalAmount',
                },
                {
                    title: '客户名称',
                    dataIndex: 'buyerName',
                    key: 'buyerName',
                },
				{
					title: '流程状态',
					dataIndex: 'processStatus',
					key: 'processStatus',
					render: text => {return getProcessStatus(text)}
				},
				{
					title: '特批状态',
					dataIndex: 'approval',
					key: 'approval',
					render: text => {return getApproval(text)}
				},
				{
					title: '合同编号',
					dataIndex: 'contractNo',
					key: 'contractNo',
				},
//                 {
//                     title: '订单状态',
//                     dataIndex: 'orderStatus',
//                     key: 'orderStatus',
//                     render: text => { return getNewOrderStatus(text)}
//                 },
                {
                    title: '订单负责人',
                    dataIndex: 'sellerName',
                    key: 'sellerName'
                },
                {
                    title: '结算状态',
                    dataIndex: 'liquidationStatus',
                    key: 'liquidationStatus',
                    render: text => { return getLiquidationStatus(text)}
                },
                {
                    title:'操作',
                    dataIndex: 'caozuo',
                    key: 'caouzo',
                    render:(text,recard)=>{
                        return <div>
                            {recard.liquidationStatus<2&&(recard.approval===1 || recard.approval===2)?<Button  style={{background:'rgb(192,192,192)'}} onClick={(e)=>{e.stopPropagation(),this.evaluateX(recard)}}>收款</Button>:<Button type="primary" onClick={(e)=>{e.stopPropagation(),this.evaluateX(recard)}}>收款</Button>}
                            {!(recard.actuallyTotalAmount&&Number(recard.actuallyTotalAmount)>0)&&<Button type="danger" style={{marginLeft:'5px'}} onClick={(e)=>{e.stopPropagation(),this.reject(recard)}}>驳回</Button>}
							{<Button type="primary" style={{marginLeft:'5px'}} onClick={(e)=>{e.stopPropagation(),this.evaluateY(recard,'财务专员')}}>转交</Button>}
                        </div>
                    }
                }
            ],
            dataSource: [],
            searchTime: [,]
        }
    },
	/* 收款 */
	evaluateX(recard){
	    this.state.assignDataX=recard;
	    this.setState({
	        assignVisibleX:true
	    })
	},
    /* 转交 */
    evaluateY(recard,nub){
        this.state.assignDataY=recard;
        this.setState({
			nub,
            assignVisibleY:true
        })
    },
    /* 驳回 */
    reject(recard){
       this.setState({
           bohuiData:recard,
           boHuiVisible:true,
           content:''
       })
    },
    boHuiOk(){
        this.setState({
            boHuiVisible:false
        })
        if((this.state.pagination.current==this.state.totalPage)&&(this.state.pagination.total)%10==1){
            this.loadData((this.state.page)-1);
        }else{
            this.loadData(this.state.page);
        }
    },
    boHuiCancel(e){
        this.setState({
            boHuiVisible:false
        })
    },
    componentWillMount() {
        this.loadData();
        this.departmentList();
    },
    tableRowClick(record, index) {
        this.state.RowData = record;
        this.setState({
            showDesc: true,
        });
    },
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData(this.state.page);
        };
    },
    closeAssignX(e, s) {
        this.state.assignDataX={};
        this.state.assignVisibleX = e;
        if (s) {
            this.loadData(this.state.page);
        };
    },
	 closeAssignY(e, s) {
	    this.state.assignDataY={};
	    this.state.assignVisibleY = e;
	    if (s) {
	        this.loadData(this.state.page);
	    };
	},
    search() {
        this.loadData();
    },
    reset() {
        this.state.nameSearch = '';
        this.state.releaseDate = [];
        this.state.orderNoSearch='';
        this.state.departmenttList=undefined;
		this.state.processStatus=[];
        this.loadData();
    },
    //驳回
    boHuiSubmit(e){
        e.preventDefault();
        if(!this.state.content){
            message.warning('请填写驳回原因');
            return false;
        }
        this.setState({
            loading:true
        })
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/financial/reject",
            data: {
                orderNo: this.state.bohuiData.orderNo,
                reason:this.state.content
            }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('驳回成功！');
                this.setState({
                    loading: false,
                });
                this.boHuiOk();
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    render() { 
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1)
                });
            }
        };
        const { RangePicker } = DatePicker;
        const hasSelect = this.state.selectedRowKeys.length;
        var departmentArr = this.state.departmentArr ||[];
        return ( <div className="user-content">
            <div className="content-title">
                    <span>收款结算</span>
                </div>
                <div className="user-search">
                    <Input placeholder="订单编号"
                        value={this.state.orderNoSearch}
                        onChange={(e) => { this.setState({ orderNoSearch: e.target.value }); }} />  
                    <Input placeholder="客户名称"
                        value={this.state.nameSearch}
                        onChange={(e) => { this.setState({ nameSearch: e.target.value }); }} />
                    <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>
					<Select placeholder="流程状态"
							onChange={(e)=>{this.setState({processStatus:e})}} 
							style={{width:160,marginRight:5}} 
							value={this.state.processStatus}>
						<Option value="3">未分配</Option>
						<Option value="4">已分配</Option>
					</Select>
                    <span style={{ marginRight:10}}>下单日期:</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 }); }} />
                    <Button type="primary" onClick={this.search} style={{ marginLeft:10}}>搜索</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={false}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick.bind(this)} />
                    </Spin>
                </div>
				<Assign
				    title="任务"
				    selApi={"/api/admin/newOrder/updateFinance"}
				    data={this.state.assignDataY}
				    showDesc={this.state.assignVisibleY}
				    closeDesc={this.closeAssignY.bind(this)}
				    // fenpaiData={8}
				    specially={0}
				    roleName={this.state.nub}
					requestMethod={"get"}
				/>
                <OrderDesc
                    data={this.state.RowData}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc.bind(this)}
                />
                <Receivable
                    title='收款记录'
                    api='/api/admin/financial/addReceiptsFlow'
                    data={this.state.assignDataX}
                    showDesc={this.state.assignVisibleX}
                    closeDesc={this.closeAssignX.bind(this)}
                />
                <Modal 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: 5 }} wrapperCol={{ span: 16 }} label={<span><strong style={{color:'#f00'}}>*</strong>驳回原因</span>}>
									<Input
										type="textarea"
										rows={4}
										placeholder="请输入驳回原因"
										value={this.state.content}
										onChange={(e) => {
											this.setState({ content: e.target.value });
										}}
									/>
								</FormItem>   
                                <FormItem wrapperCol={{ span: 12, offset:5 }}>  
                                        <Button type="primary" htmlType="submit"  style={{marginRight:20}}>驳回</Button>
                                        <Button type="default" onClick={()=>{this.boHuiCancel()}}>取消</Button>
                                </FormItem>        
                            </Spin>
                        </Form>
                </Modal>
        </div> )
    }
})
 
export default ShouKuang;