/*
 * @Description: 云课堂充值
 * @Author: zhangyi
 * @Date: 2020-05-09 15:02:39
 * @LastEditors: zhangleyuan
 * @LastEditTime: 2020-12-09 16:55:25
 */
import React from 'react';
import { Modal, message, Form, InputNumber, Row, Col, Button } from "antd";
import { QuestionCircleOutlined } from '@ant-design/icons';
import qrcode from "@/libs/qrcode/qrcode.js";
import classNames from "classnames";
import AccountArgeement from "./ChargeArgeement";
import "./AccountChargeModal.less";

const FormItem = Form.Item;
const layout = {
  labelCol: { span: 5 },
  wrapperCol: { span: 19 },
};
const buttonStyle = {
  width: 302,
  marginTop: 30,
  height: 40,
  marginLeft: 4,
  lineHeight: "40px",
};
const ChannelType = {
  WE_CHAT: "wechatPay",
  ALI_PAY: "aliPay",
};

const limitNumber = (value) => {
  return value.replace(/^(0+)|[^\d]+/g, "");
};

class AccountChargeModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      payType:
        props.payInfo && props.payInfo.orderState == "PAY_UNDO"
          ? ChannelType[props.payInfo.payChannelType]
          : "wechatPay",
      orderId: null,
      assetsId: null,
      balance: 0,
      payStatus: 0,
      step: props.payInfo && props.payInfo.orderState == "PAY_UNDO" ? 2 : 1,
      amount:
        props.payInfo && props.payInfo.orderState == "PAY_UNDO"
          ? props.payInfo.rechargeBalance
          : null,
      amoutHelp: "最少充值500元",
      validateStatus: null,
    };
  }
  componentDidMount() {
    // 发请求
    if (!this.props.notQuery) {
      this.getUserAssetsId();
    }
  }
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  //选择支付方式
  changePayType = (type) => {
    this.setState({
      payType: type,
    });
  };
  //查询账户Id
  getUserAssetsId = () => {
    window.axios
      .Business("public/liveAssets/query", {
        // instId: window.currentUserInstInfo.instId,
      })
      .then((res) => {
        // const { teacherId, adminId } = window.currentUserInstInfo;
        const { assetsId = "", balance } = res.result;
        this.setState({
          assetsId,
          balance,
        });
        if (this.props.payInfo && this.props.payInfo.orderState == "PAY_UNDO") {
          //继续充值的情况
          const { orderId } = this.props.payInfo;
          const params = {
            orderId,
            operatorId: !!teacherId ? teacherId : adminId,
          };
          this.reChargeSubmit("public/liveAssets/continueRecharge", params);
        }
      });
  };

  handleReChareg = _.debounce(
    () => {
      const { amount, payType, assetsId } = this.state;
      if (!amount) {
        this.setState({
          amoutHelp: "请输入充值金额",
          validateStatus: "error",
        });
        return;
      }
      axios
        .Business("public/liveAssets/defaultRechargeAmount", {
          // instId: window.currentUserInstInfo.instId,
        })
        .then((res) => {
          const { assetsState, defaultAmount } = res.result;
          if (amount && amount < 500 && assetsState == 1) {
            //首充值
            this.setState({
              amoutHelp: "首次最少充值500元",
              validateStatus: "error",
            });
            return;
          }
          if (
            amount &&
            amount < 500 &&
            (assetsState == 2 || assetsState == 3)
          ) {
            //不首充，不欠费
            this.setState({
              amoutHelp: "最少充值500元",
              validateStatus: "error",
            });
            return;
          }
          if (amount && amount < defaultAmount && assetsState == 3) {
            //不首充，欠费
            this.setState({
              amoutHelp: "最少充值需超过欠费金额",
              validateStatus: "error",
            });
            return;
          }
          if (amount && amount > 20000) {
            this.setState({
              amount: 20000,
            });
          }
          // const { instId, adminId, teacherId } = window.currentUserInstInfo;
          const params = {
            instId,
            assetsId,
            paymentType: payType == "wechatPay" ? "WECHAT" : "ALIPAY",
            rechargeAmount: amount > 20000 ? 20000 : amount,
            operatorId: !!teacherId ? teacherId : adminId,
            reqSn: parseInt(Math.random() * Math.pow(10, 16)),
          };
          this.reChargeSubmit("public/liveAssets/recharge", params);
        });
    },
    1000,
    true
  );
  reChargeSubmit = (url, params) => {
    axios.Business(url, params).then((res) => {
      const data = res.result;
      this.setState(
        {
          orderId: data.orderId,
          step: 2,
          payStatus: 0,
        },
        () => {
          this.getQrcode(data);
          this.cutDownTimer();
        }
      );
    });
  };

  //获取二维码
  getQrcode = (payInfo) => {
    const text = payInfo.qrUrl;
    setTimeout(() => {
      const qrcodeNode = new qrcode({
        text,
        size: 150,
      });
      if (!document.querySelector("#qrcode").innerHTML) {
        document.querySelector("#qrcode").appendChild(qrcodeNode);
      }
    });
  };
  cutDownTimer = () => {
    this.timer = setInterval(() => {
      this.getDealStatus(true);
    }, 5000);
  };
  //获取订单状态
  getDealStatus = (flag) => {
    axios
      .Business("public/liveAssets/rechargeState", {
        orderId: this.state.orderId,
      })
      .then((res) => {
        if (res.result == "PAY_SUCCESS") {
          // 2是已支付
          $(".qr-code-row #qrcode").innerHTML = "";
          this.setState({ payStatus: 1 });
          clearInterval(this.timer);
        } else {
          if (!flag) {
            message.info("支付未完成");
          }
          return;
        }
      });
  };

  //关闭弹窗
  handleCancel = () => {
    const { step, payStatus } = this.state;
    if (step == 2 && !payStatus) {
      Modal.confirm({
        title: "确定要放弃支付？",
        content: `你的订单在30分钟内未支付将被取消，请尽快完成支付。`,
        okText: "确认离开",
        cancelText: "继续支付",
        icon: <QuestionCircleOutlined />,
        onCancel: () => {},
        onOk: () => {
          clearInterval(this.timer);
          this.handleFresh();
        },
      });
    } else {
      if(payStatus == 1) {
        this.props.refresh();
      }
      clearInterval(this.timer);
      this.props.close();
    }
  };
  //打开协议弹窗
  handleToAgreement = () => {
    const agreement = (
      // <AccountArgeement
      //   close={() => {
      //     this.setState({
      //       agreement: null,
      //     });
      //   }}
      // />
    ge);
    this.setState({
      agreement,
    });
  };
  handleChangeAmount = (val) => {
      val = val > 20000 ? 20000 : val;
      this.setState({
        amount: val ? parseInt(val) : null,
        amoutHelp: "最少充值500元",
        validateStatus: null,
      });
  };

  //关闭弹窗并刷新页面
  handleFresh = () => {
    this.props.close();
    this.props.refresh();
  };

  render() {
    const {
      payType,
      payStatus,
      step,
      amount,
      validateStatus,
      amoutHelp,
      balance,
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Modal
        title="充值"
        visible={true}
        width={550}
        footer={null}
        className="account-charge-modal"
        onCancel={() => {
          this.handleCancel();
        }}
      >
        <div>
          {step == 1 && (
            <div>
              <Form style={{ width: 320, margin: "0 auto" }}>
                <FormItem {...layout} label="当前余额:">
                  <span>{balance.toFixed(2)}元</span>
                </FormItem>
                <FormItem
                  {...layout}
                  label="充值金额"
                  help={amoutHelp}
                  validateStatus={validateStatus}
                >
                  <InputNumber
                    name="price"
                    style={{
                      width: 120,
                      borderColor: "#e8e8e8",
                      color: "#333",
                    }}
                    onChange={this.handleChangeAmount}
                    placeholder="请输入"
                    value={amount}
                  />
                  <span style={{ marginLeft: 4 }}>元</span>
                </FormItem>
                <FormItem {...layout} label="支付方式:">
                  <Row type="flex" justify="start">
                    <Col>
                      <div
                        className={classNames("wechat-pay pay-item", {
                          active: payType == "wechatPay",
                        })}
                        onClick={() => {
                          this.changePayType("wechatPay");
                        }}
                      >
                        <span className="pay-radio-inner"></span>
                        <span className="icon-weixin icon iconfont">
                          &#xe659;
                        </span>
                        <span>微信</span>
                      </div>
                    </Col>
                    <Col>
                      <div
                        className={classNames("ali-pay pay-item", {
                          active: payType == "aliPay",
                        })}
                        onClick={() => {
                          this.changePayType("aliPay");
                        }}
                      >
                        <span className="pay-radio-inner"></span>
                        <span className="icon-ali icon iconfont">&#xe685;</span>
                        <span>支付宝</span>
                      </div>
                    </Col>
                  </Row>
                </FormItem>
                <FormItem>
                  <Button
                    type="primary"
                    style={buttonStyle}
                    onClick={this.handleReChareg}
                  >
                    充值
                  </Button>
                  <div className="charge-tips">
                    确认充值即表示已阅读并同意
                    <span
                      onClick={() => {
                        this.handleToAgreement();
                      }}
                    >
                      《服务协议》
                    </span>
                  </div>
                </FormItem>
              </Form>
            </div>
          )}
          {step == 2 && (
            <div>
              {!payStatus ? (
                <div className="pay-wrapper">
                  <div className="notice">
                    请用
                    <span
                      style={{
                        color: payType == "aliPay" ? "#58b7ef" : "#42ae3c",
                      }}
                    >
                      {payType == "aliPay" ? "支付宝" : "微信"}
                    </span>
                    扫一扫付款
                  </div>
                  <div className="money">￥{amount.toFixed(2)}</div>
                  <div className="qr-code" id="qrcode"></div>
                </div>
              ) : (
                <div className="pay-success">
                  <div className="img-wrap">
                    <span
                      className="icon iconfont"
                      style={{ fontSize: 60, color: "#5DD333" }}
                    >
                      &#xe800;
                    </span>
                  </div>
                  <p className="pay-success-name">充值成功</p>
                  <p className="pay-success-tip">
                    充值成功{amount.toFixed(2)}元，你可以到订单列表查看。
                  </p>
                  <Button type="primary" onClick={this.handleFresh}>
                    我知道了
                  </Button>
                </div>
              )}
            </div>
          )}
        </div>
        {this.state.agreement}
      </Modal>
    );
  }
}

export default AccountChargeModal;
