import { AppUtil, RandomUtil, StrUtil } from '@pura/harmony-utils';
import { TipDialog } from '../../../../../dialog/TipDialog';
import { UserEntity } from '../../../../../entity/UserEntity';
import { ConfigManager } from '../../../../../manager/UserConfigManager';
import { ToastUtils } from '../../../../../utils/ToastUtils';
import { TitleBar } from '../../../../../view/TitleBar';
import BindAccountViewModel from '../../../../../viewModel/BindAccountViewModel';
import * as WxOpenSdk from '@tencent/wechat_open_sdk';
import { ErrCode, SendAuthResp } from '@tencent/wechat_open_sdk';
import { OnWXResp, WXApi, WXEventHandler } from '../../../../../utils/wechat/WXApiEventHandlerImpl';
import BuildProfile from 'BuildProfile';
import { BindPhoneDialog } from '../../../../../dialog/BindPhoneDialog';
import { LevelMode } from '@kit.ArkUI';
import { EventConstants } from '../../../../../common/EventConstants';
import { LoadingDialog } from '../../../../../dialog/LoadingDialog';
import { EventReportGlobalManager } from '../../../../../manager/EventReportGlobalManager';

@Entry
@ComponentV2
struct BindAccountPage {
  bindPhoneDialogController?: CustomDialogController | null;

  viewModel: BindAccountViewModel = new BindAccountViewModel(this.getUIContext());

  @Local userEntity?: UserEntity;

  //从微信返回的回调
  onWXResp: OnWXResp = (resp) => {
    //微信返回的数据
    if (resp instanceof SendAuthResp && resp.state?.endsWith('bind')) {
      const authResult = JSON.stringify(resp ?? {}, null , 2);
      const errCode = JSON.parse(authResult).errCode as number;
      if (errCode === ErrCode.ERR_OK) {
        const authCode = JSON.parse(authResult).code as string;
        this.viewModel.bindWx(authCode);
      } else {
        ToastUtils.show(JSON.parse(authResult).errStr);
      }
    }
  }

  @Monitor('viewModel.userEntity')
  onUserinfoChange(monitor: IMonitor) {
    this.userEntity = monitor.value()?.now as UserEntity;
  }

  @Monitor('viewModel.bindInfo')
  onBindInfoChange(monitor: IMonitor) {
    ToastUtils.show('绑定成功');
    this.refreshData();
    EventReportGlobalManager.eventReport(EventConstants.ACCOUNT_BIND)
  }

  @Monitor('viewModel.unbindInfo')
  onUnbindInfoChange(monitor: IMonitor) {
    ToastUtils.show('解绑成功');
    this.refreshData();
  }

  async aboutToAppear() {
    WXEventHandler.registerOnWXRespCallback(this.onWXResp)
    this.viewModel.userinfo();
  }

  aboutToDisappear() {
    WXEventHandler.unregisterOnWXRespCallback(this.onWXResp)
    this.bindPhoneDialogController = null
  }

  showBindPhoneDialog() {
    this.bindPhoneDialogController = new CustomDialogController({
      builder: BindPhoneDialog({
        success: () => {
          this.refreshData();
        }
      }),
      width: '100%',
      cornerRadius: 20,
      autoCancel: false,
      maskColor: '#CC000000',
      levelMode: LevelMode.EMBEDDED,
      backgroundBlurStyle: BlurStyle.NONE,
      alignment: DialogAlignment.Bottom
    })
    this.bindPhoneDialogController.open();
  }

  async wxAuth() {
    if (!WXApi.isWXAppInstalled()) {
      ToastUtils.show('请先下载安装微信客户端');
      return;
    }
    LoadingDialog.show(this.getUIContext());
    let req = new WxOpenSdk.SendAuthReq;
    req.isOption1 = false;
    req.nonAutomatic = true;
    req.scope = 'snsapi_userinfo';
    req.state = BuildProfile.BUNDLE_NAME + RandomUtil.getRandomInt(0, 1000) + '_bind';
    req.transaction ='';

    await WXApi.sendReq(AppUtil.getContext(), req)
    LoadingDialog.dismiss();
  }

  refreshData() {
    ConfigManager.userConfig()
      .then(() => {
        this.viewModel.userinfo();
        AppUtil.getContext().eventHub.emit(EventConstants.HomeRefreshEvent);
        AppUtil.getContext().eventHub.emit(EventConstants.MineRefreshEvent);
      })
  }

  build() {
    Column() {
      TitleBar({ title: '账号绑定' }).backgroundColor(Color.White)
      Row() {
        Image($r('app.media.ic_bind_wx')).width(30).height(30)
        Text('微信绑定').fontColor($r('app.color.color_1a1a1a')).fontSize(15).layoutWeight(1).margin({left: 14})
        Text(StrUtil.isEmpty(this.userEntity?.unionid) ? '立即绑定' : '解除绑定')
          .textAlign(TextAlign.Center)
          .fontColor($r('app.color.color_1a1a1a'))
          .fontSize(12)
          .borderColor($r('app.color.color_dfdfdf'))
          .borderWidth(1)
          .borderRadius(4)
          .width(64)
          .height(24)
          .onClick(() => {
            if (StrUtil.isEmpty(this.userEntity?.unionid)) {
              this.wxAuth();
            } else {
              TipDialog.show(this.getUIContext(), {title: '解除微信绑定', content: '解绑后将无法使用该微信号登录此账号，请谨慎操作！', callback: {
                confirm: () => {
                  if (StrUtil.isNotEmpty(this.userEntity?.phone)) {
                    this.viewModel.unbind('weixin');
                  } else {
                    TipDialog.show(this.getUIContext(), {title: '预警提示', content: '您若继续解除绑定，您的账号将没有绑定账号，软件在使用过程中可能会造成账号丢失！是否继续解除绑定！', callback: {
                      confirm: () => {
                        this.viewModel.unbind('weixin');
                      }
                    }})
                  }
                }
              }})
            }
          })
      }.width('100%').height(60).padding({ left: 16, right: 16 }).backgroundColor(Color.White)
      Divider().color('#EFF2F7').strokeWidth(1).margin({left: 16, right: 16})
      Row() {
        Image($r('app.media.ic_bind_phone')).width(30).height(30)
        Text('手机绑定').fontColor($r('app.color.color_1a1a1a')).fontSize(15).layoutWeight(1).margin({left: 14})
        Text(StrUtil.isEmpty(this.userEntity?.phone) ? '立即绑定' : '解除绑定')
          .textAlign(TextAlign.Center)
          .fontColor($r('app.color.color_1a1a1a'))
          .fontSize(12)
          .borderColor($r('app.color.color_dfdfdf'))
          .borderWidth(1)
          .borderRadius(4)
          .width(64)
          .height(24)
          .onClick(() => {
            if (StrUtil.isEmpty(this.userEntity?.phone)) {
              this.showBindPhoneDialog();
            } else {
              TipDialog.show(this.getUIContext(), {title: '解除手机绑定', content: '解绑后将无法使用该手机号登录此账号，请谨慎操作！', callback: {
                confirm: () => {
                  if (StrUtil.isNotEmpty(this.userEntity?.unionid)) {
                    this.viewModel.unbind('phone');
                  } else {
                    TipDialog.show(this.getUIContext(), {title: '预警提示', content: '您若继续解除绑定，您的账号将没有绑定账号，软件在使用过程中可能会造成账号丢失！是否继续解除绑定！', callback: {
                      confirm: () => {
                        this.viewModel.unbind('phone');
                      }
                    }})
                  }
                }
              }})
            }
          })
      }.width('100%').height(60).padding({ left: 16, right: 16 }).backgroundColor(Color.White)
    }
    .backgroundColor($r('app.color.window_background'))
    .height('100%')
  }
}