import { AppUtil, FileUtil } from '@pura/harmony-utils'
import { EventConstants } from '../../../../common/EventConstants'
import { RouterUrls } from '../../../../common/RouterUrls'
import { TipDialog } from '../../../../dialog/TipDialog'
import { LoginManager } from '../../../../manager/LoginGlobalManager'
import { ConfigManager } from '../../../../manager/UserConfigManager'
import { ToastUtils } from '../../../../utils/ToastUtils'
import { TextItemChildView } from '../../../../view/TextItemChildView'
import { TitleBar } from '../../../../view/TitleBar'
import { SettingsViewModel } from '../../../../viewModel/SettingsViewModel'
import { router } from '@kit.ArkUI'
import { EventReportManager } from '../../../../manager/EventReportManager'
import { fileIo, storageStatistics } from '@kit.CoreFileKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { LoadingDialog } from '../../../../dialog/LoadingDialog'
import { TextItemView } from '../../../../view/TextItemView'

@Entry
@ComponentV2
struct SettingsPage {
  viewModel: SettingsViewModel = new SettingsViewModel(this.getUIContext());

  @Local cacheSize: number = 0

  @Monitor('viewModel.destroy')
  onDestroy(monitor: IMonitor) {
    EventReportManager.eventReport(EventConstants.CANCEL_ACCOUNT)
    this.logout();
    ToastUtils.show('账户已注销');
  }

  @Monitor('viewModel.logout')
  onLogout(monitor: IMonitor) {
    EventReportManager.eventReport(EventConstants.EXIT_LOGIN)
    this.logout();
  }

  aboutToAppear(): void {
    this.getCache()
  }

  getCache() {
    storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => {
      if (error) {
        console.error('getCurrentBundleStats failed with error:' + JSON.stringify(error));
      } else {
        console.info('getCurrentBundleStats successfully:' + JSON.stringify(bundleStats));
        this.cacheSize = bundleStats.cacheSize
      }
    });
  }

  // Clear cache
  clearCache() {
    LoadingDialog.show(this.getUIContext())
    let cacheDir = AppUtil.getContext().cacheDir;
    fileIo.listFile(cacheDir).then((filenames) => {
      for (let i = 0; i < filenames.length; i++) {
        let dirPath = cacheDir + '/' + filenames[i];
        let isDirectory: boolean = false;
        try {
          isDirectory = fileIo.statSync(dirPath).isDirectory();
        } catch (e) {
          console.error(JSON.stringify(e));
        }
        if (isDirectory) {
          fileIo.rmdirSync(dirPath);
        } else {
          fileIo.unlinkSync(dirPath);
        }
      }
    })
    setTimeout(() => { this.getCache() }, 200)
    LoadingDialog.dismiss()
  }


  logout() {
    LoginManager.saveLastUserInfo(LoginManager.getUserInfo()!!);
    ConfigManager.saveBindWxPlaybackHelper(false);
    ConfigManager.saveBindWxVideoHelper(false);
    LoginManager.logout();
    AppUtil.getContext().eventHub.emit(EventConstants.LogoutSuccessEvent);
    this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.LOGIN_PAGE }, router.RouterMode.Single);
  }

  build() {
    Column() {
      TitleBar({ title: '设置' }).width('100%').backgroundColor(Color.White)
      Scroll() {
        Column() {
          TextItemChildView({ text: '账号绑定' }).height(60).padding({ left: 16, right: 16 })
            .backgroundColor(Color.White)
            .onClick(() => {
              this.getUIContext().getRouter().pushUrl({url: RouterUrls.BIND_ACCOUNT_PAGE});
              EventReportManager.eventReport(EventConstants.JUMP_TO_ACCOUNT_BIND)
            })
          TextItemChildView({ text: '账号管理' }).height(60).padding({ left: 16, right: 16 })
            .backgroundColor(Color.White)
            .onClick(() => {
              this.getUIContext().getRouter().pushUrl({url: RouterUrls.MANAGE_ACCOUNT_PAGE});
              EventReportManager.eventReport(EventConstants.JUMP_TO_ACCOUNT_MANAGE)
            })
          Divider().strokeWidth(10).color($r('app.color.color_eff2f7'))
          TextItemChildView({ text: '清除缓存', rightText: FileUtil.getFormatFileSize(this.cacheSize) }).height(60)
            .backgroundColor(Color.White)
            .padding({ left: 16, right: 16 })
            .onClick(() => {
              if (this.cacheSize > 0) {
                TipDialog.show(this.getUIContext(), {title: '提示', content: '确定清除缓存？', callback: {
                  confirm: () => {
                    this.clearCache()
                  }
                }})
              }
            })
          TextItemChildView({ text: '关于我们' }).height(60).padding({ left: 16, right: 16 })
            .backgroundColor(Color.White)
            .onClick(() => {
              this.getUIContext().getRouter().pushUrl({url: RouterUrls.ABOUT_PAGE});
              EventReportManager.eventReport(EventConstants.JUMP_TO_ABOUT_US)
            })
          TextItemChildView({ text: '注销账号' }).height(60).padding({ left: 16, right: 16 })
            .backgroundColor(Color.White)
            .onClick(() => {
              TipDialog.show(this.getUIContext(), {title: '提示', content: '为了您的账户安全，注销账户后将会永久清除与该账户相关的所有信息，服务器不再保存', callback: {
                confirm: () => {
                  this.viewModel.userDestroy();
                }
              }})
            })
            .visibility(LoginManager.isLogin() ? Visibility.Visible : Visibility.None)
        }
        .justifyContent(FlexAlign.Start)
        .height('100%')
      }
      .layoutWeight(1)

      Stack() {
        Button('退出登录', { type: ButtonType.Capsule, stateEffect: true })
          .fontColor(Color.White)
          .fontSize(15)
          .fontWeight(FontWeight.Medium)
          .backgroundColor($r('app.color.color_466afd'))
          .width('100%')
          .height(46)
          .onClick(() => {
            TipDialog.show(this.getUIContext(), {title: '温馨提示', content: '确定退出登录？', callback: {
              confirm: () => {
                this.viewModel.userLogout()
              }
            }})
          })
      }
      .padding({ left: 16, right: 16 })
      .margin({ bottom: 30 })
      .visibility(LoginManager.isLogin() ? Visibility.Visible : Visibility.None)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }
}