import { BindParams, WebParams } from '@ohos/common/src/main/ets/viewmodel/ParamBean';
import { AGREEMENT_URL, IS_AGREE_AGREEMENT, PRIVACY_URL,
  WX_BIND_AUTHOR } from '@ohos/common/src/main/ets/constants/AppConstants';
import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore';
import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils';
import { promptAction } from '@kit.ArkUI';
import { TitleBarComponent } from '../view/TitleBarComponent';
import { MainService } from '../viewmodel/MainService';
import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService';
import { common } from '@kit.AbilityKit';
import { emitter } from '@kit.BasicServicesKit';
import { EVT_BIND_WX_AUTHOR_SUCCESS } from '@ohos/common/src/main/ets/constants/EventConstants';

@Builder
export function AccountBindLoginBuilder() {
  AccountBindLoginLayout()
}

/**
 * 绑定账号页面（类似登录）
 * 与登录页相比：只显示单一的绑定方式
 */
@Component
struct AccountBindLoginLayout {
  @Consume('pageInfos') pageStack: NavPathStack;
  @State fromSource: string = '';
  @State hasAgreed?: boolean = undefined;
  @State bindParams: BindParams | null = null;

  /*
  // 在 Page 页面中
  dialogController: CustomDialogController = new CustomDialogController({
    builder: AgreementDialog({
      confirm: () => {
        // 执行你的逻辑
        KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true');
      }
    }),
    // 1. 禁止点击空白处关闭
    autoCancel: false,

    // 2. 拦截返回手势 (API 11+) 如果用户触发返回手势，此回调会被触发。 不调用 dismiss() 则弹窗不会消失。
    onWillDismiss: (dismissDialogAction: DismissDialogAction) => {
      console.info("Reason: " + JSON.stringify(dismissDialogAction.reason));
      // 如果是因为点击遮罩(0)或按下返回键(1)触发，我们不做处理，从而实现禁止关闭
      if (dismissDialogAction.reason === DismissReason.PRESS_BACK ||
        dismissDialogAction.reason === DismissReason.TOUCH_OUTSIDE) {
      }
    },
    alignment: DialogAlignment.Center,
    customStyle: true
  })
  */

  async aboutToAppear() {
    emitter.once({ eventId: EVT_BIND_WX_AUTHOR_SUCCESS }, (eventData: emitter.EventData) => {
      const payload = eventData.data;
      if (payload && payload["result"]) {
        const authCode: string = payload["result"] as string;

        // 获取授权码，请求登录
        MainService.wxBind(authCode, {
          onSuccess: (_) => {
            BindSuccess(this.pageStack)
          },
          onFailure: (message) => {
            ToastUtils.showToast(this.getUIContext(), message);
          },
          onError: (_) => {
            ToastUtils.showToast(this.getUIContext(), '绑定失败');
          }
        })
      }
    });
  }

  build() {
    NavDestination() {
      Stack() {
        // 1. 背景层
        Stack(){
          Image($r('app.media.ic_login_mask')).width('100%')
        }
        .width('100%')
        .height('100%')
        .alignContent(Alignment.TopStart)

        // 2. 主体内容层 (标题 + 绑定框)
        Column() {
          TitleBarComponent({
            titleName: '',
            isShowTitle: false,
            isShowBack: true
          })
          //显示绑定内容
          if(this.bindParams?.type === 2){
            // 微信绑定
            BindForWechat({isChecked: this.hasAgreed})
          }else{
            //一键绑定OR手机绑定
            BindForPhone({isChecked: this.hasAgreed})
          }
        }
        .width('100%')
        .height('100%')

        /*
        // 3. 底部“其他方式”层
        Column() {
          Row() {
            Image($r('app.media.ic_login_other_left_line'))
              .margin({ right: 12 })
              .width(60)
              .height(2)

            Text('其他方式')
              .fontSize(16)
              .fontColor('#FF767676')
              .fontWeight(FontWeight.Bold)

            Image($r('app.media.ic_login_other_right_line'))
              .margin({ left: 12 })
              .width(60)
              .height(2)
          }
          .alignItems(VerticalAlign.Center) // 确保横线和文字垂直居中对齐

          Row(){
            Image($r('app.media.ic_login_wx_icon'))
              .width(40)
              .height(40)
              .onClick(() => {
                this.loginMethod = 2;
              })

            Image($r('app.media.ic_login_phone_icon'))
              .width(40)
              .height(40)
              .margin({ left: 18 })
              .onClick(() => {
                this.loginMethod = 0;
              })
          }
          .margin({ top: 27, bottom: 60 })
        }
        .width('100%')
        .margin({ bottom: 40 }) // 距离屏幕底部留一点间距，避免贴边
        */
      }
      .alignContent(Alignment.Bottom) // 将 Stack 默认对齐方式设为底部，或者手动控制层级
      .width('100%')
      .height('100%')
      .backgroundColor($r('sys.color.white'))
    }
    .onReady((context: NavDestinationContext) => {
      this.bindParams = context.pathInfo.param as BindParams;
    })
    .hideTitleBar(true)
  }
}

@Component
struct BindForPhone {
  @Consume('pageInfos') pageStack: NavPathStack;
  @State textPhoneValue: string = '';
  @State textCaptchaValue: string = '';
  @State captchaTimestampValue: string = '';

  @State countdown: number = 0; // 倒计时秒数
  @State isCounting: boolean = false; // 是否正在倒计时
  private timerId: number = -1; // 定时器ID

  @Prop isChecked: boolean = false;
  onChange: (checked: boolean) => void = (checked: boolean) => {
    if(checked){ 'true' }else{ 'false' }
    KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true');
  };

  cancel: () => void = () => {};
  confirm: () => void = () => {
    if(!this.textPhoneValue){
      ToastUtils.showToast(this.getUIContext(), '请输入手机号码')
    }else if(!this.isChecked){
      ToastUtils.showToast(this.getUIContext(), '请先同意隐私和协议...')
    }else if(!this.textCaptchaValue){
      ToastUtils.showToast(this.getUIContext(), '请输入验证码')
    }else{
      MainService.bindForCaptcha(this.textPhoneValue, this.textCaptchaValue, this.captchaTimestampValue, {
        onSuccess: (_) => {
          BindSuccess(this.pageStack)
        },
        onFailure: (message) => {
          ToastUtils.showToast(this.getUIContext(), message);
        },
        onError: (_) => {
          ToastUtils.showToast(this.getUIContext(), '绑定失败');
        }
      })
    }
  };


  build() {
    Column() {
      // Logo图标区域
      Row() {
        Image($r('app.media.ic_login_vertical_line'))
          .width('4vp')
          .height('55vp')

        Column(){
          Text('欢迎使用')
            .width('100%')
            .fontSize(18)
            .fontColor('#FF000000')
            .textAlign(TextAlign.Start)
            .fontWeight(FontWeight.Bold)

          Text('截图兔')
            .width('100%')
            .fontSize(32)
            .fontColor('#FF000000')
            .textAlign(TextAlign.Start)
            .fontWeight(FontWeight.Bold)
        }
        .width('100%')
        .margin({left: 12})

      }
      .width('100%')
      .justifyContent(FlexAlign.Start)
      .margin({top: 63})

      //账号输入框
      Stack({ alignContent: Alignment.BottomEnd }) {
        Row(){
          Text('+86')
            .fontSize(14)
            .fontColor('#FF3D3D3D')
            .textAlign(TextAlign.Start)

          Image($r('app.media.ic_login_input_div_line'))
            .width(1)
            .height(28)
            .margin({ left: 12 })

          TextInput({ placeholder: '请输入手机号', text: this.textPhoneValue })
            .width('100%')
            .type(InputType.PhoneNumber)
            .maxLength(11)
            .fontSize(16)
            .fontColor('#FF1A1A1A')
            .textAlign(TextAlign.Start)
            .placeholderColor('#FF767676')
            .backgroundColor('#00000000')
            .borderRadius(8)
            .borderColor('#00000000')
            .borderWidth(0.5)
            .onChange((v) => this.textPhoneValue = v)
        }
      }
      .width('100%')
      .backgroundColor('#FFF6F6F6')
      .borderRadius(8)
      .borderColor('#FFDEDEDE')
      .borderWidth(0.5)
      .margin({top: 100})
      .padding({ left: 16, right: 16})

      //验证码输入框
      Stack({ alignContent: Alignment.BottomEnd }) {
        Row(){
          TextInput({ placeholder: '请输入验证码', text: this.textCaptchaValue })
            .layoutWeight(1)
            .type(InputType.Number)
            .maxLength(20)
            .fontSize(16)
            .fontColor('#FF1A1A1A')
            .textAlign(TextAlign.Start)
            .placeholderColor('#FF767676')
            .backgroundColor('#00000000')
            .borderRadius(8)
            .borderColor('#00000000')
            .borderWidth(0.5)
            .onChange((v) => this.textCaptchaValue = v)
          Stack() {
            Text(this.isCounting ? `${this.countdown}s后重新获取` : '获取验证码')
              .fontSize(12)
              .fontColor(this.isCounting ? '#FF999999' : '#FF3D3D3D') // 倒计时变灰
              .textAlign(TextAlign.Start)
          }
          .backgroundColor('#FFFFFFFF')
          .borderRadius(8)
          .borderColor('#00000000')
          .borderWidth(0.5)
          .padding({ left: 19, right: 19, top: 12, bottom: 12})
          .onClick(() => {
            if (this.isCounting) return; // 倒计时中点击无效

            if (!this.textPhoneValue || this.textPhoneValue.length < 11) {
              ToastUtils.showToast(this.getUIContext(), '请输入正确的手机号码');
              return;
            }

            CommonService.sendSmsCode(this.textPhoneValue,{
              onSuccess: (captchaTimestamp) => {
                this.captchaTimestampValue = captchaTimestamp.toString()
                // 发送成功后调用倒计时
                this.startCountdown();

                ToastUtils.normalToast({
                  message: '验证码已发送',    // 提示文字
                  duration: 2000,           // 显示时长 (ms)，默认 1500
                  bottom: '50%'
                });
              },
              onFailure: (message) => {
                ToastUtils.showToast(this.getUIContext(), message);
              },
              onError: (_) => {
                ToastUtils.showToast(this.getUIContext(), '发送失败');
              }
            })

          })

        }
      }
      .width('100%')
      .backgroundColor('#FFF6F6F6')
      .borderRadius(12)
      .borderColor('#FFDEDEDE')
      .borderWidth(0.5)
      .margin({top: 20})
      .padding({ left: 14, right: 5})

      //绑定按钮
      Button('绑定')
        .onClick(() => {
          this.confirm();
        })
        .backgroundColor(Color.Black) // 对应图片中的黑色按钮
        .fontColor('#FFC2FF43')
        .borderRadius(359)
        .fontSize(16)
        .height(46)
        .width('100%')
        .margin({top: 46, bottom:14})

      //用户协议
      Row(){
        Image(this.isChecked ?
          $r('app.media.ic_tick_circle_selected') : // 选中的图片资源
          $r('app.media.ic_tick_circle_normal') // 未选中的图片资源
        )
          .width(16)
          .height(16)
          .margin({ right: 4 })
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            this.isChecked = !this.isChecked;
            this.onChange(this.isChecked);
          })
          // 添加点击时的缩放动画，增加反馈感
          .animation({ duration: 200, curve: Curve.EaseInOut })

        Text() {
          Span('我已阅读并同意')
            .fontColor('#80aaaaaa')

          Span('《用户协议》')
            .fontColor('#FFAAAAAA') // 高亮颜色（深灰）
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              const params: WebParams = {
                id: 1001,
                name: "用户协议",
                type: 1,
                url: AGREEMENT_URL
              };
              this.pageStack.pushPathByName("WebLayout", params)
            })

          Span('和')
            .fontColor('#80aaaaaa')

          Span('《隐私政策》')
            .fontColor('#FFAAAAAA') // 高亮颜色（深灰）
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              const params: WebParams = {
                id: 1001,
                name: "用户协议",
                type: 1,
                url: PRIVACY_URL
              };
              this.pageStack.pushPathByName("WebLayout", params);
            })
        }
        .fontSize(12)
        .textAlign(TextAlign.Start)
        .margin({ right: 4 })

      }
    }
    .width('100%')
    .height('100%')
    .padding({ left: 38, right: 38})
  }

  // 开启倒计时
  startCountdown() {
    if (this.isCounting) return;

    this.countdown = 60;
    this.isCounting = true;

    // 清理可能存在的旧定时器
    clearInterval(this.timerId);

    // 使用箭头函数确保 this 指向 LoginForPhone 组件
    this.timerId = setInterval(() => {
      if (this.countdown > 1) {
        this.countdown--;
      } else {
        this.stopCountdown();
      }
    }, 1000);
  }


  // 停止倒计时
  stopCountdown() {
    this.isCounting = false;
    this.countdown = 0;
    clearInterval(this.timerId);
  }

  // 组件销毁前清理，防止内存泄漏
  aboutToDisappear() {
    this.stopCountdown();
  }
}

@Component
struct BindForWechat {
  @Consume('pageInfos') pageStack: NavPathStack;

  @Prop isChecked: boolean = false;
  onChange: (checked: boolean) => void = (checked: boolean) => {
    if(checked){ 'true' }else{ 'false' }
    KVStore.getInstance().put(IS_AGREE_AGREEMENT, 'true');
  };
  build() {
    Column(){
      Image($r('app.media.ic_app_logo'))
        .width('100vp')
        .height('100vp')
        .margin({ top: 120 })
        .align(Alignment.Center)

      Text('截图兔')
        .fontSize(16)
        .fontColor('#FF000000')
        .textAlign(TextAlign.Center)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 8 })

      Column() {
        Text('为了更好地为您提供服务，请先完成微信授权')
          .fontSize(14)
          .fontColor('#805d5c5c')
          .textAlign(TextAlign.Center)
          .margin({ top: 30 })

        Row() {
          Image($r('app.media.ic_login_wx_auth_icon'))
            .width(16)
            .height(16)
            .margin({ right: 4 })

          Text('微信授权绑定')
            .fontSize(16)
            .fontColor('#FFC2FF43')
            .textAlign(TextAlign.Center)
        }
        .width('100%')
        .height(48)
        .backgroundColor('#FF252525')
        .borderRadius(359)
        .margin({ top: 8 })
        .padding({ top: 6, bottom: 6 })
        .align(Alignment.Center)
        .justifyContent(FlexAlign.Center)
        .onClick(() => {
          if (this.isChecked) {
            AppStorage.setOrCreate<number>(WX_BIND_AUTHOR, 2);
            CommonService.wxAuthorize(getContext(this) as common.UIAbilityContext, true);
          }else{
            ToastUtils.showToast(this.getUIContext(), '请先同意隐私和协议...')
          }
        })
      }
      .margin({ bottom:14 })

      //用户协议
      Row(){
        Image(this.isChecked ?
          $r('app.media.ic_tick_circle_selected') : // 选中的图片资源
          $r('app.media.ic_tick_circle_normal') // 未选中的图片资源
        )
          .width(16)
          .height(16)
          .margin({ right: 4 })
          .objectFit(ImageFit.Contain)
          .onClick(() => {
            this.isChecked = !this.isChecked;
            this.onChange(this.isChecked);
          })
          // 可选：添加点击时的缩放动画，增加反馈感
          .animation({ duration: 200, curve: Curve.EaseInOut })

        Text() {
          Span('我已阅读并同意')
            .fontColor('#80aaaaaa')

          Span('《用户协议》')
            .fontColor('#FFAAAAAA') // 高亮颜色（深灰）
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              const params: WebParams = {
                id: 1001,
                name: "用户协议",
                type: 1,
                url: AGREEMENT_URL
              };
              this.pageStack.pushPathByName("WebLayout", params)
            })

          Span('和')
            .fontColor('#80aaaaaa')

          Span('《隐私政策》')
            .fontColor('#FFAAAAAA') // 高亮颜色（深灰）
            .fontWeight(FontWeight.Bold)
            .onClick(() => {
              const params: WebParams = {
                id: 1001,
                name: "用户协议",
                type: 1,
                url: PRIVACY_URL
              };
              this.pageStack.pushPathByName("WebLayout", params);
            })
        }
        .fontSize(12)
        .textAlign(TextAlign.Start)
        .margin({ right: 4 })

      }
    }
    .width('100%')
    .height('100%')
    .padding({ left: 16, right: 16})
  }
}

function BindSuccess(pageStack: NavPathStack) {
  ToastUtils.normalToast({
    message: '绑定成功',        // 提示文字
    duration: 2000,            // 显示时长 (ms)，默认 1500
    bottom: '50%'
  });

  //重新获取用户配置(数据会持久化到本地)
  CommonService.getUserProfile().then(_ => {
    // 当用户配置获取完成后，重新获取用户信息(数据会持久化到本地)
    CommonService.getUserInfo()
  })

  AppStorage.setOrCreate('back', { isBack: true, source: 'bindLogin' });
  pageStack.pop();
}