import { PlatformLocation } from '@angular/common';
import { Component, Inject, OnDestroy, OnInit, Optional } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { GeneralHttpService, GeneralUtilsService, StartupService } from '@core';
import { ReuseTabService } from '@delon/abc/reuse-tab';
import { ACLService } from '@delon/acl';
import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { CacheService } from '@delon/cache';
import { _HttpClient, MenuService, SettingsService, TitleService } from '@delon/theme';
// import { environment } from '@env/environment';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';

@Component({
  selector: 'passport-free-login-inline',
  templateUrl: './loginFreeInline.component.html',
  styleUrls: ['./loginFreeInline.component.less']
})
export class UserLoginFreeInlineComponent implements OnInit {
  loginType = [];
  form: FormGroup;
  error = '';
  type = 0;
  code = '';

  // #region get captcha

  count = 0;
  interval$: any;
  computerModel = false;
  computerIp = '';
  computerMac = '';
  computerSerial = '';
  mainBoardSerial = '';
  promptInfo = '';
  smscode = '';
  rescode = '';
  resmobile = '';

  customRouterUrl = '';
  customLoginType = 'SingleSignOn';
  otherPars = '';
  // 免密登录用户
  secretFreeUser = '';
  // 免密登录连接
  secretFreeUrl = '';
  // 免密登录参数
  secretFreeUrlPar = '';
  secretFreeUrlLimit = '';

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private menuService: MenuService,
    private settingsService: SettingsService,
    private aclService: ACLService,
    // private socialService: SocialService,
    @Optional()
    @Inject(ReuseTabService)
    private reuseTabService: ReuseTabService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    public http: _HttpClient,
    public msg: NzMessageService,
    public utils: GeneralUtilsService,
    private titleService: TitleService,
    private httpUtils: GeneralHttpService,
    public srv: CacheService,
    private notification: NzNotificationService,
    private location: PlatformLocation
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(4)]],
      password: [null, Validators.required],
      mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      captcha: [null, [Validators.required]],
      remember: [true]
    });
    modalSrv.closeAll();
  }

  ngOnInit(): void {
    console.log(this.location);
    const freeLoginUrl = this.location.href.replace('%3D', '=');
    console.log('freeLoginUrl', freeLoginUrl);
    if (freeLoginUrl) {
      const urls = freeLoginUrl.split('?');
      if (urls && urls[1]) {
        if (urls[1].indexOf('token=') >= 0) {
          const strs = urls[1].split('&');
          let rid = '';
          strs.forEach(v => {
            if (v.indexOf('token=') === 0) {
              rid = v.replace('token=', '');
            } else if (v.indexOf('customRouterUrl=') === 0) {
              this.customRouterUrl = v.replace('customRouterUrl=', '');
            } else {
              if (this.otherPars === '') {
                this.otherPars = v;
              } else {
                this.otherPars = this.otherPars + '&' + v;
              }
            }
          });
          this.login(rid);
        } else if (urls[1].indexOf('secretFreeUser=') === 0) {
          this.customLoginType = 'secretFree';
          const strs = urls[1].split('&');
          this.secretFreeUser = strs[0].replace('secretFreeUser=', '');
          this.secretFreeUrl = strs[1].replace('secretFreeUrl=', '');
          if (strs.length === 3) {
            if (strs[2].indexOf('secretFreeUrlLimit=') === 0) {
              this.secretFreeUrlLimit = strs[2].replace('secretFreeUrlLimit=', '');
            }
          }

          if (strs.length > 2) {
            for (let i = 2; i < strs.length; i++) {
              if (strs[i].indexOf('secretFreeUrlLimit=') === -1) {
                if (this.secretFreeUrlPar === '') {
                  this.secretFreeUrlPar = strs[i];
                } else {
                  this.secretFreeUrlPar = this.secretFreeUrlPar + '&' + strs[i];
                }
              }
            }
          }
          this.login(this.secretFreeUser);
        } else if (urls[1].indexOf('code=') >= 0) {
          this.customLoginType = 'bySso';
          const rid = urls[1].replace('code=', '');
          this.login(rid);
        }
        // const pars = par.split('_');
        // const userName = this.decode(pars[0]);
        // const passWord = this.decode(pars[1]);
      } else {
        console.log('error');
      }
    }
  }

  decode(ciphertext: String) {
    let _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    var t = '';
    var n, r, i;
    var s, o, u, a;
    var f = 0;
    ciphertext = ciphertext.replace(/[^A-Za-z0-9+/=]/g, '');
    while (f < ciphertext.length) {
      s = _keyStr.indexOf(ciphertext.charAt(f++));
      o = _keyStr.indexOf(ciphertext.charAt(f++));
      u = _keyStr.indexOf(ciphertext.charAt(f++));
      a = _keyStr.indexOf(ciphertext.charAt(f++));
      n = (s << 2) | (o >> 4);
      r = ((o & 15) << 4) | (u >> 2);
      i = ((u & 3) << 6) | a;
      t = t + String.fromCharCode(n);
      if (u != 64) {
        t = t + String.fromCharCode(r);
      }
      if (a != 64) {
        t = t + String.fromCharCode(i);
      }
    }
    t = this.utf8Ddecode(t);
    return t;
  }
  utf8Ddecode(e: String) {
    var t = '';
    var n = 0;
    var r = 0;
    var c1 = 0;
    var c2 = 0;
    while (n < e.length) {
      r = e.charCodeAt(n);
      if (r < 128) {
        t += String.fromCharCode(r);
        n++;
      } else if (r > 191 && r < 224) {
        c1 = e.charCodeAt(n + 1);
        t += String.fromCharCode(((r & 31) << 6) | (c1 & 63));
        n += 2;
      } else {
        c1 = e.charCodeAt(n + 1);
        c2 = e.charCodeAt(n + 2);
        t += String.fromCharCode(((r & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
        n += 3;
      }
    }
    return t;
  }

  login(rid: any) {
    let ppstUrl = 'inControlServer/sys/login/loginInSso?_allow_anonymous=true';
    if (this.customLoginType === 'secretFree') {
      ppstUrl = 'inControlServer/sys/login/loginSecretFree?secretFreeUser=' + this.secretFreeUser;
      if (this.secretFreeUrlLimit === '1') {
        ppstUrl = 'inControlServer/sys/login/loginSecretFreeLimit?secretFreeUser=' + this.secretFreeUser;
      }
    } else if ((this.customLoginType = 'bySso')) {
      ppstUrl = `inControlServer/qualityInspection/sysLogin/loginSso?_allow_anonymous=true`;
    }

    this.http
      // .post('/login/account?_allow_anonymous=true', {
      // .post('server/system/userLogin?_allow_anonymous=true', {
      .post(ppstUrl, {
        // type: this.type,
        rid
      })
      .subscribe({
        next: (res: any) => {
          if (res.msg !== 'success') {
            this.error = res.msg;
            this.code = res.code;
            return;
          }
          // 清空路由复用信息
          this.reuseTabService.clear();
          // 设置用户Token信息
          // this.tokenService.set(res.user);
          this.tokenService.set(res.data);
          const tokenInfo: any = res.data.userInfo;
          this.srv.set('ic_userInfo', tokenInfo, { type: 'm' });
          const treeList = this.utils.getMenuFromUserInfo(res.data.userInfo);
          if (treeList[0]) {
            treeList[0].text = '主导航';
            treeList[0].group = true;
            treeList[0].open = true;
            if (treeList[0].children && treeList[0].children[0]) {
              treeList[0].children[0].open = true;
            }
            this.menuService.add(treeList);
          }
          // Application information: including site name, description, year
          tokenInfo.appInfos = {
            name: 'in-control',
            description: '融为inControl平台前端框架'
          };
          tokenInfo.userInfos = {
            name: tokenInfo.name,
            avatar: tokenInfo.portrait,
            email: tokenInfo.email,
            token: res.data.token
          };
          if (!tokenInfo.userInfos.avatar || tokenInfo.userInfos.avatar.length < 2) {
            tokenInfo.userInfos.avatar = 'http://i2.tiimg.com/674794/2b045fc622344d1c.png';
          }
          this.settingsService.setApp(tokenInfo.appInfos);
          // User information: including name, avatar, email address
          this.settingsService.setUser(tokenInfo.userInfos);
          // ACL: Set the permissions to full, https://ng-alain.com/acl/getting-started
          this.aclService.setFull(true);
          this.titleService.suffix = tokenInfo.appInfos.name;
          let url = this.tokenService.referrer!.url || '/';
          if (url.includes('/passport') || url === '/') {
            url = treeList[0].children[0].link;
          }
          // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
          this.startupSrv.load().subscribe(() => {
            if ((this.customLoginType = 'secretFree' && this.secretFreeUrl)) {
              let routerUrl = this.secretFreeUrl.replace(/%2F/g, '/');
              if (this.secretFreeUrlPar) {
                routerUrl = routerUrl + '?' + this.secretFreeUrlPar;
              }
              setTimeout(() => this.router.navigateByUrl(routerUrl));
            } else {
              let url = this.tokenService.referrer!.url || '/';
              if (this.customRouterUrl) {
                url = this.customRouterUrl;
                if (this.otherPars && this.otherPars !== '') {
                  url = url + '?' + this.otherPars;
                }
              } else {
                if (url.includes('/passport') || url === '/') {
                  url = treeList[0].children[0].link;
                }
              }
              url = url.replace(/%2F/g, '/');
              // this.router.navigateByUrl('/page/s/c8aa07a9e3fe4761bc007707bf5cfc77');
              // setTimeout(() => this.router.navigateByUrl(url));
            }
          });
        },
        error: (error: any) => {
          this.notification.error('获取内联表格配置失败', '');
          console.error(error);
        },
        complete: () => {}
      });
  }
}
