import React, {
    PureComponent
} from "react";
var QRCode = require('qrcode-react');
import {
    connect
} from "dva";
import {
    Modal,
    Input,
    Radio,
    Button,
    Row,
    Col,
    Popconfirm,
    Spin,
    Form
} from "antd";
import {
    routerRedux
} from "dva/router";
import styles from "./index.less";
import alipayImg from "./imgs/alipay.png";
import chanpayImg from "./imgs/chanpay.png";
import wechatpayImg from "./imgs/wechatpay.png";
import codeBgImg from "./imgs/codebg.png";
import codeHintImg from "./imgs/codehint.png";
import {
    accDiv,
    accMul
} from "@/utils/utils.js"

const oldFetch = global.fetch;
const RadioGroup = Radio.Group;
class PayforDialog extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            selectedRows: [],
            selectedRowKeys: [], // 货补选择项
            payurl: 'Alipay', //支付方式请求地址
            loading: false,
            modalResultVisible: false,
            wiexinCode: '',
            intervalFun: 1,
            status: 2,
        };
    }
    componentWillMount() {
        const {
            dispatch
        } = this.props;
        dispatch({
            type: "orderList/getOrderStatusData",
            payload: null
        });
    }
    onChangeHandle(selectedRowKeys, selectedRows) {
        this.setState({
            selectedRowKeys: selectedRowKeys,
            selectedRows: selectedRows
        });
    }
    handleOkBtn = () => {
        let {
            dispatch,
            payNeedData,
            orderPayBillSet
        } = this.props;
        if (this.isEmptyObject(payNeedData)) {
            payNeedData = orderPayBillSet;
        }
        let payBillDates = payNeedData.payBillData;
        if (!this.isEmptyObject(payBillDates)) { // 转支付单
            payBillDates.paymentModeId = this.state.payurl;
            dispatch({
                type: "paymentNotice/tempBillToPayBill",
                payload: payBillDates
            }).finally(() => {
                this.setState({
                    loading: false
                });
                const {
                    dispatch,
                    returnTempToPayData
                } = this.props;
                if (returnTempToPayData.length > 1) {
                    this.hideModal();
                    dispatch(
                        routerRedux.push({
                            pathname: "/buyer/onlinePayList",
                            query: {
                                srcBillCode: payNeedData.out_trade_no,
                            }
                        })
                    );
                } else {
                    var fulls = "left=0,screenX=0,top=0,screenY=0,scrollbars=1,resizable=yes,location=no, status=no"; //定义弹出窗口的参数
                    if (window.screen) {
                        var ah = screen.availHeight - 30;
                        var aw = screen.availWidth - 10;
                        fulls += ",height=" + ah;
                        fulls += ",innerHeight=" + ah;
                        fulls += ",width=" + aw;
                        fulls += ",innerWidth=" + aw;
                        fulls += ",resizable"
                    }

                    var totalAmount = accDiv(Math.ceil(accMul(payNeedData.total_amount, 100)), 100);

                    switch (this.state.payurl) {
                        case 'FreePayment':
                            window.open(window.location.origin + '/occ-pay/chanpay/redirectpaypage?OutTradeNo=' + returnTempToPayData[0].paybillCode + '&OrderAmt=' + totalAmount + '&financialOrgId=' + returnTempToPayData[0].payeeId, '畅捷通', fulls);
                            break;
                        case 'Alipay':
                            window.open(window.location.origin + '/occ-pay/alipay/redirectpaypage?out_trade_no=' + returnTempToPayData[0].paybillCode + '&total_amount=' + totalAmount + '&financialOrgId=' + returnTempToPayData[0].payeeId, "支付宝", fulls);
                            break;
                        case 'WeChat':
                            oldFetch(window.location.origin + '/occ-pay/wechatpay/redirectpaypage?out_trade_no=' + returnTempToPayData[0].paybillCode + '&total_fee=' + parseInt(totalAmount * 100) + '&financialOrgId=' + returnTempToPayData[0].payeeId)
                                .then(res => res.text())
                                .then(data => {
                                    console.log(data);
                                    this.setState({
                                        wiexinCode: data
                                    });
                                })
                            break;
                    }
                    this.setModalResultVisible(true);
                    this.hideModal();
                }
            });
        } else { //支付单页面直接支付
            var fulls = "left=0,screenX=0,top=0,screenY=0,scrollbars=1,resizable=yes,location=no, status=no"; //定义弹出窗口的参数
            if (window.screen) {
                var ah = screen.availHeight - 30;
                var aw = screen.availWidth - 10;
                fulls += ",height=" + ah;
                fulls += ",innerHeight=" + ah;
                fulls += ",width=" + aw;
                fulls += ",innerWidth=" + aw;
                fulls += ",resizable"
            }

            var totalAmount = accDiv(Math.ceil(accMul(payNeedData.total_amount, 100)), 100);

            switch (this.state.payurl) {
                case 'FreePayment':
                    window.open(window.location.origin + '/occ-pay/chanpay/redirectpaypage?OutTradeNo=' + payNeedData.out_trade_no + '&OrderAmt=' + totalAmount + '&financialOrgId=' + payNeedData.financialOrgId, '畅捷通', fulls);
                    break;
                case 'Alipay':
                    window.open(window.location.origin + '/occ-pay/alipay/redirectpaypage?out_trade_no=' + payNeedData.out_trade_no + '&total_amount=' + totalAmount + '&financialOrgId=' + payNeedData.financialOrgId, "支付宝", fulls);
                    break;
                case 'WeChat':
                    oldFetch(window.location.origin + '/occ-pay/wechatpay/redirectpaypage?out_trade_no=' + payNeedData.out_trade_no + '&total_fee=' + parseInt(totalAmount * 100) + '&financialOrgId=' + payNeedData.financialOrgId)
                        .then(res => res.text())
                        .then(data => {
                            this.setState({
                                wiexinCode: data
                            });
                        })
                    break;
            }
            this.setModalResultVisible(true);
            this.hideModal();
        }

    };

    showModal = () => {
        this.props.dispatch({
            type: "global/orderListVisible",
            payload: true
        });
    };
    hideModal = () => {
        if (window.location.href.indexOf('buyer/orderEdit') > -1) {
            setTimeout(() => {
                window.history.go(-1);
            }, 500);
        }
        this.props.dispatch({
            type: "global/orderListVisible",
            payload: false
        });
    };
    radioOnChange = (e) => {
        this.setState({
            payurl: e.target.value,
        });
    };
    setModalResultVisible = (modalResultVisible) => {
        this.setState({
            modalResultVisible
        });
    };
    backToList = () => {
        const {
            dispatch,
            backToWho
        } = this.props;
        this.setModalResultVisible(false);
        setTimeout(() => {
            dispatch(routerRedux.push("/buyer/" + backToWho));
            this.setState({
                status: 2
            });
        }, 2000);
    };
    isEmptyObject = (obj) => {
        for (var key in obj) {
            return false;
        }
        return true;
    };
    timer = () => {
        const {
            dispatch,
            returnTempToPayData,
            payNeedData,
            onlinePayData,
            orderPayBillSet
        } = this.props;
        if (!this.state.modalResultVisible) return;
        let payNeedDataCopy = payNeedData;
        if (this.isEmptyObject(payNeedData)) {
            payNeedDataCopy = orderPayBillSet;
        }
        let paybillId = returnTempToPayData.length ? returnTempToPayData[0].id : payNeedDataCopy.paybillId;
        // 防止有历史数据，先清空信息
        dispatch({
            type: "paymentNotice/onlinePayData",
            onlinePayData: null
        });
        dispatch({
            type: "paymentNotice/getOnlinePayById",
            payload: {
                id: paybillId
            }
        }).finally((data) => {
            console.log(onlinePayData);
            if (onlinePayData && onlinePayData.paymentStatusCode == '1') {
                this.setState({
                    status: 1
                });
                this.backToList();
            } else if (this.state.status != 1) {
                if (!this.state.modalResultVisible) return;
                this.reInerval()
            }
        });
    };
    reInerval = () => {
        setTimeout(() => this.timer(), 5000);
    };
    showCodes = () => {
        if (!this.state.modalResultVisible) return;
        if (this.state.wiexinCode && this.state.wiexinCode.indexOf('weixin') != -1) {
            if (this.state.status != 1) {
                this.reInerval();
            }
            return (
                <div>
               <div style={{float:'left',width:230,paddingLeft:62,marginTop:17,marginRight:130}}>
                    <img style={{width:230}} src={codeHintImg}/>
               </div>
               <div style={{width:240,marginTop:17,float:'left'}}>
                    <div style={{backgroundImage:"url("+codeBgImg+")",backgroundSize:240,width:240,height:240,padding:18}}>
                        <QRCode value={this.state.wiexinCode} size={203} />
                    </div>
                    <p style={{fontSize:16,color:'#333',letterSpacing: 0.43,textAlign: 'center',marginBottom:10}}>请使用微信<em style={{color:'#e14c46'}}>扫一扫</em></p>
                    <p style={{fontSize:16,color:'#333',letterSpacing: 0.43,textAlign: 'center'}}>扫描二维码支付</p>
                </div>
                <div style={{clear:'both'}}></div>
           </div>
            );
        }
    };
    render() {
        let {
            payNeedData,
            orderPayBillSet
        } = this.props;
        // console.log(this.props);        
        const iptDisabled = true;
        if (this.isEmptyObject(payNeedData)) {
            payNeedData = orderPayBillSet;
        }
        const radioStyle = {
            display: 'block',
            height: '30px',
            lineHeight: '30px',
            marginBottom: '23px',
        };
        const titleStyle = {
            height: '32px',
            lineHeight: '32px',
            textAlign: "right",
            marginBottom: "16px",
        };
        return (
            <div>
            <div className={styles.payforBox}>
            <Modal
                title={this.props.title || "请选择"}
                visible={this.props.visible || false}
                onOk={this.handleOkBtn.bind(this)}
                onCancel={this.hideModal}
                okText="确认"
                cancelText="取消"
                width={500}
                className={styles.modal}
            >
                <div className={styles.payforDialogBox}>
                    <Spin spinning={this.state.loading}>
                        <div className={styles.payfortHeadBox}>                            
                                <div className={styles.payforItemBox}>
                                    <div className={styles.payforItem}>
                                        <Row gutter={16}>
                                        <Col span={2}></Col>
                                            <Col span={6} style={titleStyle}>
                                                <span className={styles.label}>付款金额：</span>
                                            </Col>
                                            <Col span={14}>
                                                <Input
                                                className={styles.iptBox}
                                                style={{ width: "200px" }}
                                                value={payNeedData.total_amount}
                                                disabled={iptDisabled}
                                                />                                            
                                            </Col>
                                        </Row>
                                        <Row gutter={16}>
                                        <Col span={2}></Col>
                                        <Col span={6} style={titleStyle}>
                                             <span className={styles.label}>付款业务类型：</span>
                                        </Col>
                                        <Col span={14}>
                                            <Input
                                            className={styles.iptBox}
                                            style={{ width: "200px" }}
                                            value={'货款'}
                                            disabled={iptDisabled}
                                            />
                                        </Col>
                                        </Row>
                                        <Row gutter={16}>
                                        <Col span={2}></Col>
                                        <Col span={6} style={titleStyle}>
                                            <span className={styles.label}>支付币种：</span>
                                        </Col>
                                        <Col span={14}>
                                            <Input
                                            className={styles.iptBox}
                                            style={{ width: "200px" }}
                                            value={payNeedData.currencyName}
                                            disabled={iptDisabled}
                                            />
                                        </Col>
                                        </Row>
                                    </div>
                                </div>
                            
                            <div className={styles.payforItemBox}>
                           
                                <div className={styles.payforItem}>
                                <Row gutter={16}>
                                <Col span={2}></Col>
                                <Col span={6} style={{textAlign:"right"}}>
                                    <span className={styles.label}>支付方式：</span>
                                </Col>
                                <Col span={14}>                                            
                                    <RadioGroup onChange={this.radioOnChange} value={this.state.payurl}>
                                    <Radio style={radioStyle} value={'FreePayment'}><img style={{ width: 24, height: 24,marginRight:8 }} src={chanpayImg}/>畅捷支付</Radio>
                                    <Radio style={radioStyle} value={'Alipay'}><img style={{ width: 24, height: 24,marginRight:8 }} src={alipayImg}/>支付宝</Radio>
                                    <Radio style={radioStyle} value={'WeChat'}><img style={{ width: 24, height: 24,marginRight:8 }} src={wechatpayImg}/>微信支付</Radio>
                                    </RadioGroup>
                                    </Col>
                                    </Row>
                                    
                                </div>
                             
                            </div>
                        </div>   
                    </Spin>    
                </div>
            </Modal>
            </div>
            <div id="returnmodal" className={styles.returnmodal}>
                <Modal
                    title="提示"
                    style={{ top: 20 }}
                    visible={this.props.wxVisible? true:this.state.modalResultVisible}
                    width={700}
                    footer={null}
                    closable={false}
                    centered={true}
                    cancelText={'支付遇到问题'}
                    okText={'支付成功'}
                    getContainer={()=>document.getElementById('returnmodal')}
                    wrapClassName={'returnmodal'} 
                    bodyStyle={{'textAlign':'center'}}
                >          
                {this.showCodes()}
                <div>
                    <Button
                    className={styles.btn}
                    onClick={this.backToList.bind(this)}
                        >
                        返回订单列表
                    </Button>
                    </div>
                </Modal>
        </div>
            </div>
        )
    }
}
const FormPayforDialog = Form.create()(PayforDialog);
export default connect(state => ({
    visible: state.global.orderListVisible,
    orderStatusData: state.orderList.orderStatusData,
    orderPayBillSet: state.paymentNotice.orderPayBillSet,
    returnTempToPayData: state.paymentNotice.returnTempToPayData,
    onlinePayData: state.paymentNotice.onlinePayData,
}))(FormPayforDialog);