import { router, window } from '@kit.ArkUI';
import { HomePage } from './home/HomePage';
import { MinePage } from './mine/MinePage';
import systemDateTime from '@ohos.systemDateTime';
import { ToastUtils } from '../../utils/ToastUtils';
import { AppUtil, PasteboardUtil, StrUtil } from '@pura/harmony-utils';
import { EventConstants } from '../../common/EventConstants';
import { MainViewModel } from '../../viewModel/MainViewModel';
import { UserEntity } from '../../entity/UserEntity';
import { SimpleTipDialog } from '../../dialog/SimpleTipDialog';
import { RouterUrls } from '../../common/RouterUrls';
import { TipDialog } from '../../dialog/TipDialog';
import { ConfigManager } from '../../manager/UserConfigManager';
import { EventReportManager } from '../../manager/EventReportManager';
import { PasteboardUtils } from '../../utils/PasteboardUtils';
import { MaterialPage } from './material/MaterialPage';
import { ToolsPage } from './mine/tool/ToolsPage';

@Entry
@ComponentV2
struct MainPage {
  windowStage: window.WindowStage = AppStorage.get("windowStage") as window.WindowStage;

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

  tabController: TabsController = new TabsController()

  userinfo?: UserEntity;

  titles = ['首页', '素材库', '工具', '我的'];

  clickTime: number = 0;

  @Local currentIndex: number = 0;
  @Provider() recordIndex: number = 0

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

  aboutToAppear(): void {
    this.windowStage.getMainWindowSync().setWindowSystemBarProperties({
      statusBarColor: '#00000000',
      statusBarContentColor: '#000000'
    });
    this.initObserver();
    ConfigManager.userConfig()
  }

  aboutToDisappear(): void {
    AppUtil.getContext().eventHub.off(EventConstants.LoginSuccessEvent);
    AppUtil.getContext().eventHub.off(EventConstants.JumpToRecordEvent);
    AppUtil.getContext().eventHub.off(EventConstants.JumpToToolsEvent);
  }

  onPageShow(): void {
    this.viewModel.userinfo();
    if (this.currentIndex === 3) {
      AppUtil.getContext().eventHub.emit(EventConstants.MineRefreshEvent);
      AppUtil.getContext().eventHub.emit(EventConstants.RecordRefreshEvent);
    }
    this.checkPasteboard()
  }

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.LoginSuccessEvent, () => {
      AppUtil.getContext().eventHub.emit(EventConstants.HomeRefreshEvent);
      AppUtil.getContext().eventHub.emit(EventConstants.MineRefreshEvent);
    })
    AppUtil.getContext().eventHub.on(EventConstants.JumpToRecordEvent, (index: number) => {
      this.tabController.changeIndex(3)
      this.currentIndex = 1
    })
    AppUtil.getContext().eventHub.on(EventConstants.JumpToToolsEvent, () => {
      this.tabController.changeIndex(2)
    })
  }

  checkPasteboard() {
    PasteboardUtils.isNeedGetPermissionFromUser()
      .then((isNeed) => {
        if (isNeed) {
          PasteboardUtil.requestPermissions()
            .then((isGranted) => {
              if (isGranted) {
                let content = PasteboardUtil.getDataTextSync()
                if (StrUtil.isNotEmpty(content) && content !== PasteboardUtils.clipText && PasteboardUtils.isValidUrl(content)) {
                  TipDialog.show(this.getUIContext(), {title: '您已复制链接，是否粘贴', content: content, leftText: '取消', rightText: '粘贴', callback: {
                    confirm: () => {
                      PasteboardUtils.clipText = content
                      this.getUIContext().getRouter().pushUrl({url: RouterUrls.TAKE_MATERIAL_PAGE, params:{url: content}})
                    },
                    cancel: () => {
                      PasteboardUtils.clipText = content
                    }
                  }})
                }
              }
            })
            .catch(() => {})
        }
      })
  }

  build() {
    Tabs({ controller: this.tabController, barPosition: BarPosition.End }) {
      TabContent() {
        HomePage()
      }
      .tabBar(this.tabBuilder(this.titles[0], 0, $r('app.media.ic_home_select'), $r('app.media.ic_home_default')))

      TabContent() {
        MaterialPage()
      }
      .tabBar(this.tabBuilder(this.titles[1], 1, $r('app.media.ic_material_select'), $r('app.media.ic_material_default')))

      TabContent() {
        ToolsPage()
      }
      .tabBar(this.tabBuilder(this.titles[2], 2, $r('app.media.ic_tool_select'), $r('app.media.ic_tool_default')))

      TabContent() {
        MinePage()
      }
      .tabBar(this.tabBuilder(this.titles[3], 3, $r('app.media.ic_mine_select'), $r('app.media.ic_mine_default')))
    }
    .scrollable(false)
    .onSelected((index: number) => {
      this.currentIndex = index;
      if (index === 3) {
        AppUtil.getContext().eventHub.emit(EventConstants.MineRefreshEvent);
      }
      this.showLoginTip();
      EventReportManager.eventReport(EventConstants.HOME_BOTTOM_TAB_CHECK, this.titles[index], '')
    })
    .padding({ bottom: 20 })
    .backgroundColor(Color.White)
  }

  @Builder
  tabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
    Column() {
      Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
        .size({ width: 24, height: 24 })
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? $r("app.color.color_466afd") : '#676E87')
        .fontSize(10)
    }
    .width('100%')
    .height(50)
    .justifyContent(FlexAlign.Center)
  }

  showLoginTip() {
    if (this.userinfo && this.userinfo.temp && (this.userinfo.vip === 2 || this.userinfo.vip == 3)) {
      SimpleTipDialog.show(this.getUIContext(), {
        title: '郑重提示',
        content: '系统检测到您目前尚未登录，但您已成为我们尊贵的会员，为了防止您的会员账号丢失，建议您立即前往登录',
        buttonText: '立即登录',
        callback: {
          confirm: () => {
            this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.LOGIN_PAGE }, router.RouterMode.Single)
          }
        }
      }, false)
    }
  }

  onBackPress(): boolean | void {
    if (systemDateTime.getTime() - this.clickTime < 1500) {
      AppUtil.getContext().terminateSelf();
    } else {
      EventReportManager.eventReport(EventConstants.EXIT_APP, 'main')
      this.clickTime = systemDateTime.getTime();
      ToastUtils.show('双击退出应用');
    }
    return true;
  }
}