import { Component, Inject, Injector, OnDestroy, OnInit, Optional, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router, ActivatedRoute, Params } 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, SocialOpenType, SocialService } from '@delon/auth';
import { CacheService } from '@delon/cache';
import { SFComponent, SFSchema } from '@delon/form';
import { MenuService, SettingsService, TitleService, _HttpClient } from '@delon/theme';
import { environment } from '@env/environment';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';

import * as incontrolUtils from '../../../shared/utils/ic-utils';

@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService]
})
export class UserLoginComponent implements OnDestroy, OnInit {
  // 修改密码弹窗
  tplModalButtonLoading = false;
  isPwVisible = false;
  userId = '';
  @ViewChild('baseSf', { static: false }) baseSf!: SFComponent;
  schema: SFSchema = {
    properties: {
      oldPw: {
        type: 'string',
        title: '旧密码',
        ui: {
          showRequired: true,
          type: 'password'
        }
      },
      newPw: {
        type: 'string',
        title: '新密码',
        ui: {
          showRequired: true,
          type: 'password',
          validator: (value: string, formProperty: any, form: any) => {
            if (value) {
              if (form.value.oldPw === value) {
                return [{ keyword: 'required', message: '新密码不能和旧密码一样' }];
              } else {
                return [];
              }
            } else {
              return [{ keyword: 'required', message: '请填入新密码' }];
            }
          }
        }
      },
      confirmPw: {
        type: 'string',
        title: '确认密码',
        ui: {
          showRequired: true,
          type: 'password',
          validator: (value: string, formProperty: any, form: any) => {
            if (value) {
              if (form.value.newPw !== value) {
                return [{ keyword: 'required', message: '新密码和确认密码不一样' }];
              } else {
                return [];
              }
            } else {
              return [{ keyword: 'required', message: '请填入确认密码' }];
            }
          }
        }
      }
    }
  };
  formData: any = {};

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private route: ActivatedRoute,
    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 modal: NzModalService,
    private notification: NzNotificationService,
    private injector: Injector
  ) {
    this.form = fb.group({
      userName: [null, [Validators.required, Validators.minLength(1)]],
      password: [null, Validators.required],
      mobile: [{ value: null, disabled: true }],
      captcha: [null, [Validators.required]],
      remember: [true]
    });
    modalSrv.closeAll();
  }

  // #region fields

  get userName() {
    return this.form.controls.userName;
  }
  get password() {
    return this.form.controls.password;
  }
  get mobile() {
    return this.form.controls.mobile;
  }
  get captcha() {
    return this.form.controls.captcha;
  }

  loginType: NzSafeAny = [];
  form: FormGroup;
  error = '';
  type = 0;
  code = '';

  // #region get captcha

  count = 0;
  interval$: any;
  computerModel = false;
  computerIp = '';
  computerMac = '';
  computerSerial = '';
  mainBoardSerial = '';
  promptInfo = '';
  smscode = '';
  rescode = '';
  resmobile = '';
  btnContent = 0;
  phone = '';
  showRegisterButton = false;
  showForgetPasswordButton = false;
  registerButtonName = '注册账号';
  registerUrl = '/passport/login';

  ngOnInit(): void {
    const queryInfos = { enabled: 'Y' };
    this.route.queryParams.subscribe((params: Params) => {
      this.userName.setValue(params.account);
    });
    this.httpUtils.getLoginConfigList(queryInfos).subscribe(res => {
      if (res) {
        if (res.data.length > 0) {
          const loginConfig = res.data[0];
          if (loginConfig.logintype) {
            this.loginType = loginConfig.logintype.split(',');
          }
          if (loginConfig.logintitile) {
            this.titleService.setTitle(loginConfig.logintitile);
          }
          const configs = JSON.parse(loginConfig.roption);
          if (configs.showRegisterButton) {
            this.showRegisterButton = true;
            if (incontrolUtils.icIsNotNull(configs.registerButtonName)) {
              this.registerButtonName = configs.registerButtonName;
            }
            if (configs.registerButtonLink) {
              this.registerUrl = configs.registerButtonLink;
            }
          }
          if (configs.showForgetPasswordButton) {
            this.showForgetPasswordButton = true;
          }
          // 融公社通过参数显示全部过滤条件
          // if (this.route.snapshot.queryParams['backend'] && this.route.snapshot.queryParams['backend'] == 't') {
          //   this.loginType = ['1', '2'];
          // } else {
          //   this.loginType = ['2'];
          // }
        }
      }
    });
    const userCollection = this.srv.get('ic_userCollection', { type: 'm', mode: 'none' });
    if (!incontrolUtils.icIsNotNull(userCollection)) {
      this.httpUtils.getPostData('inControlServer/sys/usercollection/list?v=rw&source=init&_allow_anonymous=true', {}).subscribe({
        next: res => {
          if (res.data?.configList) {
            this.srv.set('ic_userCollection', res.data, { type: 'm' });
          }
        }
      });
    }
  }
  // #endregion

  switch(ret: any) {
    this.type = ret.index;
  }

  getCaptcha() {
    // if (this.mobile.invalid) {
    //   this.mobile.markAsDirty({ onlySelf: true });
    //   this.mobile.updateValueAndValidity({ onlySelf: true });
    //   return;
    // }
    if (this.userName.invalid) {
      this.userName.markAsDirty({ onlySelf: true });
      this.userName.updateValueAndValidity({ onlySelf: true });
      return;
    }
    if (this.password.invalid) {
      this.password.markAsDirty({ onlySelf: true });
      this.password.updateValueAndValidity({ onlySelf: true });
      return;
    }
    this.http
      .post('inControlServer/qualityInspection/zhcxApi/sendCode?_allow_anonymous=true', {
        account: this.userName.value,
        password: this.password.value,
        loginType: 'PC'
      })
      .subscribe((res: any) => {
        // if (res.msg !== 'success') {
        //   this.error = res.msg;
        //   this.code = res.code;
        //   this.rescode = '';
        //   this.resmobile = '';
        //   return;
        // }
        if (res.code == '200') {
          this.phone = res.data.phone;
        } else {
          this.phone = '';
          this.error = res.msg;
          return;
        }
        //this.rescode = res.data.smscode;
        //this.resmobile = res.data.phone;
      });

    this.btnContent = 59;
    this.interval$ = setInterval(() => {
      this.btnContent -= 1;
      if (this.btnContent <= 0) {
        clearInterval(this.interval$);
        this.btnContent = 0;
      }
    }, 1000);
  }

  // #endregion

  submit() {
    this.error = '';
    if (this.loginType.length == 1 && this.loginType.includes('2')) {
      this.type = 1;
    }
    if (this.type === 0) {
      this.userName.markAsDirty();
      this.userName.updateValueAndValidity();
      this.password.markAsDirty();
      this.password.updateValueAndValidity();
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.userName.invalid || this.password.invalid || this.mobile.invalid || this.captcha.invalid) {
        return;
      }
    } else {
      this.mobile.markAsDirty();
      this.mobile.updateValueAndValidity();
      this.captcha.markAsDirty();
      this.captcha.updateValueAndValidity();
      if (this.mobile.invalid || this.captcha.invalid) {
        return;
      }
      // 改为后端校验验证码信息
      //if (this.mobile.value === this.resmobile && this.captcha.value === this.rescode) {
      if (this.mobile.value === this.resmobile) {
        this.http
          // .post('/login/account?_allow_anonymous=true', {
          // .post('server/system/userLogin?_allow_anonymous=true', {
          .post('inControlServer/sys/login/loginInphone?_allow_anonymous=true', {
            // type: this.type,
            username: this.mobile.value,
            password: this.captcha.value
          })
          .subscribe((res: any) => {
            if (res.msg !== 'success') {
              this.error = res.msg;
              // this.code = res.code;
              this.tokenService.clear();
              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,
              mobile: res.data.userInfo.mobile ?? '',
              tenantname: !res.data.userInfo.tenantDo ? '' : res.data.userInfo.tenantDo.tenantname
            };
            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;
            }
            // this.router.navigateByUrl(url);
            // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
            this.startupSrv.load().subscribe(() => {
              let url = this.tokenService.referrer!.url || '/';
              if (url.includes('/passport') || url === '/') {
                url = treeList[0].children[0].link;
              }
              this.router.navigateByUrl(url);
            });
          });
      } else {
        this.error = '验证码错误';
        this.code = '1';
        return;
      }
      return;
    }

    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
    this.http
      // .post('/login/account?_allow_anonymous=true', {
      // .post('server/system/userLogin?_allow_anonymous=true', {
      .post('inControlServer/qualityInspection/sysLogin/loginIn?_allow_anonymous=true', {
        // type: this.type,
        phone: this.mobile.value,
        loginType: 'PC',
        account: this.userName.value,
        password: this.password.value,
        code: this.captcha.value
      })
      .subscribe((res: any) => {
        if (res.msg !== 'success') {
          this.error = res.msg;
          this.code = res.code;
          return;
        }
        // res.data.userInfo.hasPwOverdue = 'aaa';
        if (res.data.userInfo.hasPwOverdue && res.data.userInfo.hasPwOverdue === 'overdue') {
          this.userId = res.data.userInfo.id;
          this.isPwVisible = true;
        } else {
          // 清空路由复用信息
          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,
            mobile: res.data.userInfo.mobile ?? '',
            tenantname: !res.data.userInfo.tenantDo ? '' : res.data.userInfo.tenantDo.tenantname
          };
          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 || '/';
          let firstMenuUrl = incontrolUtils.getFirstMenu(treeList);
          if (url.includes('/passport') || url === '/') {
            if (firstMenuUrl) {
              url = firstMenuUrl;
            } else {
              this.notification.warning('没有权限', '未授权,请联系管理员分配系统功能权限!');
              (this.injector.get(DA_SERVICE_TOKEN) as ITokenService).clear();
              return;
            }
          }

          // this.router.navigateByUrl(url);
          // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
          this.startupSrv.load().subscribe(() => {
            let url = this.tokenService.referrer!.url || '/';
            if (url.includes('/passport') || url === '/') {
              url = treeList[0].children[0].link;
            }
            // this.router.navigateByUrl(url);
          });
        }
      });
  }

  destroyTplModal(e: any): void {
    console.log(this.baseSf.value);
    const userVo = {
      id: this.userId,
      oldpassword: this.baseSf.value.oldPw,
      newpassword: this.baseSf.value.newPw
    };
    this.tplModalButtonLoading = true;
    this.http.post(`inControlServer/sys/sysuser/resetUserPwLogin?_allow_anonymous=true`, userVo).subscribe(
      (res: any) => {
        console.log('res', res);
        if (res.code === '200' || res.code === '710') {
          this.isPwVisible = false;
        }
      },
      (error: any) => {
        console.log('error', error);
        this.tplModalButtonLoading = false;
      },
      () => {
        this.tplModalButtonLoading = false;
      }
    );
  }

  handleCancel() {
    this.isPwVisible = false;
  }

  goToRegister() {
    if (incontrolUtils.icIsExtraLink(this.registerUrl)) {
      window.open(this.registerUrl);
    } else {
      this.updateWhitelist(this.registerUrl);
      setTimeout(() => this.injector.get(Router).navigateByUrl(this.registerUrl));
    }
  }

  forgetPassword() {
    this.updateWhitelist('/passport/forget-password');
    this.router.navigate(['/passport/forget-password'], { queryParams: { account: this.userName.value } });
    // @ts-ignore
    // setTimeout(() => this.injector.get(Router).navigateByUrl('/passport/forget-password', { state: { account: this.userName.value } }));
  }

  private updateWhitelist(url: string): void {
    const icWhitelist = this.utils.loadCache('ic-whitelist');
    let tempSet = new Set(icWhitelist);
    tempSet.add(url);
    let newWhitelist = Array.from(tempSet);
    this.utils.saveCache('ic-whitelist', newWhitelist);
  }

  // #endregion

  ngOnDestroy(): void {
    if (this.interval$) {
      clearInterval(this.interval$);
    }
  }
  getComputerInfo(): void {
    this.promptInfo = '请将此信息发送至服务提供商生成证书';
    this.computerModel = true;
    this.http.get('inControlServer/sys/license/getServerInfos?_allow_anonymous=true').subscribe((res: any) => {
      this.computerIp = res.ipAddress;
      this.computerMac = res.macAddress;
      this.computerSerial = res.cpuSerial;
      this.mainBoardSerial = res.mainBoardSerial;
      console.log(res);
    });
  }
}
