import React from "react";
import OstMask from "../OstMask/index";
import Loading from "../Loading/index";
import * as Utils from "./utils/utils";
import * as RequsetFetch from "./services/services";
import WeChat from "orcrist-wechat";
import NumberCode from "./components/NumberCode";
import GraphicCode from "./components/GraphicCode";

interface LoginProps {
  isPopup: boolean;
  phoneNumber: any;
  closeNumberCodeHandle: any;
  callback?: any;
}

interface LoginState {
  count: number;
  phoneNumber?: string;
  numberCode?: string;
  inputGraphicCode?: string;
  graphicCode?: string;
  isSending?: boolean;
  isSendingGraphic?: boolean;
  isWxlogined?: boolean;
  isWxEnv?: boolean;
  loading: {
    isLoading?: boolean;
  };
}
let countDownTimer: any = null;
export default class LoginC extends React.Component<LoginProps, LoginState> {
  constructor(props: Readonly<LoginProps>) {
    super(props);

    const isweixin = Utils.isweixin();
    this.state = {
      count: 120,
      phoneNumber: "",
      numberCode: "",
      inputGraphicCode: "",
      graphicCode: "",
      isSending: false,
      isSendingGraphic: false,
      isWxlogined: true,
      isWxEnv: isweixin,
      loading: {
        isLoading: false,
      },
    };
  }

  //getDerivedStateFromProps
  static getDerivedStateFromProps(props: any, state: any) {
    // console.info("getDerivedStateFromProps", props, state);
    const { isPopup, phoneNumber } = props;
    const { isWxEnv, isWxlogined } = state;

    if (isPopup && ((isWxEnv && isWxlogined === false) || !isWxEnv)) {
      //微信环境下，openid查询用户没有token后或者h5环境

      if (phoneNumber !== state.phoneNumber) {
        return {
          phoneNumber: props.phoneNumber,
          isWxlogined: false,
        };
      } else {
        return { isWxlogined: false };
      }
    }
    return null;
  }

  queryUser = (openid: string) => {
    let queryUserPromise = RequsetFetch.queryUserIdFetch(openid)();
    queryUserPromise.then((resData: any) => {
      if (resData && resData.success && resData.data) {
        let token = resData.data.jwtToken;
        sessionStorage.setItem("SP_TOKEN", token);
        sessionStorage.setItem("SP_LOGIN", JSON.stringify(resData.data));
        this.LoginedCallback();
        this.setState({
          isWxlogined: true,
        });
      } else {
        this.setState({
          isWxlogined: false,
        });
      }
    });
  };

  componentDidUpdate(preProps: any, preState: any) {
    // console.log("componentDidUpdate", preProps, preState, this.state);
    const { isPopup, phoneNumber } = this.props;
    let { isWxEnv, isWxlogined } = this.state;

    //微信环境openid用户查询
    if (isPopup && isWxEnv && isWxlogined === true) {
      //查询token判断
      let openid = sessionStorage.getItem("SP_WX_OPENID");
      //微信
      if (!!openid) {
        this.queryUser(openid);
      } else {
        WeChat.authorize().then(({ code, data, type }: any) => {
          if (code === 20000 && type === "openID") {
            this.queryUser(data);
          } else if (code === 20000 && type === "userINFO") {
            this.queryUser(data.openid);
          }
        });
      }
    }

    //登录组件发送验证码接口
    if (isPopup && !isWxlogined && preState.phoneNumber !== phoneNumber) {
      this.sendCodeHandle(phoneNumber);
    }
  }

  //发送验证码
  sendCodeHandle = (phoneNumber: string) => {
    if (!Utils.phoneNumberCheck(phoneNumber)) {
      Utils.Toast("输入手机号有误", 2);
      return false;
    }

    this.setState({
      loading: {
        isLoading: true,
      },
      numberCode: "",
    });

    let sendCodePromise = RequsetFetch.sendCodeFetch(phoneNumber)();
    sendCodePromise.then((resData: any) => {
      this.setState({
        loading: {
          isLoading: false,
        },
      });
      if (resData && resData.success) {
        this.setState({
          isSending: true,
          isSendingGraphic: false,
          inputGraphicCode: "",
        });
        this.countDownHandle()();
      } else if (
        (resData && resData.code === "10002") ||
        resData.code === "10003"
      ) {
        this.setState({
          loading: {
            isLoading: false,
          },
          isSending: false,
          isSendingGraphic: true,
        });
        this.sendGraphicCode();
      } else if (resData && resData.code) {
        let messages =
          Utils.getMessage(resData.code) ||
          `${resData.code}:${resData.message || ""}`;

        Utils.Toast(messages, 2);
      } else {
        Utils.Toast("网络异常，稍后再试", 3);
      }
    });
  };

  //请求图形验证码
  sendGraphicCode = () => {
    let phoneNumber = this.state.phoneNumber || "";

    if (!Utils.phoneNumberCheck(phoneNumber)) {
      Utils.Toast("输入手机号有误", 2);
      return false;
    }

    this.setState({
      loading: {
        isLoading: true,
      },
    });

    let graphicCodePromise = RequsetFetch.graphicCodeFetch(phoneNumber)();
    graphicCodePromise.then((resData: any) => {
      this.setState({
        loading: {
          isLoading: false,
        },
      });
      if (resData && resData.success) {
        this.setState({
          isSendingGraphic: true,
          graphicCode: resData.data,
        });
      } else if (resData && resData.code) {
        let messages =
          Utils.getMessage(resData.code) ||
          `${resData.code}:${resData.message || ""}`;

        Utils.Toast(messages, 2);
      } else {
        Utils.Toast("网络异常，稍后再试", 2);
      }
    });
  };

  //图形验证码输入
  inputGraphicCodeHandle = (e: any) => {
    let inputGraphicCode = e.target.value;
    this.setState({
      inputGraphicCode,
    });

    if (inputGraphicCode && inputGraphicCode.length === 4) {
      let phoneNumber = this.state.phoneNumber || "";

      if (!Utils.phoneNumberCheck(phoneNumber)) {
        Utils.Toast("输入手机号有误", 2);
        return false;
      }

      this.setState({
        loading: {
          isLoading: true,
        },
      });

      let vertifycodePromise = RequsetFetch.verifyCodeFetch(
        phoneNumber,
        inputGraphicCode
      )();
      vertifycodePromise.then((resData: any) => {
        this.setState({
          loading: {
            isLoading: false,
          },
        });
        if (resData && resData.success) {
          this.setState({
            isSending: true,
            isSendingGraphic: false,
            inputGraphicCode: "",
          });
          this.countDownHandle()();
        } else if (
          resData &&
          (resData.code === "10002" || resData.code === "10003")
        ) {
          this.sendGraphicCode();
          this.setState({
            isSending: false,
            isSendingGraphic: true,
            inputGraphicCode: "",
          });
          Utils.Toast("防刷验证码输入错误，请重新输入", 2);
        } else if (resData && resData.code) {
          let messages =
            Utils.getMessage(resData.code) ||
            `${resData.code}:${resData.message || ""}`;
          Utils.Toast(messages, 2);
        } else {
          Utils.Toast("网络异常，稍后再试", 3);
        }
      });
    }
  };

  //关闭图形验证码码·
  closeGraphicCodeHandle = () => {
    this.setState({
      isSendingGraphic: false,
    });
  };

  /* 倒计时 */
  countDownHandle = () => {
    let that = this;
    let { count } = this.state;
    if (countDownTimer) {
      count = 120;
      clearInterval(countDownTimer);
    }
    return function () {
      countDownTimer = setInterval(() => {
        if (count === 0) {
          clearInterval(countDownTimer);
          that.setState({
            isSending: false,
            count: 120,
          });
          return null;
        }
        that.setState({
          count: --count,
        });
      }, 1000);
    };
  };

  // 弹窗验证码
  numberCodeHandle = (e: any) => {
    let numberCode = e.target.value;
    if ((!numberCode || /[0-9*]/i.test(numberCode)) && numberCode.length < 7) {
      this.setState({
        numberCode: numberCode,
      });
    }
  };

  //关闭输入验证码框
  closeComponent = () => {
    const { closeNumberCodeHandle } = this.props;
    closeNumberCodeHandle && closeNumberCodeHandle();
  };

  //登录
  loginHandle = () => {
    let { numberCode, phoneNumber, isSending } = this.state;
    phoneNumber = phoneNumber || "";
    numberCode = numberCode || "";

    if (!Utils.phoneNumberCheck(phoneNumber)) {
      Utils.Toast("输入手机号有误", 2);
      return false;
    }

    if (!Utils.numberCodeCheck(numberCode)) {
      Utils.Toast("请输入六位验证码", 2);
      return false;
    }

    if (!isSending) {
      Utils.Toast("验证码已过期，请重新发送", 2);
      return false;
    }

    this.setState({
      loading: {
        isLoading: true,
      },
    });
    let loginPromise = RequsetFetch.loginFetch(phoneNumber, numberCode)();
    loginPromise.then((resData: any) => {
      this.setState({
        loading: {
          isLoading: false,
        },
      });
      if (resData && resData.success) {
        let token = resData.data.jwtToken;
        sessionStorage.setItem("SP_TOKEN", token);
        sessionStorage.setItem("SP_LOGIN", JSON.stringify(resData.data));
        clearInterval(countDownTimer);
        this.setState({
          isSending: false,
        });
        this.LoginedCallback();
      } else if (resData && resData.code) {
        let messages =
          Utils.getMessage(resData.code) ||
          `${resData.code}:${resData.message || ""}`;
        if (resData.code === "10004" || resData.code === "10011") {
          this.setState({
            isSending: false,
            numberCode: "",
          });
          clearInterval(countDownTimer);
        } else if (resData.code === "10005") {
          this.setState({
            numberCode: "",
          });
        }
        Utils.Toast(messages, 2);
      } else {
        Utils.Toast("网络异常，稍后再试", 3);
      }
    });
  };

  //组件登录成功回调
  LoginedCallback = () => {
    const { closeNumberCodeHandle, callback } = this.props;
    closeNumberCodeHandle && closeNumberCodeHandle();
    callback && callback();
  };

  render() {
    let { isPopup, phoneNumber } = this.props;
    let {
      numberCode,
      isSending,
      isSendingGraphic,
      inputGraphicCode,
      graphicCode,
      loading,
      isWxlogined,
      count,
    } = this.state;

    if (isPopup && isWxlogined) {
      return (
        <div>
          <Loading isLoading={isWxlogined} />
        </div>
      );
    } else if (isPopup && !isWxlogined && !isSendingGraphic) {
      return (
        <OstMask show={isPopup && !isSendingGraphic}>
          <NumberCode
            phoneNumber={phoneNumber}
            numberCode={numberCode}
            count={count}
            isSending={isSending}
            sendCodeHandle={this.sendCodeHandle.bind(this, phoneNumber)}
            numberCodeHandle={this.numberCodeHandle}
            loginHandle={this.loginHandle}
            closeComponent={this.closeComponent}
          />
          <Loading isLoading={loading.isLoading} />
        </OstMask>
      );
    } else if (isPopup && !isWxlogined && isSendingGraphic) {
      return (
        <OstMask show={isPopup && isSendingGraphic}>
          <GraphicCode
            inputGraphicCode={inputGraphicCode}
            graphicCode={graphicCode}
            sendGraphicCodeHandle={this.sendGraphicCode}
            closeGraphicCodeHandle={this.closeGraphicCodeHandle}
            inputGraphicCodeHandle={this.inputGraphicCodeHandle}
          />
          <Loading isLoading={loading.isLoading} />
        </OstMask>
      );
    } else {
      return <OstMask show={false}></OstMask>;
    }
  }
}
