import { AfterViewInit, 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 { Observable, Observer } from 'rxjs';
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 })
  url = `/rule?_allow_anonymous=true`;
  // private dun!: CaptchaComponent;
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  record: any = {};
  i: any;
  schema!: SFSchema;
  ui!: SFUISchema;

  formData: any = {};
  count = 0;
  oldName: any;
  codeTips: any;
  interval$: any;

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

  ngOnInit() {
    this.codeTips = '为了账户安全，需您的手机验证（' + this.i.phone + '）';
    this.formData.oldName = this.i.name;
    this.initSF();
    // 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: '请输入新用户名',
            },
            // validator: (val) => this.validatecomponent(val),
            // blur: () => this.checkUserName(),
            // validator: (val) => {
            //   const name = this.sf?.getValue('/oldName');
            //   if (name === val) {
            //     return [{ keyword: 'validateName', message: '新用户名不能与旧用户名一样' }];
            //   }
            //   // console.log(this.isCheck,'this.isCheck');
            //   // if (!this.isCheck) {
            //   //   return [{ keyword: 'validateName', message: '用户名已存在，请修改' }];
            //   // }
            // },
          } 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 },
      },
    };
  }

  getCaptcha() {
    const params = {
      // phoneNumber: phone
    };
    this.service.request(this.service.$api_get_current_user_info, params, 'POST', true, 'FORM').subscribe((res) => {
      console.log(res);
      // code==503046 弹出网易盾
      if (res && res.code === '1') {
        this.service.msgSrv.success('发送成功');
        this.codeCountDown();
      } 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);
  }
  /* 网易盾验证通过 */
  captchaDone(validate: any) {
    this.codeCountDown();
  }

  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);
      // }
    });
  }
  /**
   * 验证组件名称
   * 规则：以小写字母开头，长度1-20， 仅限小写字母、数字和横线
   */
  // validatecomponent(value: string): Observable<ErrorData[]> {
  //   return new Observable((observer: Observer<ErrorData[] | null>) => {
  //     if (!value || value.trim().length === 0) {
  //       observer.next([{ keyword: 'required', message: '用户名不能为空！' }]);
  //       return;
  //     }

  //     let isCheck: any;
  //     this.service.request(this.service.$api_checkUserName, { userName: value }, 'POST', true, 'FORM').subscribe((res) => {
  //       // 检查用户名
  //       isCheck = res;
  //     });

  //     setTimeout(() => {
  //       // 以小写字母开头，长度1-20， 仅限小写字母、数字和横线
  //       // const partern = /^[a-z][a-zA-Z0-9-]{0,30}$/;

  //       // 3-30个字符，支持中英文、数字、符号“_”和“-”
  //       const partern = /^[a-zA-Z0-9_\-\u4e00-\u9fa5]{3,30}$/;
  //       const reg = new RegExp(partern);
  //       const result = reg.test(value);
  //       const name = this.sf?.getValue('/oldName');
  //       if (name === value) {
  //         observer.next([{ keyword: 'validateName', message: '新用户名不能与旧用户名一样' }]);
  //         return;
  //       }
  //       console.log(value, 'value', isCheck);
  //       if (!isCheck) {
  //         observer.next([{ keyword: 'validateName', message: '用户名已存在，请修改' }]);
  //         return;
  //       }
  //       if (!result) {
  //         observer.next([{ keyword: 'validateName', message: '请输入3-30个字符,且不能含有特殊符号!' }]);
  //       } else {
  //         observer.next([]);
  //       }
  //       observer.complete();
  //     }, 500);
  //   });
  // }
  // this.usernameValidator = (control: FormControl) => {
  //   if (control.value === this.i.name) {
  //     return of(null);
  //   }
  //   return control.valueChanges.pipe(

  //   );
  // };
  close() {
    this.modal.destroy();
  }
  submitForm() {
    console.log(this.sf.value, 'this.sf.value');
    const params = {
      ...this.sf.value,
    };
    this.service.http.post(this.service.$api_get_current_user_info, params).subscribe((res) => {
      console.log(res, 'submitForm');
      if (res.success) {
        this.service.msgSrv.success(res.msg);
        this.modal.close(true);
      } else {
        this.service.msgSrv.warning(res.msg);
      }
    });
  }
}
