import { StrUtil } from '@pura/harmony-utils';
import { plainToInstance } from 'class-transformer';
import { SendCodeEntity } from '../entity/SendCodeEntity';
import { apiService } from '../net/ApiService';
import { HttpResult } from '../net/HttpResult';
import { ToastUtils } from '../utils/ToastUtils';
import { LoadingDialog } from './LoadingDialog';

@CustomDialog
export struct BindPhoneDialog {
  controller: CustomDialogController;

  success: () => void = () => {}

  private phone: string = '';
  private code: string = '';
  private timestamp: string = '';
  private intervalId: number = -1;

  @State countDownTime: number = 0;

  sendCode(phone: string) {
    if (StrUtil.isEmpty(this.phone)) {
      ToastUtils.show('请输入手机号');
      return;
    }
    if (this.phone.length != 11) {
      ToastUtils.show('请输入正确的手机号');
      return;
    }
    LoadingDialog.show(this.getUIContext());
    try {
      apiService.sendCode(phone)
        .then((result: HttpResult) => {
          if (result.isSuccess()) {
            ToastUtils.show('验证码已发送');
            const codeEntity = plainToInstance(SendCodeEntity, result.data);
            this.timestamp = codeEntity.timestamp;
            this.countDownTime = 60;
            this.intervalId = setInterval(() => {
              if (this.countDownTime > 0) {
                this.countDownTime--
              } else {
                if (this.intervalId !== 0) {
                  clearInterval(this.intervalId);
                }
              }
            }, 1000)
          } else {
            ToastUtils.show(result.message, true);
          }
        })
        .finally(() => {
          LoadingDialog.dismiss();
        })
    } catch (e) {
      LoadingDialog.dismiss();
      console.log(e);
      ToastUtils.show(e);
    }
  }

  bindPhone() {
    if (StrUtil.isEmpty(this.phone)) {
      ToastUtils.show('请输入手机号');
      return;
    }
    if (this.phone.length != 11) {
      ToastUtils.show('请输入正确的手机号');
      return;
    }
    if (StrUtil.isEmpty(this.code)) {
      ToastUtils.show('请输入验证码');
      return;
    }
    LoadingDialog.show(this.getUIContext());
    try {
      apiService.loginByPhone(this.phone, this.code, this.timestamp, true)
        .then((result: HttpResult) => {
          if (result.isSuccess()) {
            ToastUtils.show('绑定成功');
            this.controller.close();
            this.success();
          } else {
            ToastUtils.show(result.message, true)
          }
        })
        .finally(() => {
          LoadingDialog.dismiss();
        })
    } catch (e) {
      LoadingDialog.dismiss();
    }
  }

  build() {
    RelativeContainer() {
      Text('绑定手机号')
        .width('auto')
        .fontColor($r('app.color.color_1a1a1a'))
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .alignRules({
          top: { anchor: '__container__', align: VerticalAlign.Top },
          left: { anchor: '__container__', align: HorizontalAlign.Start },
          right: { anchor: '__container__', align: HorizontalAlign.End },
        })
        .margin({ top: 18 })
        .id('tv_title')

      Image($r('app.media.ic_close'))
        .width(20)
        .height(20)
        .alignRules({
          top: { anchor: '__container__', align: VerticalAlign.Top },
          right: { anchor: '__container__', align: HorizontalAlign.End }
        })
        .margin({ top: 12, right: 12 })
        .onClick(() => {
          this.controller.close();
        })

      TextInput({ placeholder: '请输入手机号' })
        .height(48)
        .type(InputType.PhoneNumber)
        .fontColor($r('app.color.color_1a1a1a'))
        .fontSize(15)
        .placeholderColor($r('app.color.color_bcbcbc'))
        .placeholderFont({ size: 15 })
        .maxLength(11)
        .backgroundColor(Color.Transparent)
        .borderRadius(8)
        .borderWidth(1)
        .borderColor($r('app.color.color_dfdfdf'))
        .margin({ top: 20, left: 16, right: 16 })
        .alignRules({
          top: { anchor: 'tv_title', align: VerticalAlign.Bottom }
        })
        .id('et_phone')
        .onChange((value: string) => {
          this.phone = value;
        })

      Row() {
        TextInput({ placeholder: '请输入验证码' })
          .height(48)
          .type(InputType.Number)
          .fontColor($r('app.color.color_1a1a1a'))
          .fontSize(15)
          .placeholderColor($r('app.color.color_bcbcbc'))
          .placeholderFont({ size: 15 })
          .maxLength(6)
          .backgroundColor(Color.Transparent)
          .borderRadius(8)
          .borderWidth(1)
          .borderColor($r('app.color.color_dfdfdf'))
          .margin({ left: 16, right: 12 })
          .id('et_code')
          .onChange((value: string) => {
            this.code = value;
          })
          .layoutWeight(1)

        Text(this.countDownTime === 0 && StrUtil.isEmpty(this.timestamp) ? '获取验证码' : this.countDownTime > 0 ? `${this.countDownTime}s` : '重新发送')
          .width(110)
          .height(48)
          .textAlign(TextAlign.Center)
          .fontColor($r("app.color.color_466afd"))
          .fontSize(15)
          .borderRadius(8)
          .borderWidth(1)
          .borderColor($r('app.color.color_dfdfdf'))
          .margin({ right: 16 })
          .onClick(() => {
            this.sendCode(this.phone);
          })
      }
      .alignRules({
        top: { anchor: 'et_phone', align: VerticalAlign.Bottom }
      })
      .margin({ top: 14 })
      .id('layout_code')

      Stack() {
        Button('确定', { type: ButtonType.Capsule, stateEffect: true })
          .width('100%')
          .height(46)
          .fontColor(Color.White)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .backgroundColor($r('app.color.color_466afd'))
          .onClick(() => {
            this.bindPhone();
          })
      }
      .padding({ left: 16, right: 16 })
      .margin({ top: 55 })
      .alignRules({
        top: { anchor: 'layout_code', align: VerticalAlign.Bottom }
      })
    }
    .width('100%')
    .height(320)
    .borderRadius(20)
    .backgroundColor(Color.White)
  }
}