import { asyncDelay, buttonOnClick, jumpToBundle, onHomeworkFinish } from "../script/util";
import { MyCocosSceneComponent } from "../script/MyCocosSceneComponent";
import { lang as languageString, langConfig} from "../script/language_NJ_login"
const { ccclass, property } = cc._decorator;

@ccclass
export default class SceneComponent extends MyCocosSceneComponent {

  async onLoadEnd() {
    this.initData();
    // 本地化
    this.localization();
    this.initListener();
  }

  middleLayer;
  orgId = 507;
  localLanguage = "zh-cn"
  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(languageString[this.localLanguage].phone_error);
      return;
    }

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

    const check = cc.find('Canvas/bg/ui/btnLaw/check');
    if (!check.active) {
      console.log('请勾选下方协议');
      this.middleLayer.showTips(languageString[this.localLanguage].check_agreement);
      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');
  }

  localization() {
    if(!this.middleLayer || !this.middleLayer.getLocalLanguage) {
      console.log("未检测到中间层，或中间层不支持getLocalLanguage, 使用默认语言")
      return
    }

    const localLanguage = this.middleLayer.getLocalLanguage()

    if(!languageString[localLanguage] || !langConfig[localLanguage]) {
      console.log(`语言${localLanguage}未找到，使用默认语言`)
      return
    }

    this.localLanguage = localLanguage;

    this.translateLanguageString();
    this.repositionLaws();
  }

  translateLanguageString() {
    console.log(`使用语言${this.localLanguage}`)
    // 点击输入手机号
    cc.find("Canvas/bg/ui/loginNode/phone/inputPhone").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_phone;
    cc.find("Canvas/bg/ui/forgetNode/phone/inputPhone").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_phone;
    cc.find("Canvas/bg/ui/registerNode/phone/inputPhone").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_phone;
    
    // 点击输入密码
    cc.find("Canvas/bg/ui/loginNode/password/password").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_password;
    cc.find("Canvas/bg/ui/forgetNode/password/password").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_new_password;
    cc.find("Canvas/bg/ui/registerNode/password/password").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_password;

    // 点击输入验证码
    cc.find("Canvas/bg/ui/forgetNode/passCode/passCode").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_code;
    cc.find("Canvas/bg/ui/registerNode/passCode/passCode").getComponent(cc.EditBox).placeholder = languageString[this.localLanguage].click_input_code;

    // 发送验证码
    cc.find("Canvas/bg/ui/forgetNode/passCode/btnSendCode/label").getComponent(cc.Label).string = languageString[this.localLanguage].send_code;
    cc.find("Canvas/bg/ui/registerNode/passCode/btnSendCode/label").getComponent(cc.Label).string = languageString[this.localLanguage].send_code;

    // 马上登录
    cc.find("Canvas/bg/ui/loginNode/btnLogin/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].login_right_now;
    cc.find("Canvas/bg/ui/forgetNode/btnGoToLogin/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].login_right_now;
    cc.find("Canvas/bg/ui/registerNode/btnGoToLogin/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].login_right_now;

    // 重置并登录
    cc.find("Canvas/bg/ui/forgetNode/btnResetPassword/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].reset_and_login;

    // 注册并登录
    cc.find("Canvas/bg/ui/registerNode/btnRegister/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].register_and_login;

    // 立即注册
    cc.find("Canvas/bg/ui/loginNode/btnRegister/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].register_now;
    cc.find("Canvas/bg/ui/forgetNode/btnRegister/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].register_now;
    
    // 忘记密码
    cc.find("Canvas/bg/ui/loginNode/btnForgetPassword/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].forget_password;
    cc.find("Canvas/bg/ui/registerNode/btnForgetPassword/New Label").getComponent(cc.Label).string = languageString[this.localLanguage].forget_password;
    
    // 不想登录？去游乐场
    cc.find("Canvas/bg/ui/tryatry/text").getComponent(cc.Label).string = languageString[this.localLanguage].tryatry;

    // 关闭
    cc.find("Canvas/bg/webContainer/closeWebbtn").getComponent(cc.Label).string = languageString[this.localLanguage].close;

    // 我已阅读并同意 用户隐私保护政策 及 服务条款
    cc.find("Canvas/bg/ui/btnLaw/New Label_1").getComponent(cc.Label).string = languageString[this.localLanguage].law.split("/@/")[0];
    cc.find("Canvas/bg/ui/btnLaw/privacy").getComponent(cc.RichText).string = `<color=#fee60a>《${languageString[this.localLanguage].law.split("/@/")[1]}》</c>`;
    cc.find("Canvas/bg/ui/btnLaw/New Label_2").getComponent(cc.Label).string = languageString[this.localLanguage].law.split("/@/")[2];
    cc.find("Canvas/bg/ui/btnLaw/policy").getComponent(cc.RichText).string = `<color=#fee60a>《${languageString[this.localLanguage].law.split("/@/")[3]}》</c>`;
  }

  repositionLaws() {
    // 针对俄语调整协议、声明的位置
    if(this.localLanguage == "ru-ru") {
      cc.find("Canvas/bg/ui/btnLaw/radio").x = -275.074;
      cc.find("Canvas/bg/ui/btnLaw/check").x = -275.074;
      cc.find("Canvas/bg/ui/btnLaw/New Label_1").x = -254.576;
      cc.find("Canvas/bg/ui/btnLaw/privacy").x = -138.207;
      cc.find("Canvas/bg/ui/btnLaw/New Label_2").x = 77.799;
      cc.find("Canvas/bg/ui/btnLaw/policy").x = 86.604;
    }
  }

  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(languageString[this.localLanguage].phone_error);
      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(languageString[this.localLanguage].password_format_error);
        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(languageString[this.localLanguage].password_format_error);
        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(languageString[this.localLanguage].code_error);
        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 == languageString[this.localLanguage].send_code) {
        let countDown = 60;
        const tween = cc.tween(label)
          .call(() => {
            label.string = `${countDown}`;
            if (countDown == 0) {
              label.string = languageString[this.localLanguage].send_code;
              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 == languageString[this.localLanguage].send_code) {
        let countDown = 60;
        const tween = cc.tween(label)
          .call(() => {
            label.string = `${countDown}`;
            if (countDown == 0) {
              label.string = languageString[this.localLanguage].send_code;
              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 = langConfig[this.localLanguage].privacy_url+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 = langConfig[this.localLanguage].policy_url+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);
  // }

}
