import { it } from "@ohos/hypium";
import { MyPageSectionClass } from "../model/MyPageSectionClass";
import { MyPageSectionItem } from '../view/MyPageSectionItem'
import { common, Want } from '@kit.AbilityKit';
import notificationManager from '@ohos.notificationManager';
import { Theme } from "@ohos.arkui.theme";
import { BusinessError } from "@kit.BasicServicesKit";
import emitter from '@ohos.events.emitter';

@Component
export struct FourSection {
  @State sectionTitle: string = "常规操作";
  @State currentIndex: number = 0;
  @State pushStatus: string = '通知已开';
  @State refreshFlag: boolean = false;

  @State fourSectionList:Array<MyPageSectionClass> = [
    new MyPageSectionClass('oneItem',$r('app.media.app_icon'),'微信绑定','/pages/MyHomePage'),
    new MyPageSectionClass('twoItem',$r('app.media.app_icon'),'更换手机号','/pages/MyHomePage'),
    new MyPageSectionClass('threeItem',$r('app.media.app_icon'),this.pushStatus,'/pages/MyHomePage'),
    new MyPageSectionClass('fourItem',$r('app.media.app_icon'),'发现新版本','/pages/MyHomePage')
  ];

  aboutToAppear() {
    console.log('FourSection aboutToAppear!');
    this.checkNotificationStatus();

    // 监听通知状态变化事件
    emitter.on('notification_status_changed', this.onNotificationChanged);
  }

  aboutToDisappear() {
    // 取消事件监听
    emitter.off('notification_status_changed', this.onNotificationChanged);
  }

  private onNotificationChanged = () => {
    console.log('收到通知状态变化事件');
    this.checkNotificationStatus();
  }

  private getPagedItems(): Array<Array<MyPageSectionClass>> {
    const pages: Array<Array<MyPageSectionClass>> = [];
    const itemsPerPage = 4;
    for (let i = 0; i < this.fourSectionList.length; i += itemsPerPage) {
      pages.push(this.fourSectionList.slice(i, i + itemsPerPage));
    }
    return pages;
  }

  async checkNotificationStatus() {
    try {
      let isEnabled = await notificationManager.isNotificationEnabledSync();
      console.log('当前通知状态:', isEnabled);
      this.pushStatus = isEnabled ? '通知已开' : '通知已关';
      // 更新数组中的标题
      this.fourSectionList = this.fourSectionList.map((item, index) => {
        if (index === 2) {
          return new MyPageSectionClass(item.id, item.imageSrc, this.pushStatus, item.path);
        }
        return item;
      });
    } catch (error) {
      console.error('Failed to check notification status:', error);
    }
  }

  private handleNotificationClick() {
    let want: Want = {
      bundleName: 'com.huawei.hmos.settings',
      abilityName: 'com.huawei.hmos.settings.MainAbility',
      uri: 'application_info_entry',
      parameters: {
        pushParams: 'com.example.expert'
      }
    };
    const context = getContext(this) as common.UIAbilityContext;
    // 发送全局事件
    emitter.emit('notification_status_changed');
    context.startAbility(want).catch((err:BusinessError) => {
      console.error('Failed to start ability:', err);
    });
  }

  build() {
    Column() {
      // 标题
      Text(this.sectionTitle)
        .fontSize(17)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 10, left: 13 })
        .height(42)

      Column() {
        Stack({ alignContent: Alignment.Bottom }) {
          Swiper() {
            ForEach(this.getPagedItems(), (pageItems: Array<MyPageSectionClass>, index?: number) => {
              Grid() {
                ForEach(pageItems, (item: MyPageSectionClass) => {
                  GridItem() {
                    MyPageSectionItem({ sectionItem: item })
                  }
                  .onClick(()=>{
                    if (item.title.includes('通知')) {
                      this.handleNotificationClick();
                    }
                  })
                }, (item: MyPageSectionClass) => item.id)
              }
              .columnsTemplate('1fr 1fr 1fr 1fr')
              .columnsGap(8)
              .rowsGap(8)
              .height('100%')
              .width('100%')
            })
          }
          .index(this.currentIndex)
          .onChange((index: number) => {
            this.currentIndex = index;
          })
          .height(78)
          .indicator(false)

          if (this.fourSectionList.length > 4) {
            Row() {
              ForEach(new Array(Math.ceil(this.fourSectionList.length / 4)).fill(0), (item: number, idx: number) => {
                Row()
                  .width('50%')
                  .height(6)
                  .borderRadius(3)
                  .backgroundColor(this.currentIndex === idx ? '#8B2316' :
                    '#D8D8D8')// .margin({ right: idx !== Math.ceil(this.oneSectionList.length / 4) - 1 ? 0 : 0 })
                  .margin({ right: 0 })
              }, (item: number, index: number) => index.toString())
            }
            .justifyContent(FlexAlign.Center)
            .backgroundColor('#D8D8D8')
            .height(6)
            .width(23)
            .borderRadius(3)
            .margin({ bottom: 8 })
          }
        }
      }
      .padding({ left: 20, right: 20 })
    }
    .alignItems(HorizontalAlign.Start)
    .backgroundColor(Color.White)
    .borderRadius(5)
    .margin({ top: 10, left: 10, right: 10 })
  }
}