import React, { useContext, useState, useCallback } from "react";
import {
  Button,
  Box,
  Radio,
  FormControlLabel,
  RadioGroup,
  InputAdornment,
  TextField,
  FormControl,
} from "@mui/material";
import PageLayout from "../../../Common/Layout/PageLayout";
import PageHeader from "../../../Common/PageHeader/PageHeader";
import AlipayImg from "../../assets/alipay.jpeg";
import WechatImg from "../../assets/wechat.png";
import OfflineImg from "../../assets/offline.png";
import { createOrder, getOrderInfo } from "../../services";
import { CreateOrderRequestBody } from "../../services/interface";
import { PAY, PAY_TYPE } from "../../constants";
import Modal from "../../components/Modal";
import OfflinePayContent from "./components/OfflinePayContent";

import styles from "./index.module.css";
import { UserInfoContext } from "../../context/UserInfoContext";
import { useAccountMoneyInfo } from "./hooks";
import { toNewTab } from "../../utils";
import QrCode from "../../components/QrCode";
import message from "../../../../../utils/message";
import history from "../../../../../history";

const startAdornment = <InputAdornment position="start">￥</InputAdornment>;
const payTypeList = [
  {
    cname: PAY.ALI.cname,
    value: PAY.ALI.value,
    logo: AlipayImg,
  },
  {
    cname: PAY.WECHAT.cname,
    value: PAY.WECHAT.value,
    logo: WechatImg,
  },
  {
    cname: "银联",
    value: 3,
    logo: OfflineImg,
  },
];

class OfflinePayModal {
  visible: boolean = false;
}

class QrCodeModal {
  visible: boolean = false;
  value: string;
}

function loadPayStatus(orderID: string) {
  // 轮询订单状态
  const getInfo = () => {
    getOrderInfo(orderID).then((res) => {
      if (!res.data.pay_status) {
        setTimeout(() => {
          getInfo();
        }, 2000);
      } else {
        message.success("充值成功");
        history.push("/saturn/cost");
      }
    });
  };
  getInfo();
}

const CostRecharge: React.FC = () => {
  const userInfo = useContext(UserInfoContext);
  const { data: moneyInfo } = useAccountMoneyInfo();
  const [loading, setLoading] = useState(false);
  const [offlinePayModal, setOfflinePayModal] = useState<OfflinePayModal>(
    new OfflinePayModal()
  );
  const [qrCodeModal, setQrCodeModal] = useState<QrCodeModal>(
    new QrCodeModal()
  );
  const [form, setForm] = useState<CreateOrderRequestBody>({
    money: 5000,
    pay_type: 1,
  });
  const submitHandler = useCallback(
    (e) => {
      e.preventDefault();
      setLoading(true);
      createOrder(form)
        .then((res) => {
          if (form.pay_type === PAY.ALI.value) {
            toNewTab(res.data.url);
          }
          if (form.pay_type === PAY.WECHAT.value) {
            setQrCodeModal((state) => ({
              ...state,
              visible: true,
              value: res.data.url,
            }));
          }
          loadPayStatus(res.data.order_num);
        })
        .finally(() => {
          setLoading(false);
        });
    },
    [form]
  );

  function offlineModalShow() {
    setOfflinePayModal((state) => ({ ...state, visible: true }));
  }
  function offlineModalHide() {
    setOfflinePayModal((state) => ({ ...state, visible: false }));
  }
  function qrCodeModalHide() {
    setQrCodeModal((state) => ({ ...state, visible: false }));
  }

  return (
    <>
      <PageHeader label="充值"></PageHeader>
      <PageLayout>
        <>
          <Box
            sx={{
              "& .MuiTextField-root": { mb: 3 },
            }}
            style={{ maxWidth: 500 }}
          >
            <TextField
              fullWidth
              label="充值账户"
              value={userInfo?.phone || userInfo?.email}
              InputProps={{ readOnly: true }}
            />
            <TextField
              fullWidth
              label="账户余额"
              name="money"
              value={moneyInfo.balance}
              InputProps={{ readOnly: true, startAdornment }}
            />
            <TextField
              fullWidth
              required
              label="充值金额"
              value={form.money}
              type="number"
              inputMode="numeric"
              inputProps={{ min: 5000, step: 1000 }}
              InputProps={{
                startAdornment,
              }}
              helperText="充值金额不低于5000元，且为1000的整数倍"
              onChange={(e) => {
                let value = Number(e.target.value);
                setForm((state) => ({ ...state, money: value }));
              }}
              onBlur={(e) => {
                let value = Number(e.target.value);
                if (value < 5000) {
                  value = 5000;
                }
                if (value % 1000) {
                  value -= value % 1000;
                }
                setForm((state) => ({ ...state, money: value }));
              }}
            />
            <FormControl>
              <RadioGroup
                row
                name="pay_type"
                value={form.pay_type}
                onChange={(e) => {
                  const value = Number(e.target.value) as PAY_TYPE;
                  setForm((state) => ({ ...state, pay_type: value }));
                }}
              >
                {payTypeList.map((pay) => {
                  return (
                    <FormControlLabel
                      key={pay.value}
                      value={pay.value}
                      control={<Radio />}
                      label={
                        <div className={styles.payType}>
                          <img src={pay.logo} alt="" />
                        </div>
                      }
                      onClick={() => {
                        if (pay.value === 3) {
                          offlineModalShow();
                        }
                      }}
                    />
                  );
                })}
              </RadioGroup>
            </FormControl>

            <div style={{ marginTop: 40 }}>
              <Button
                variant="contained"
                type="submit"
                disabled={loading}
                onClick={submitHandler}
              >
                充 值
              </Button>
            </div>
            {/* <Alert color="warning">
            <AlertTitle>提示</AlertTitle>
            当您在使用 Safari、QQ 等浏览器进行支付宝充值时，若出现{" "}
            <strong>弹出式窗口被阻止</strong> 请在 <strong>偏好设置</strong>中
            <strong>选择网络</strong> <span>{"-->"}</span>{" "}
            <strong>弹出式窗口</strong>
            <span>{"-->"}</span> <strong>允许</strong> 即可！
          </Alert> */}
          </Box>
          <Modal
            visible={offlinePayModal.visible}
            onCancel={offlineModalHide}
            title="支付中心"
            width={700}
          >
            <OfflinePayContent />
          </Modal>
          <Modal
            visible={qrCodeModal.visible}
            onCancel={qrCodeModalHide}
            title="微信扫码支付"
            width={400}
            footer={false}
          >
            <div style={{ textAlign: "center" }}>
              支付金额：<strong>{form.money}</strong> 元
            </div>
            <QrCode
              value={qrCodeModal.value}
              options={{ width: 300, margin: 1 }}
              className={styles.qrcodeImage}
            />
          </Modal>
        </>
      </PageLayout>
    </>
  );
};

export default CostRecharge;
