import { AfterViewInit, ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { ErrorData, SFComponent, SFSchema, SFStringWidgetSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
// import { CaptchaComponent } from '@shared';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { interval, Observable, Observer } from 'rxjs';
import { take } from 'rxjs/operators';
import { AccountService } from '../../services/account.service';

@Component({
  selector: 'app-account-components-edit-name',
  templateUrl: './edit-name.component.html',
  styleUrls: ['./edit-name.component.less'],
})
export class AccountComponentsEditNameComponent implements OnInit, AfterViewInit {
  // @ViewChild('dun', { static: false })
  // private dun!: CaptchaComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  record: any = {};
  i: any;
  schema!: SFSchema;
  schemaView!: SFSchema;
  ui!: SFUISchema;
  uiView: SFUISchema = {};
  isVisibleView = false;
  isVisibleOk = false;
  formData: any = {};
  count = 0;
  count2 = 0;
  oldName: any;
  voucher: any;
  codeTips: any;
  interval$: any;

  constructor(private modal: NzModalRef, public msgSrv: NzMessageService, public http: _HttpClient, public service: AccountService,private cdr: ChangeDetectorRef,) {}
  ngAfterViewInit(): void {
    // this.dun.init();
  }

  ngOnInit() {
    this.codeTips = '为了账户安全，需您的手机验证（' + this.i?.phone + '）';
    this.formData.oldName = this.i?.phone;
    this.initSF();
    this.initSFNew();
    // this.getInfo();
  }
  initSF() {
    this.schema = {
      properties: {
        oldName: {
          title: '手机号',
          type: 'string',
          default: this.formData?.oldName,
          ui: {
            widget: 'text',
          },
        },
        // userName: {
        //   title: '用户名(新)',
        //   type: 'string',
        //   minLength: 3,
        //   maxLength: 30,
        //   description: '3-30个字符，支持中英文、数字、符号“_”和“-”，只能修改一次',
        //   ui: {
        //     placeholder: '请输入新用户名',
        //     errors: {
        //       required: '请输入新用户名',
        //     },
        //   } as SFStringWidgetSchema,
        // },
        smsVerifyCode: {
          title: '验证码',
          type: 'string',
          maxLength: 6,
          minLength: 6,
          description: this.codeTips,
          ui: {
            widget: 'custom',
            placeholder: '请输入验证码',
            errors: {
              required: '请输入6位数字验证码',
              minLength: '请输入6位数字验证码',
            },
          },
        },
      },
      required: ['userName', 'smsVerifyCode'],
    };
    this.ui = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 24 },
      },
    };
  }
  initSFNew() {
    this.schemaView = {
      properties: {
        phone: {
          title: '新手机号',
          type: 'string',
          format: 'mobile',
          maxLength: 11,
          ui: {
            placeholder: '请输入新手机号',
            errors: {
              required: '请输入新手机号',
            },
          } as SFStringWidgetSchema,
        },
        smsVerifyCode: {
          title: '验证码',
          type: 'string',
          maxLength: 6,
          minLength: 6,
          ui: {
            widget: 'custom',
            placeholder: '请输入验证码',
            errors: {
              required: '请输入6位验证码',
              minLength: '请输入6位验证码',
            },
          },
        },
      },
      required: ['phone', 'smsVerifyCode'],
    };
    this.uiView = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 24 },
      },
    };
  }

  getCaptcha() {
    const params = {
      // phoneNumber: phone
    };
    this.service.request(this.service.$api_get_current_user_smVerification, params, 'POST', true, 'FORM').subscribe((res) => {
      // code==503046 弹出网易盾
      if (res && res.code === '1') {
        this.service.msgSrv.success('发送成功');
        this.createInterval();
      } else if (res.code === '503046') {
        // this.dun.popUp();
      } else {
        this.service.msgSrv.success(res.msg);
      }
    });
  }

  getCaptcha2() {
    const params = {
      phoneNumber: this.sfView.value.phone
    };
    this.service.request(this.service.$api_get_getSMVerificationCode, params, 'POST', true, 'FORM').subscribe((res) => {
      // code==503046 弹出网易盾
      if (res && res.code === '1') {
        this.service.msgSrv.success('发送成功');
        this.createInterval2();
      } else if (res.code === '503046') {
        // this.dun.popUp();
      } else {
        this.service.msgSrv.success(res.msg);
      }
    });
  }

  // /* code倒计时 */
  // codeCountDown() {
  //   this.count = 59;
  //   this.interval$ = setInterval(() => {
  //     this.count -= 1;
  //     if (this.count <= 0) {
  //       clearInterval(this.interval$);
  //     }
  //   }, 1000);
  // }
  private createInterval() {
    this.count = 59;
    interval(1000)
      .pipe(take(60))
      .subscribe((x: any) => {
        this.count = 59 - (x + 1);
        this.cdr.detectChanges();
      });
  }
  private createInterval2() {
    this.count2 = 59;
    interval(1000)
      .pipe(take(60))
      .subscribe((x: any) => {
        this.count2 = 59 - (x + 1);
        this.cdr.detectChanges();
      });
  }
  // codeCountDown2() {
  //   this.count2 = 59;
  //   this.interval$ = setInterval(() => {
  //     this.count2 -= 1;
  //     if (this.count <= 0) {
  //       clearInterval(this.interval$);
  //     }
  //   }, 1000);
  // }
  /* 网易盾验证通过 */
  captchaDone(validate: any) {
    this.createInterval();
  }

  getInfo() {
    const params = {
      // id: this.i.id,
    };
    this.service.http.post(this.service.$api_get_current_user_info, params).subscribe((res) => {
      // if (res) {
      //   this.getCaptcha(res.data.phone);
      // }
    });
  }

  close() {
    this.modal.destroy();
  }
  submitForm() {
    const params = {
      smsVerifyCode: this.sf.value.smsVerifyCode,
    };

    this.service.http.post(this.service.$api_get_verifyPhone, params).subscribe((res) => {
      if (res.success) {
        // this.modal.close(true);
        this.voucher = res.data.voucher
         this.isVisibleView = true
      } else {
        this.service.msgSrv.error(res.msg)
      }
    });
  }
  handleCancel(type: string) {
     if(type === '1') {
      this.isVisibleView = false
    } else if(type === '2') {
    console.log(type)
    } else if(type === '3') {
    this.modal.close()
    }
  }
  handleOK() {
    
  }
  handleNew() {
    if(!this.sfView.valid) {
      return;
    }
    const params = {
      voucher: this.voucher,
      ...this.sfView.value,
    }
    this.service.http.post(this.service.$api_set_voucherUpdatePhone, params).subscribe((res) => {
      if (res.success) {
        this.isVisibleOk = true;
      } else {
        this.service.msgSrv.error(res.msg)
      }
    });
  }
}
