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

@Builder
export function AccountManagerBuilder() {
  AccountManagerLayout()
}

/**
 * 设置页面
 */
@Component
export struct AccountManagerLayout {
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;

  @State currentUserInfo: UserInfo | undefined = undefined;
  @State accountList: Array<UserInfo>|undefined = undefined
  @State selectedAccount: UserInfo | undefined = undefined;

  dialogController: CustomDialogController = new CustomDialogController({
    builder: TipsDialog({
      title: '您确定要切换账户吗？',
      content: '',
      desc: '',
      cancel: () => { console.info('用户点击取消') },
      confirm: () => {
        if (!this.selectedAccount) {
          ToastUtils.normalToast({
            message: '出错啦~',        // 提示文字
            bottom: '50%'
          });
          return;
        }
        MainService.switchAccount(this.selectedAccount.user_id??'',{
          onSuccess: (_) => {
            ToastUtils.normalToast({
              message: '切换成功',        // 提示文字
              bottom: '50%'
            });

            //重新获取用户配置(数据会持久化到本地)
            setTimeout(() => {
              this.syncData()
            }, 1000);
          }
        })
      }
    }),
    alignment: DialogAlignment.Center, // 居中显示
    customStyle: true, // 使用自定义样式，去掉系统默认背景
    autoCancel: true // 点击遮罩层可关闭
  })

  async syncData() {
    await CommonService.getUserProfile()
    await CommonService.getUserInfo()
    KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
      this.currentUserInfo = JSON.parse(userJson) as UserInfo;
    })
    MainService.getAccount().then(res => {
      this.accountList = res;
    });
  }

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

  build() {
    NavDestination() {
      Stack() {
        Image($r('app.media.ic_mine_account_mask'))
          .width('100%')
          .height('100%')
          .backgroundColor('#FFF9F9F9')

        Column() {
          //标题栏
          TitleBarComponent({titleName:'', isShowTitle:false, isShowBack:true})

          Stack (){
            List(){
              // 标题栏
              ListItem() {
                Text('轻触头像以切换帐号')
                  .width('100%')
                  .fontSize(16)
                  .fontColor('#FF1A1A1A')
                  .textAlign(TextAlign.Center)
                  .borderRadius(12)
                  .fontWeight(1)
                  .fontWeight(FontWeight.Bold)
                .margin({ bottom: 55 })
              }

              ForEach(this.accountList, (item: UserInfo) => {
                ListItem() {
                  AccountItem({
                    currentUserInfo: this.currentUserInfo,
                    item: item,
                    isChecked: item.user_id === this.currentUserInfo?.user_id,
                    onChange: (_: boolean) => {
                      // 切换帐号
                      this.selectedAccount = item;
                      this.dialogController.open()
                    }
                  })
                }
              })

              // 添加帐号栏
              ListItem() {
                Row() {
                  Stack(){
                    Image($r('app.media.ic_image_add'))
                      .width('100%')
                      .height('100%')
                  }
                  .width('60vp')
                  .height('60vp')
                  .margin({ left: 11, right: 11, top: 16, bottom: 16})
                  .alignContent(Alignment.Center)
                  .backgroundColor('#FFF3F3F3')
                  .borderRadius(8)

                  Text('添加帐号')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(FontWeight.Bold)
                    .layoutWeight(1)
                }
                .width('100%')
                .height('80vp')
                .margin({ bottom: 46 })
                .backgroundColor('#FFFFFFFF')
                .borderRadius(8)
                .shadow({
                  radius: 5,           // 阴影模糊半径（数值越大越模糊）
                  color: '#4DE5E5E5',  // 阴影颜色（建议带透明度，如 10% 透明的黑色）
                  offsetX: 0,          // X 轴偏移
                  offsetY: 0           // Y 轴偏移（正数向下，负数向上）
                })
                .onClick(() => {
                  routerLogin('account',false)
                })
              }
            }
            .width('100%')
            .scrollBar(BarState.Off)
            .edgeEffect(EdgeEffect.None)
          }
          .width('100%')
          .layoutWeight(1)
          .alignContent(Alignment.Center)
          .padding({ left: 16, right: 16})
        }
        .width('100%')
        .height('100%')
      }
      .width('100%')
      .height('100%')
    }
    .hideTitleBar(true)
    .onShown(() => {
      // 上一页返回时，刷新账号数据
      let result = AppStorage.get<Record<string, Object>>('back');
      if (result && result.isBack && result.source === 'login') {
        MainService.getAccount().then(res => {

          setTimeout(() => {
            // 延迟刷新当前登录用户信息，否则可能因为数据未刷新而显示错误
            KVStore.getInstance().get(USER_INFO, '{}').then(userJson => {
              this.currentUserInfo = JSON.parse(userJson) as UserInfo;
              this.accountList = res;
            })
          }, 800);
        });
        AppStorage.setOrCreate('back', null); // 用完即删，防止重复触发
      }
    })
  }
}

/**
 * 账号 item
 */
@Component
export struct AccountItem {
  @State currentUserInfo: UserInfo | undefined = undefined;
  @State item: UserInfo | null = null;
  @State isChecked: boolean = false;
  onChange: (checked: boolean) => void = () => {};

  build() {
    Row() {
      Stack(){
        Image(this.item?.avater || $r('app.media.ic_mine_user_normal'))
          .width('100%')
          .height('100%')
          .borderRadius(8)
          .onClick(() => {
          })
      }
      .width('60vp')
      .height('60vp')
      .margin({ left: 11, right: 11, top: 16, bottom: 16})
      .alignContent(Alignment.Center)
      .backgroundColor('#FFF3F3F3')
      .borderRadius(8)

      Column(){
        Text(this.item?.name || '大白兔')
          .width('100%')
          .layoutWeight(1)
          .fontSize(16)
          .fontColor('#FF1A1A1A')
          .textAlign(TextAlign.Start)
          .borderRadius(12)
          .fontWeight(FontWeight.Medium)

        Text('ID: ' + this.item?.user_id)
          .width('100%')
          .fontSize(12)
          .fontColor('#FF767676')
          .textAlign(TextAlign.Start)
          .borderRadius(12)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
      .layoutWeight(1)
      .margin({ top: 16, bottom: 16 })

      Image(this.isChecked ?
        $r('app.media.ic_tick_circle_selected') : // 选中的图片资源
        $r('app.media.ic_tick_circle_normal') // 未选中的图片资源
      )
        .width(20)
        .height(20)
        .margin({ right: 16 })
        .objectFit(ImageFit.Contain)
        // 添加点击时的缩放动画，增加反馈感
        .animation({ duration: 200, curve: Curve.EaseInOut })
    }
    .width('100%')
    .height('80vp')
    .backgroundColor('#FFFFFFFF')
    .borderRadius(8)
    .shadow({
      radius: 5,           // 阴影模糊半径（数值越大越模糊）
      color: '#4DE5E5E5',  // 阴影颜色（建议带透明度，如 10% 透明的黑色）
      offsetX: 0,          // X 轴偏移
      offsetY: 0           // Y 轴偏移（正数向下，负数向上）
    })
    .margin({ bottom: 16 })
    .onClick(() => {
      if(this.isChecked && this.item?.user_id === this.currentUserInfo?.user_id) {
        ToastUtils.showToast(this.getUIContext(), '当前帐号已登录');
        return
      };
      //this.isChecked = !this.isChecked;
      this.onChange(this.isChecked);
    })
  }
}

