import { asyncDelay, buttonOnClick, jumpToBundle, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";

const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

  async onLoadEnd() {
    this.initData();
    this.initListener();
  }

  middleLayer;
  orgId = 507;
  initData() {
    const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
    if (middleLayer) {
      this.middleLayer = middleLayer;
      this.orgId = middleLayer.ORG_ID || 507;
    }
    cc.find(`Canvas/bg/ui/logo`).active = this.orgId === 507;
    cc.find(`Canvas/bg/ui/logolite`).active = this.orgId !== 507;
    cc.find('Canvas/bg/ui/tryatry').active = this.orgId !== 507;

  }

  async login(phone, password, passCode = '') {
    if (!this.checkPhone(phone)) {
      console.log('请输入正确的手机号码');
      this.middleLayer.showTips('请输入正确的手机号码');
      return;
    }

    const oldPhone = cc.sys.localStorage.getItem('phone');
    if (`${phone}_x` === oldPhone) {
      console.log("用户不存在，请先注册");
      this.middleLayer.showTips('用户不存在，请先注册');
      return;
    }

    const check = cc.find('Canvas/bg/ui/btnLaw/check');
    if (!check.active) {
      console.log('请勾选下方协议');
      this.middleLayer.showTips('请勾选下方协议');
      return;
    }

    const res = await this.middleLayer.asyncCallNetworkApiPost('/api/oxford/v1/login', {
      phone: phone,
      password: password,
      sms_code: passCode
    });
    if (res.code != '200') {
      this.middleLayer.showTips(res.msg);
      return;
    }
    this.middleLayer.isLogin = true;
    cc.sys.localStorage.setItem('token', res.token);
    cc.sys.localStorage.setItem('phone', phone);
    jumpToBundle('NJ_YouLeChang');
  }

  checkPhone(phone) {
    const test = /^[1]([3-9])[0-9]{9}$/;
    if (!test.test(phone)) {
      return false;
    }
    return true;
  }

  checkPassword(pwd) {
    let validationStr = /^(?=.*[0-9])(?=.*[a-zA-Z])(.{8,})$/;
    if (!validationStr.test(pwd)) {
      return false;
    }
    return true;
  }

  async sendCode(phone) {
    if (!this.checkPhone(phone)) {
      console.log('请输入正确的手机号码');
      this.middleLayer.showTips('请输入正确的手机号码');
      return;
    }
    const res = await this.middleLayer.asyncCallNetworkApiPost('/api/oxford/v1/sendcode', {
      phone: phone
    });
    console.log('res = ' + JSON.stringify(res));
  }

  initListener() {
    const btnLaw = cc.find('Canvas/bg/ui/btnLaw');
    buttonOnClick(btnLaw, () => {
      const check = cc.find('Canvas/bg/ui/btnLaw/check');
      check.active = !check.active;
    }, 1.02);

    const btnLogin = cc.find('Canvas/bg/ui/loginNode/btnLogin');
    buttonOnClick(btnLogin, async () => {
      const inputPhone = cc.find('Canvas/bg/ui/loginNode/phone/inputPhone');
      const phone = inputPhone.getComponent(cc.EditBox).string;
      const inputPassword = cc.find('Canvas/bg/ui/loginNode/password/password');
      const password = inputPassword.getComponent(cc.EditBox).string;

      this.login(phone, password);
    });


    const tryatry = cc.find('Canvas/bg/ui/tryatry');
    buttonOnClick(tryatry, () => {
      jumpToBundle('NJ_YouLeChang');
    });

    const btnResetPassword = cc.find('Canvas/bg/ui/forgetNode/btnResetPassword');
    buttonOnClick(btnResetPassword, async () => {
      const inputPhone = cc.find('Canvas/bg/ui/forgetNode/phone/inputPhone');
      const phone = inputPhone.getComponent(cc.EditBox).string;
      const inputPassword = cc.find('Canvas/bg/ui/forgetNode/password/password');
      const password = inputPassword.getComponent(cc.EditBox).string;

      if(!this.checkPassword(password)) {
        this.middleLayer.showTips('密码由字母大小写和数字组成，必须包含字母和数字且不得少于8位');
        inputPassword.getComponent(cc.EditBox).string == "";
        return;
      }

      const inputPassCode = cc.find('Canvas/bg/ui/forgetNode/passCode/passCode');
      const passCode = inputPassCode.getComponent(cc.EditBox).string;
      if (!passCode || passCode.length != 6) {
        this.middleLayer.showTips("请填写正确的验证码");
        return;
      }
      this.login(phone, password, passCode);
    });

    const btnRegister = cc.find('Canvas/bg/ui/registerNode/btnRegister');
    buttonOnClick(btnRegister, async () => {
      const inputPhone = cc.find('Canvas/bg/ui/registerNode/phone/inputPhone');
      const phone = inputPhone.getComponent(cc.EditBox).string;
      const inputPassword = cc.find('Canvas/bg/ui/registerNode/password/password');
      const password = inputPassword.getComponent(cc.EditBox).string;
      if(!this.checkPassword(password)) {
        this.middleLayer.showTips('密码由字母大小写和数字组成，必须包含字母和数字且不得少于8位');
        inputPassword.getComponent(cc.EditBox).string == "";
        return;
      }

      const inputPassCode = cc.find('Canvas/bg/ui/registerNode/passCode/passCode');
      const passCode = inputPassCode.getComponent(cc.EditBox).string;
      if (!passCode || passCode.length != 6) {
        this.middleLayer.showTips("请填写正确的验证码");
        return;
      }
      
      const oldPhone = cc.sys.localStorage.getItem('phone');
      if (`${phone}_x` === oldPhone) {
        cc.sys.localStorage.setItem('phone', '');
      }

      window["courseware"]?.behaviorToCollectWithParam("userRegistrationEvent", "");

      this.login(phone, password, passCode);
    });

    const btnSendCode = cc.find('Canvas/bg/ui/registerNode/passCode/btnSendCode');
    buttonOnClick(btnSendCode, async () => {
      const inputPhone = cc.find('Canvas/bg/ui/registerNode/phone/inputPhone');
      const phone = inputPhone.getComponent(cc.EditBox).string;

      const label = btnSendCode.getChildByName('label').getComponent(cc.Label);
      // 发送验证码
      if (label.string == '发送验证码') {
        let countDown = 60;
        const tween = cc.tween(label)
          .call(() => {
            label.string = `${countDown}`;
            if (countDown == 0) {
              label.string = '发送验证码';
              tween.stop();
            }
            countDown--;
          })
          .delay(1)
          .union()
          .repeatForever()
          .start();
      }
      this.sendCode(phone);
    });
    const btnSendCode2 = cc.find('Canvas/bg/ui/forgetNode/passCode/btnSendCode');
    buttonOnClick(btnSendCode2, async () => {
      const inputPhone = cc.find('Canvas/bg/ui/forgetNode/phone/inputPhone');
      const phone = inputPhone.getComponent(cc.EditBox).string;
      const label = btnSendCode2.getChildByName('label').getComponent(cc.Label);
      if (label.string == '发送验证码') {
        let countDown = 60;
        const tween = cc.tween(label)
          .call(() => {
            label.string = `${countDown}`;
            if (countDown == 0) {
              label.string = '发送验证码';
              tween.stop();
            }
            countDown--;
          })
          .delay(1)
          .union()
          .repeatForever()
          .start();
      }
      this.sendCode(phone);
    });

    const btnGotoRegister = cc.find('Canvas/bg/ui/loginNode/btnRegister');
    buttonOnClick(btnGotoRegister, () => {
      const loginNode = cc.find('Canvas/bg/ui/loginNode');
      const registerNode = cc.find('Canvas/bg/ui/registerNode');
      cc.tween(loginNode)
        .to(0.3, { scaleX: 0, x: 200 }, { easing: 'sineOut' })
        .call(() => {
          loginNode.active = false;
        })
        .start();
      registerNode.active = true;
      cc.tween(registerNode)
        .set({ scaleX: 0, x: -200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });
    const btnForgetPassword = cc.find('Canvas/bg/ui/loginNode/btnForgetPassword');
    buttonOnClick(btnForgetPassword, () => {
      const loginNode = cc.find('Canvas/bg/ui/loginNode');
      const forgetNode = cc.find('Canvas/bg/ui/forgetNode');
      cc.tween(loginNode)
        .to(0.3, { scaleX: 0, x: -200 }, { easing: 'sineOut' })
        .call(() => {
          loginNode.active = false;
        })
        .start();
      forgetNode.active = true;
      cc.tween(forgetNode)
        .set({ scaleX: 0, x: 200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });

    const btnGoToLogin = cc.find('Canvas/bg/ui/forgetNode/btnGoToLogin');
    buttonOnClick(btnGoToLogin, () => {
      const forgetNode = cc.find('Canvas/bg/ui/forgetNode');
      const loginNode = cc.find('Canvas/bg/ui/loginNode');
      cc.tween(forgetNode)
        .to(0.3, { scaleX: 0, x: -200 }, { easing: 'sineOut' })
        .call(() => {
          forgetNode.active = false;
        })
        .start();
      loginNode.active = true;
      cc.tween(loginNode)
        .set({ scaleX: 0, x: 200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });
    const btnRegister2 = cc.find('Canvas/bg/ui/forgetNode/btnRegister');
    buttonOnClick(btnRegister2, () => {
      const forgetNode = cc.find('Canvas/bg/ui/forgetNode');
      const registerNode = cc.find('Canvas/bg/ui/registerNode');
      cc.tween(forgetNode)
        .to(0.3, { scaleX: 0, x: 200 }, { easing: 'sineOut' })
        .call(() => {
          forgetNode.active = false;
        })
        .start();
      registerNode.active = true;
      cc.tween(registerNode)
        .set({ scaleX: 0, x: -200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });

    const btnGoToLogin2 = cc.find('Canvas/bg/ui/registerNode/btnGoToLogin');
    buttonOnClick(btnGoToLogin2, () => {
      const registerNode = cc.find('Canvas/bg/ui/registerNode');
      const loginNode = cc.find('Canvas/bg/ui/loginNode');
      cc.tween(registerNode)
        .to(0.3, { scaleX: 0, x: 200 }, { easing: 'sineOut' })
        .call(() => {
          registerNode.active = false;
        })
        .start();
      loginNode.active = true;
      cc.tween(loginNode)
        .set({ scaleX: 0, x: -200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });
    const btnForgetPassword2 = cc.find('Canvas/bg/ui/registerNode/btnForgetPassword');
    buttonOnClick(btnForgetPassword2, () => {
      const registerNode = cc.find('Canvas/bg/ui/registerNode');
      const forgetNode = cc.find('Canvas/bg/ui/forgetNode');
      cc.tween(registerNode)
        .to(0.3, { scaleX: 0, x: -200 }, { easing: 'sineOut' })
        .call(() => {
          registerNode.active = false;
        })
        .start();
      forgetNode.active = true;
      cc.tween(forgetNode)
        .set({ scaleX: 0, x: 200 })
        .to(0.3, { scaleX: 1, x: 0 }, { easing: 'sineIn' })
        .start();
    });
  

    const privacy = cc.find(`Canvas/bg/ui/btnLaw/privacy`);
    privacy.on('click', () => {
      this.onOpenPrivacy();
    });
    const policy = cc.find(`Canvas/bg/ui/btnLaw/policy`);
    policy.on('click', () => {
      this.onOpenPolicy();
    });
    const closeWebbtn = cc.find(`Canvas/bg/webContainer/closeWebbtn`);
    closeWebbtn.on('click', () => {
      this.closeWebView();
    });


    // 环境切换后门(两秒内连点十下以上)
    // Canvas/bg/bg_oxford
    const bk = cc.find(`Canvas/bg/bg_oxford`);
    bk.on('click', () => {
      const bk_count = bk["bk_count"];
      if (!bk_count) {
        bk.attr({bk_count: 1});
        setTimeout(() => {
          const real = cc.find(`Canvas/bg/bg_oxford`);
          if (real["bk_count"] == 6) {
            // 切换一个纸书调试
            const isDebug = cc.sys.localStorage.getItem('isDebug');
            cc.sys.localStorage.setItem('isDebug', isDebug?'':'true');
            this.middleLayer.showTips(`已切换为 ${isDebug?'正常':'Debug'} 模式`);
          }
          // this.middleLayer.showTips(`时间到 ${real["bk_count"]}`);
          real.attr({bk_count: null});
        }, 2000);
      } else if (bk_count>10){
        window["courseware"]?.changeHost();
      } else {
        bk.attr({bk_count: bk_count+1});
      }
    });

  }

  onOpenPrivacy() {
    const web_container = cc.find(`Canvas/bg/webContainer`);
    const web_view = cc.find(`webBg/webview`, web_container);
    web_view.getComponent(cc.WebView).url = "https://appstore.iteachabc.com/application/web/privacy_policy/oxford_privacy.html?t="+Date.now();
    web_container.active = true;
  }
  onOpenPolicy() {
    const web_container = cc.find(`Canvas/bg/webContainer`);
    const web_view = cc.find(`webBg/webview`, web_container);
    web_view.getComponent(cc.WebView).url = "https://appstore.iteachabc.com/application/web/privacy_policy/oxford_policy.html?t="+Date.now();
    web_container.active = true;
  }
  closeWebView() {
    const web_container = cc.find(`Canvas/bg/webContainer`);
    web_container.active = false;
  }

  // onDestroy() {
  //   setTimeout(() => {
  //     cc.find(`Canvas/bg/webContainer`).active = false;
  //   }, 5000);
  // }

}
