import { USER_INFO } from '@ohos/common/src/main/ets/constants/AppConstants';
import { TipsDialog } from '@ohos/common/src/main/ets/dialog/TipsDialog';
import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils';
import { KVStore } from '@ohos/common/src/main/ets/utils/KVStore';
import { CommonService } from '@ohos/common/src/main/ets/viewmodel/CommonService';
import { UserInfo } from '@ohos/common/src/main/ets/viewmodel/DataBean';
import { TitleBarComponent } from '../view/TitleBarComponent';
import { MainService } from '../viewmodel/MainService';
import { BindParams } from '@ohos/common/src/main/ets/viewmodel/ParamBean';
import { getWechatAuthCode } from '@ohos/common/src/main/ets/utils/KVManager';

@Builder
export function AccountBindBuilder() {
  AccountBindLayout()
}

/**
 * 设置页面
 */
@Component
export struct AccountBindLayout {
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;
  private unBindType: number = 0;//0:Normal 1:phone 2:微信
  @State currentUserInfo: UserInfo | undefined = undefined;

  dialogController: CustomDialogController = new CustomDialogController({
    builder: TipsDialog({
      title: this.unBindType===2 ? '确定解除绑定的微信？' : '解开绑定的手机号？',
      content: this.unBindType===2 ? '解除后将无法使用该微信登录此账号，请谨慎操作！' : '当前绑定的手机号码为',
      desc: this.unBindType===2 ? '' : '+86 ' + this.currentUserInfo?.phone?.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'),
      cancel: () => { console.info('用户点击取消') },
      confirm: () => {
        if(this.unBindType===1){
          // 解绑请求
          MainService.unBindPhone(this.currentUserInfo?.phone || '',{
            onSuccess: (_) => {
              UnBindSuccess()
              //添加1秒延迟，防止数据未写入
              setTimeout(() => {
                KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
                  this.currentUserInfo = JSON.parse(userJson) as UserInfo;
                })
              }, 1000);
            },
            onFailure: (message) => {
              ToastUtils.showToast(this.getUIContext(), message);
            },
            onError: (_) => {
              ToastUtils.showToast(this.getUIContext(), '解绑失败');
            }
          })
        }else{
          // 解绑微信
          getWechatAuthCode().then(wechatCode => {
            // 微信解绑请求
            MainService.unBindWechat(wechatCode,{
              onSuccess: (_) => {
                UnBindSuccess()
                //添加1秒延迟，防止数据未写入
                setTimeout(() => {
                  KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
                    this.currentUserInfo = JSON.parse(userJson) as UserInfo;
                  })
                }, 1000);
              }
            })
          })
        }
        this.unBindType = 0
      }
    }),
    alignment: DialogAlignment.Center, // 居中显示
    customStyle: true, // 使用自定义样式，去掉系统默认背景
    autoCancel: true // 点击遮罩层可关闭
  })

  aboutToAppear() {
    KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
      this.currentUserInfo = JSON.parse(userJson) as UserInfo;
    })
  }

  build() {
    NavDestination() {
      Stack() {
        Scroll(){
          Column() {
            //标题栏
            TitleBarComponent({titleName:'账号绑定', isShowTitle:true, isShowBack:true})

            // 内容区
            Column(){
              Column() {
                Row() {
                  Text('手机号')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)


                  Row(){
                    if(this.currentUserInfo?.phone && !this.currentUserInfo?.temp){
                      Text('+86')
                        .fontSize(14)
                        .fontColor('#4d767676')
                        .textAlign(TextAlign.Center)
                        .borderRadius(12)
                      Text(this.currentUserInfo?.phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2'))
                        .fontSize(14)
                        .fontColor('#4d767676')
                        .textAlign(TextAlign.Center)
                        .borderRadius(12)
                        .margin({ left: 8 })
                    }else{
                      Text('去绑定')
                        .fontSize(14)
                        .fontColor('#4d767676')
                        .textAlign(TextAlign.Center)
                        .borderRadius(12)
                        .margin({ left: 8 })
                    }
                    Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                  }
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  if(this.currentUserInfo?.phone && !this.currentUserInfo?.temp){
                    // 解绑,弹出确认窗
                    this.unBindType = 1
                    this.dialogController.open()
                  }else{
                    // 绑定手机号
                    const params: BindParams = {
                      id: 1001,
                      name: "手机",
                      type: 1
                    };
                    this.pageStack.pushPathByName("AccountBindLoginLayout", params);
                  }
                })

                Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

                Row() {
                  Text('微信账号')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)


                  Row(){
                    Text(this.currentUserInfo?.weixinAppId  && !this.currentUserInfo?.temp ? '已绑定' : '去绑定')
                      .fontSize(14)
                      .fontColor('#4d767676')
                      .textAlign(TextAlign.Center)
                      .borderRadius(12)
                    Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                  }
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  // 绑定微信
                  if(this.currentUserInfo?.weixinAppId  && !this.currentUserInfo?.temp){
                    // 解绑,弹出确认窗
                    this.unBindType = 2
                    this.dialogController.open()
                  }else{
                    // 绑定微信
                    const params: BindParams = {
                      id: 1002,
                      name: "微信",
                      type: 2
                    };
                    this.pageStack.pushPathByName("AccountBindLoginLayout", params);
                  }
                })

              }
              .backgroundColor(Color.White)
              .width('100%')
              .borderRadius(12)
              .margin({ top: 30})
            }
            .padding({ left: 16, right: 16})
          }
          .width('100%')
          .height('100%')
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
      }
      .width('100%')
      .height('100%')
      .alignContent(Alignment.Bottom)
      .backgroundColor('#FFF9F9F9')
    }
    .hideTitleBar(true)
    .onShown(() => {
      // 上一页返回时，刷新账号数据(添加1秒延迟，防止数据未写入)
      setTimeout(() => {
        let result = AppStorage.get<Record<string, Object>>('back');
        if (result && result.isBack && result.source === 'bindLogin') {
          KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
            this.currentUserInfo = JSON.parse(userJson) as UserInfo;
          })
          AppStorage.setOrCreate('back', null); // 用完即删，防止重复触发
        }
      }, 1000);
    })
  }
}

function UnBindSuccess() {
  ToastUtils.normalToast({
    message: '已解除绑定',        // 提示文字
    duration: 2000,            // 显示时长 (ms)，默认 1500
    bottom: '50%'
  });

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

}