import { AppUtil, StrUtil } from '@pura/harmony-utils';
import { EventConstants } from '../../../../../common/EventConstants';
import { LoadingDialog } from '../../../../../dialog/LoadingDialog';
import { TipDialog } from '../../../../../dialog/TipDialog';
import { AccountEntity } from '../../../../../entity/AccountEntity';
import { LoginEntity } from '../../../../../entity/LoginEntity';
import { EventReportManager } from '../../../../../manager/EventReportManager';
import { LoginManager } from '../../../../../manager/LoginGlobalManager';
import { ConfigManager } from '../../../../../manager/UserConfigManager';
import { ToastUtils } from '../../../../../utils/ToastUtils';
import { AccountItemView } from '../../../../../view/AccountItemView';
import { TitleBar } from '../../../../../view/TitleBar';
import ManageAccountViewModel from '../../../../../viewModel/ManageAccountViewModel';

@Entry
@ComponentV2
struct ManageAccountPage {
  viewModel: ManageAccountViewModel = new ManageAccountViewModel(this.getUIContext());

  @Local accountList: AccountEntity[] = [];

  @Local currentAccount?: AccountEntity;

  @Monitor('viewModel.accounts')
  onAccountsChange(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<AccountEntity>;
    list.forEach((item) => {
      if (item.user_id === LoginManager.getUserInfo()?.user_id) {
        this.currentAccount = item;
      } else {
        this.accountList.push(item);
      }
    })
    if (this.currentAccount === null && LoginManager.getUserInfo()) {
      let userinfo = LoginManager.getUserInfo()!!
      let account = new AccountEntity()
      let bind: string[] = []
      if (StrUtil.isNotEmpty(userinfo.unionid)) {
        bind.push("weixin")
      }
      if (StrUtil.isNotEmpty(userinfo.phone)) {
        bind.push('phone')
      }
      account.user_id = userinfo.user_id
      account.name = userinfo.name
      account.avater = userinfo.avater
      account.phone = userinfo.phone
      account.vip_name = userinfo.vip_name
      account.vip_type = userinfo.vip
      account.bind = bind
      this.currentAccount = account
    }
  }

  @Monitor('viewModel.loginEntity')
  onLoginChange(monitor: IMonitor) {
    const loginEntity = monitor.value()?.now as LoginEntity;
    LoginManager.saveToken(loginEntity.token);
    LoginManager.saveLastLoginType('device')
    LoginManager.saveLastUserInfo(LoginManager.getUserInfo()!!);
    ConfigManager.saveBindWxPlaybackHelper(false);
    ConfigManager.saveBindWxVideoHelper(false);
    ConfigManager.userConfig()
      .then(() => {
        ToastUtils.show('切换成功');
        AppUtil.getContext().eventHub.emit(EventConstants.LoginSuccessEvent);
        this.getUIContext().getRouter().back();
      })
      .finally(() => {
        LoadingDialog.dismiss();
      })
  }

  aboutToAppear(): void {
    this.viewModel.accountList();
  }

  build() {
    Column() {
      TitleBar({ title: '账户管理' }).backgroundColor(Color.White)

      Scroll() {
        Column() {
          AccountItemView({ account: this.currentAccount }).margin({ left: 20, top: 14, right: 20 })

          List() {
            ForEach(this.accountList, (item: AccountEntity) => {
              ListItem() {
                AccountItemView({account: item})
              }
              .margin({ left: 20, top: 14, right: 20 })
              .onClick(() => {
                TipDialog.show(this.getUIContext(), {title: '温馨提示', content: '是否确定切换账号？', callback: {
                  confirm: () => {
                    LoginManager.saveToken('');
                    this.viewModel.changeAccount(item.user_id);
                    EventReportManager.eventReport(EventConstants.SWITCH_ACCOUNT,item.user_id)
                  }
                }})
              })
            })
          }
          .width('100%')
          .height('auto')
          .layoutWeight(1)
          .margin({ bottom: 30 })
          .visibility(this.accountList.length > 0 ? Visibility.Visible : Visibility.Hidden)
        }
      }
      .layoutWeight(1)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}