import React from 'react';
import { Button, Table, Select, Input, DatePicker, Space, Modal ,message  } from 'antd';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { $Axios, format } from '../../common/publish';
import '../Finance-orderQuery/Finance-orderQuery.scss'
import select_data from '../../common/ssq';
const { Column, ColumnGroup } = Table;
export default class FinanceoRderQuery extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            headTxt: '财务管理 > 订单查询',
            select_data: select_data,
            data: [],
            columns: [
                {
                    title: '序号',
                    dataIndex: 'num',
                    key: 'num',

                },
                {
                    title: '订单号',
                    dataIndex: 'orderNo',
                    key: 'orderNo',
                },
                {
                    title: '订单金额',
                    dataIndex: 'totalAmount',
                    key: 'totalAmount',
                },
                {
                    title: '订单状态',
                    dataIndex: 'orderStatus',
                    key: 'orderStatus',
                },
                {
                    title: '支付金额',
                    dataIndex: 'cash',
                    key: 'cash',
                },
                {
                    title: '本金金额',
                    dataIndex: 'stbPrice',
                    key: 'stbPrice',
                },
                {
                    title: '积分币金额',
                    dataIndex: 'benbiPrice',
                    key: 'benbiPrice',
                },
                {
                    title: '已退款金额',
                    dataIndex: 'refundAmount',
                    key: 'refundAmount',
                },
                {
                    title: '下单时间',
                    dataIndex: 'createTime',
                    key: 'createTime',
                },
                {
                    title: '完成时间',
                    dataIndex: 'finishTime',
                    key: 'finishTime',
                },
                {
                    title: '支付方式',
                    dataIndex: 'payType',
                    key: 'payType',
                },
                {
                    title: '操作',
                    dataIndex: 'cz',
                    key: 'cz',
                    render: (text, record, index) => <a onClick={() => this.xqClick(text, record, index)}>查看订单金额流向</a>,
                },
            ],
            params: {
                action: "payOrderList",//查询订单列表
                appName: JSON.parse(localStorage.getItem('userData')).appName,//当前商户的appName，
                pSize: 10, //每页条数
                pNo: 1, //第几页，起始值从1开始
                orderStatus: '', //订单状态：1：未付款2：已付待入账3：已付已入账4：支付失败
                orderNo: '', //商城订单号
                userName: '', //发起人
                payType: '', //支付方式：1支付宝2微信5微包//0初始1处理中2支付成功3支付失败4退单中5退单成功6退单失败10完成(所有转账分账均完成的，不能再做任何操作)
                timeType: '', //为0或不提供此字段，表示不限制，1创建时间，2完成时间
                begTime: '',//时间戳
                endTime: '',//时间戳 format(item.createTime),
            },
            timeType: null,
            starTime: '',
            endTime: '',
            total: null,
            current: 1,
            paginationProps: {
                showSizeChanger: false,//设置每页显示数据条数
                showQuickJumper: false,
                showTotal: () => `共${this.state.total}条`,
                pageSize: 10,
                total: null,  //数据的总的条数
                onChange: (current) => this.changePage(current), //点击当前页码
            },
            isModalVisible: false,
            columns_tk : [
                {
                    title: '分账对象',
                    dataIndex: 'ownerName',
                    key: 'ownerName',
                },
                {
                    title: '分账金额',
                    dataIndex: 'amount',
                    key: 'amount',
                },
                {
                    title: '分账状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '分账原因',
                    dataIndex: 'remark',
                    key: 'remark',
                }
            ],
            payOrderInfo : null,
            orderSplitInfo : null,
            orderNo : null,
            lodings : null,
            spinning : true,
            keys : 1,
            keye : 2,
        }

    }

    componentDidMount() {
        this.initData();
    }

    xqClick = (text, record, index) => {
        this.setState({
            isModalVisible: true
        });
        this.initData_tk(record)
    }

    initData_tk(e){
        let that_ = this;
        let url = '/payment/merchant.order.query.groovy';
        let params = {
            action : "payOrderDetail",//查询订单金额流向
            orderNo : e.orderNo,//商城订单号
        }
        $Axios('get', url, params, (res) => {
            let status = res.data.head.status;
            if (status == 200) {
                let orderSplitInfo = res.data.body.orderSplitInfo;
                let payOrderInfo = res.data.body.payOrderInfo;
                that_.setState({
                    payOrderInfo : payOrderInfo,
                    orderSplitInfo : orderSplitInfo,
                    orderNo : e.orderNo
                })
            }

        })
    }

    handleOk(){
        this.setState({
            isModalVisible: false
        })
    }

    changePage(e) {
        this.state.params.pNo = e
        this.setState({
            current: e
        });
        this.initData();
    }

    starTime = (value,dateString)=>{
        if(dateString !== ''){
            dateString = new Date(value).formats('yyyy-MM-dd 00:00:00')
            let time = new Date(dateString).getTime()/1000;
            this.setState({
                starTime: time
            })
        }else{
            this.setState({
                starTime: ''
            })
        }
        
    }

    endTime = (value,dateString)=>{
        if(dateString !== ''){
            dateString = new Date(value).formats('yyyy-MM-dd 00:00:00')
            let time = new Date(dateString).getTime()/1000;
            this.setState({
                endTime: time
            })
        }else{
            this.setState({
                endTime: ''
            })
        }
    }
    handleChange_1(e) { //订单状态
        this.state.params.orderStatus = e
    }

    handleChange_2(e) {  //支付方式
        this.state.params.payType = e
    }

    handleChange_3(e) {  //时间类型
        this.state.params.timeType = e
        this.setState({
            timeType : e
        });
        if(e == 0){
            this.setState({
                starTime: '',
                endTime: '',
                keys : new Date().getTime(),
                keye : new Date().getTime() * 1000,
            });
        }
    }

    queryClick() {
        if(this.state.timeType !== 0 && this.state.timeType !== null){
            if(this.state.endTime <= this.state.starTime && (this.state.starTime !== '' && this.state.endTime !== '')){
                message.error('结束时间不可小于或者等于开始时间!');
            }else{
                if(this.state.starTime == '' && this.state.endTime == ''){
                    this.initData()
                }else if(this.state.starTime !== '' && this.state.endTime !== ''){
                    this.initData()
                }else{
                    if(this.state.starTime == ''){
                        message.error('请选择开始时间!');
                    }else if(this.state.endTime == ''){
                        message.error('请选择结束时间!');
                    }
                }
            }
        }else{
            this.initData()
        }
    }

    TableToExcel(){
        message.error('暂不支持导出功能!');
    }

    initData() {
        this.setState({
            lodings : true
        })
        let orderNo = document.getElementById("orderNo").value //商城订单号
        let userName = document.getElementById("userName").value //发起人
        let that_ = this;
        let url = '/payment/merchant.order.query.groovy';
        let params = this.state.params;
        this.state.params.orderNo = orderNo;
        this.state.params.userName = userName;
        this.state.params.begTime = this.state.starTime
        this.state.params.endTime = this.state.endTime
        $Axios('get', url, params, (res) => {
            let status = res.data.head.status;
            if (status == 200) {
                let data = res.data.body.list;
                let arr = [];
                data.map((item, index) => {
                    let obj = {
                        num: index + 1,
                        id: item.id, // 记录标识
                        orderNo: item.orderNo, //商城订单号
                        tradeNo: item.tradeNo,//交易流水号
                        totalAmount: item.totalAmount, //订单总额
                        cash: item.cash,//订单支付现金
                        stbPrice: item.stbPrice,//订单支付联盟币抵扣的现金价格
                        benbiPrice: item.benbiPrice, //订单支付本币抵扣的现金价格
                        spareAmount: item.spareAmount, //分账金额
                        refundAmount: item.refundAmount,//退款金额
                        payType: that_.payTypeList(item.payType),//支付方式：1支付宝2微信5微包
                        orderStatus: that_.orderStatus(item.orderStatus),//订单状态：1：未付款2：已付待入账3：已付已入账4：支付失败
                        createTime: item.createTime == '' ? '--' : format(Number(item.createTime)), //:创建时间
                        finishTime: item.finishTime == '' ? '--' : format(Number(item.finishTime))  //:完成时间
                    };
                    arr.push(obj)
                });
                let total = res.data.body.totalCount;
                that_.state.paginationProps.total = total
                that_.setState({
                    data: arr,
                    total: total,  //数据的总的条数
                    lodings : false
                })
            }

        })
    }

    payTypeList(e) {
        let txt;
        if (e == 1) {
            txt = '支付宝'
        } else if (e == 2) {
            txt = '微信'
        } else if (e == 5) {
            txt = '余额'
        }
        return txt
    }

    orderStatus(e) {
        let txt;
        if (e == 1) {
            txt = '未付款'
        } else if (e == 2) {
            txt = '已付待入账'
        } else if (e == 3) {
            txt = '已付已入账'
        } else if (e == 4) {
            txt = '支付失败'
        } else if (e == 0) {
            txt = '--'
        }
        return txt
    }

    render() {
        const { data, columns, headTxt, keys,keye, select_data, timeType, paginationProps , isModalVisible , columns_tk , payOrderInfo , orderSplitInfo ,orderNo , lodings} = this.state;
        const { Option } = Select;
        return (
            <div className='wrap_table'>
                <div className='header_center'>
                    {headTxt}
                </div>
                <div className='query_table'>
                    <div className='top_div'>
                        <div style={{ display: 'inline-block', }}> 订单状态 ： </div>
                        <Select size='default' placeholder="请选择" onChange={this.handleChange_1.bind(this)} style={{ width: 200, marginRight: '20px' }}>
                            {select_data.OrderType.map((item, index) => (
                                <Option key={index} value={item.value}>{item.label}</Option>
                            ))}
                        </Select>
                        <div style={{ display: 'inline-block', }}> 商户订单号 ： </div>
                        <div style={{ width: '200px', display: 'inline-block', marginLeft: '20px' }}><Input id='orderNo' placeholder="请输入订单号" /></div>
                    </div>
                    <div className='btm_div'>
                        <div style={{ display: 'inline-block', }}> 发起人 ： </div>
                        <div style={{ width: '200px', display: 'inline-block', marginLeft: '20px', marginRight: '20px' }}><Input id='userName' placeholder="请输入用户名" /></div>
                        <div style={{ display: 'inline-block', }}> 支付方式 ： </div>
                        <Select size='default' placeholder="请选择" onChange={this.handleChange_2.bind(this)} style={{ width: 200, marginRight: '20px' }}>
                            <Option key={1} value={2}>微信</Option>
                            <Option key={2} value={1}>支付宝</Option>
                            <Option key={3} value={5}>钱包余额</Option>
                        </Select>
                        <Select size='default' placeholder="请选择时间类型" onChange={this.handleChange_3.bind(this)} style={{ width: 200, marginRight: '20px' }}>
                            <Option key={0} value={0}>不限时间类型</Option>
                            <Option key={1} value={1}>完成时间</Option>
                            <Option key={2} value={2}>下单时间</Option>
                        </Select>
                        <Space direction="vertical">
                            <DatePicker key={keys} onChange={this.starTime} locale={locale} disabled={timeType == null ? true : false || timeType == 0 ? true : false} placeholder='请选择开始时间' />
                        </Space>
                        <div style={{ display: 'inline-block', margin: '0px 10px', color: '#d9d9d9' }}>-</div>
                        <Space direction="vertical">
                            <DatePicker key={keye} onChange={this.endTime} locale={locale} disabled={timeType == null ? true : false || timeType == 0 ? true : false}  placeholder='请选择结束时间' />
                        </Space>
                        

                        <Button type="primary" style={{
                            float: 'right', display: 'inline-block', margin: '0px 10px', marginRight: '20px'
                        }} onClick={this.TableToExcel.bind(this)}>导出</Button>
                        <Button type="primary" style={{
                            float: 'right', display: 'inline-block', margin: '0px 10px',
                        }} onClick={this.queryClick.bind(this)}>搜索</Button>

                    </div>
                </div>
                <div className='tables'>
                    <Table
                        columns={columns}
                        dataSource={data}
                        pagination={paginationProps}
                        loading = {lodings}
                    />
                </div>
                <Modal title="订单金额流向"
                        footer={[
                            <Button key="submit" type="primary" onClick={this.handleOk.bind(this)}>
                                确定
                            </Button>,
                        ]}
                        visible={isModalVisible}
                        closable={false}
                    // onOk={this.handleOk} 
                    >
                        {
                            (payOrderInfo !== {} && payOrderInfo !== null) &&
                            <div>
                                <p style={{fontSize : '16px',fontWeight : '600'}}>订单信息</p>
                                <p>商户订单号 : {orderNo}</p>
                                <p>订单金额 : {payOrderInfo.totalAmount}</p>
                                <p>支付金额 : {payOrderInfo.cash}</p>
                                <p>本金金额 : {payOrderInfo.stbPrice}</p>
                                <p>积分币金额 : {payOrderInfo.benbiPrice}</p>
                            </div>
                        }
                       { (orderSplitInfo !== [] && orderSplitInfo !== null) &&
                            <div>
                                <p style={{fontSize : '16px',fontWeight : '600'}}>订单金额流向信息</p>
                                <Table
                                    columns={columns_tk}
                                    dataSource={orderSplitInfo}
                                />
                            </div>
                       }
                    </Modal>
            </div>
        )
    }
}