import { HMRouter } from '@hadss/hmrouter';
import { abilityAccessCtrl, bundleManager, common, Permissions } from '@kit.AbilityKit';
import AppConstants from '../../app/AppConstant';
import { FileUtils } from '../../util/FileUtils';
import { createWaterMark } from '../custom/Watermark';
import { HomeFragment } from '../fragment/HomeFragment';
import { MyFragment } from '../fragment/MyFragment';
import { PendingMessagePage } from '../fragment/PendingMessagePage';
import { WorkbenchFragment } from '../fragment/WorkbenchFragment';

@HMRouter({ pageUrl: 'MainPage' })
@Component
export struct MainPage {
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  @State currentIndex: number = 0
  private tabsController: TabsController = new TabsController()
  // 记录上一次点击时间
  private pretime: number = -1;

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

  /**
   * 申请权限
   */
  applyForPermission() {
    let permissions = new Array<Permissions>();
    permissions.push('ohos.permission.LOCATION')
    permissions.push('ohos.permission.APPROXIMATELY_LOCATION')
    permissions.push('ohos.permission.CAMERA')
    this.checkPermissionGrant(permissions)
  }

  /**
   * 检测权限
   * @param permissionArray
   */
  checkPermissionGrant(permissionArray: Array<Permissions>) {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
    // 获取应用程序的accessTokenID
    let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo
    let tokenId: number = appInfo.accessTokenId
    let wsqPermissionArray = new Array<Permissions>()
    for (let i = 0; i < permissionArray.length; i++) {
      let grantStatus = atManager.checkAccessTokenSync(tokenId, permissionArray[i])
      if (grantStatus == abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
        wsqPermissionArray.push(permissionArray[i])
      }
    }
    if (wsqPermissionArray.length > 0) {
      //有未申请的权限，发送到Ability,由 Ability 发起权限申请
      // this.requestPermissionsFromUser(wsqPermissionArray)
      this.context.eventHub.emit('ui_event', wsqPermissionArray);
    } else {
      //权限全部申请
      this.initPage()
      // this.getCurrentLocation()
    }
  }

  initPage() {
    FileUtils.createFileDir()

  }

  build() {
    Column() {
      Tabs({
        barPosition: BarPosition.End,
        controller: this.tabsController
      }) {
        TabContent(){
          HomeFragment({
            allMessage:()=>{
               this.tabsController.changeIndex(1)
              this.currentIndex =1
            }
          })
        }
        .tabBar(this.TabBuilder('首页', 0, $r('app.media.icon_main_home'), $r('app.media.icon_main_home_def')))

        TabContent(){
          PendingMessagePage()
        }.tabBar(this.TabBuilder('待办', 1, $r('app.media.icon_main_message'), $r('app.media.icon_main_message_def')))

        TabContent(){
          WorkbenchFragment()
        }.tabBar(this.TabBuilder('工作台', 2, $r('app.media.icon_main_work'), $r('app.media.icon_main_work_def')))

        TabContent(){
            MyFragment()
        }.tabBar(this.TabBuilder('我的', 3, $r('app.media.icon_main_my'), $r('app.media.icon_main_my_def')))

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .height(AppConstants.PERCENTAGE_MAX)
      .scrollable(false)
      .barMode(BarMode.Fixed)
      .barWidth('100%')
      .barHeight('8.7%')
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .backgroundColor($r('app.color.page_background'))
    .overlay(createWaterMark())
  }

  // 自定义导航页签的样式
  @Builder
  TabBuilder(title: string, targetIndex: number, selectedImg: Resource, normalImg: Resource) {
    Column() {
      Image(this.currentIndex === targetIndex ? selectedImg : normalImg)
        .size({ width: $r('app.float.default_24'), height:  $r('app.float.default_24') })
        .margin({top: $r('app.float.default_10')})
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? $r('app.color.bull') : '#8a8a8a')
        .fontSize($r('app.float.text_size_12'))
        .margin({top: $r('app.float.default_5')})
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.white'))
    .justifyContent(FlexAlign.Start)
    .alignItems(HorizontalAlign.Center)
    .padding({bottom: $r('app.float.default_28')})
    .onClick(() => {
      this.currentIndex = targetIndex
      this.tabsController.changeIndex(this.currentIndex)
    })
  }

}