MineSettingComponent.ets 10.1 KB
import { BottomNavi, CommonConstants, SpConstants } from 'wdConstant';
import { BreakpointSystem, Logger, SPHelper, StringUtils } from 'wdKit';
import PageViewModel from '../../viewmodel/PageViewModel';
import storageStatistics from "@ohos.file.storageStatistics";
import { BusinessError } from '@ohos.base';
import router from '@ohos.router';
import { WDRouterPage, WDRouterRule } from 'wdRouter';
import { Params } from 'wdBean';
// import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { CustomCacheDialog } from './CustomCacheDialog';
import { MineSettingDatasModel } from '../../model/MineSettingDatasModel';
import { MineMainSettingFunctionItem } from '../../viewmodel/MineMainSettingFunctionItem';
import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences';
import { TitleBackComponent } from './TitleBackComponent';
import { MyCustomDialog } from '../reusable/MyCustomDialog';
import { TrackingButton, TrackConstants } from 'wdTracking/Index';
import { JSON } from '@kit.ArkTS';
import { HttpUtils } from 'wdNetwork/Index';

@Component
export struct MineSettingComponent {
  // @State listData: Array<string | Array<string>> = new Array();
  @State listData: Array<MineMainSettingFunctionItem> = new Array;
  @State privacySwitch: boolean = false
  @State cacheSize: number = 0
  @State accountState:boolean=false
  preferences: dataPreferences.Preferences | null = null;
  @StorageProp('currentBreakpoint') @Watch("currentChanged")currentBreakpoint: string = 'sm';
  private breakpointSystem = new BreakpointSystem();
  @State percent:number = 1

  currentChanged(){
    if(this.currentBreakpoint == "md" || this.currentBreakpoint == "lg"){
      this.percent = 0.7
    }else {
      this.percent = 1
    }
  }

  dialogController: CustomDialogController = new CustomDialogController({
    builder: MyCustomDialog({
      cancel: () => {
      },
      confirm: () => {
        this.deleteCache()
      },
      title: "清理缓存",
      tipValue:"是否确认清理此App的缓存",
      tipShow:true,
      leftTextColor:$r('app.color.color_333333')
    }),
    autoCancel: true,
    alignment: DialogAlignment.Center,
    customStyle: true
  })
  aboutToAppear() {
    this.breakpointSystem.register();
    this.currentChanged()
    // 获取设置页面数据
    this.getSettingPageData()

    this.getCacheSize()

    this.getAccountState()

    this.addLoginStatusObserver()

  }

  aboutToDisappear(): void {
    this.breakpointSystem.unregister();
  }

  async getAccountState(){
    let userId=await SPHelper.default.get(SpConstants.USER_ID,'') as string
    if(userId==''){
      this.accountState=false
    }else {
      this.accountState=true
    }
  }

  async getSettingPageData() {
    let oldList = MineSettingDatasModel.getMineMainSettingFunctionItemData();
    if (!HttpUtils.isLogin()) {
      this.listData = oldList.slice(1,oldList.length)
    } else {
      this.listData = oldList;
    }

  }

  build() {
    Column(){
      TitleBackComponent({title:"设置"})
      this.settingList()
    }
  }

  // 页面布局
  @Builder settingList() {
    Column() {
      List() {
        // 循环渲染ListItemGroup,contactsGroups为多个分组联系人contacts和标题title的数据集合
        ForEach(this.listData, (item: MineMainSettingFunctionItem, index: number) => {
          ListItem() {
            if (item.type == 0) {
              Column() {
                this.getArrowCell(item,index)
              }.padding({ left: `${this.calcHeight(27)}lpx` }).height(`${this.calcHeight(117)}lpx`).justifyContent(FlexAlign.Center)
            } else if (item.type == 1) {
              Column() {
                this.getSwitchCell(item,index)
              }.padding({ left: `${this.calcHeight(27)}lpx` }).height(`${this.calcHeight(117)}lpx`).justifyContent(FlexAlign.Center)
            } else {
              Column().width('100%').height(`${this.calcHeight(15)}lpx`).backgroundColor(0xf0f0f0)
            }
          }
        })
      }.onScrollFrameBegin((offset, state) => {
        return { offsetRemain: 0 }
      }).divider({strokeWidth:1,color:"#f0f0f0",startMargin: 15,endMargin: 10})
    }
    .backgroundColor(Color.White)
    .borderRadius(8)
  }

  @Builder itemHead(text: string) {
    // 列表分组的头部组件,对应联系人分组A、B等位置的组件
    if (text.length > 0) {
      Row().width('100%').height(`${this.calcHeight(20)}lpx`).backgroundColor(0xf0f0f0)
    }
  }

  // 右侧开关cell
  @Builder getSwitchCell(item:MineMainSettingFunctionItem, index:number) {
    Column() {
      Row() {
        // 左侧logo和标题
        Row() {
          // 判断有没有图片
          if (0) {
            Image('https://pic.rmb.bdstatic.com/e182cf67c341d1128d2a6cc05886bf62.jpeg@s_0,h_2000')
              .height(`${this.calcHeight(38)}lpx`)
              .margin({ right: `${this.calcHeight(5)}lpx` })

            Text(`${item.title}`)
              .margin({ top: `${this.calcHeight(8)}lpx` })
              .height(`${this.calcHeight(38)}lpx`)
              .fontColor('#333333')
              .fontSize(`${this.calcHeight(29)}lpx`)
          } else {
            Text(`${item.title}`)
              .margin({ top: `${this.calcHeight(8)}lpx` })
              .height(`${this.calcHeight(38)}lpx`)
              .fontColor('#333333')
              .fontSize(`${this.calcHeight(29)}lpx`)
          }
        }.width('60%')

        // 右侧文案和右箭头
        Row() {
          Toggle({ type: ToggleType.Switch, isOn: item.switchState })
            .height(`${this.calcHeight(50)}lpx`)
            .width(`${this.calcHeight(96)}lpx`)
            .margin({ left: `${this.calcHeight(81)}lpx`, right: `${this.calcHeight(29)}lpx` })
            .selectedColor("#ED2800")
            .onChange((isOn: boolean) => {
              Logger.debug("SPHelper", "数据 : " + JSON.stringify(item))
              if(item.itemType=='push_switch'){
                trackButtonClick("settingPagePushSwitch")
                //推送
                SPHelper.default.save(SpConstants.SETTING_PUSH_SWITCH,isOn)
              }else if(item.itemType=='wifi_switch'){
                trackButtonClick("settingPageOnlyWifiNetworkLoadPicture")
                //wifi 图片
                SPHelper.default.save(SpConstants.SETTING_WIFI_IMAGE_SWITCH,isOn)
              }else if(item.itemType=='video_switch'){
                trackButtonClick("settingPageAutomaticallyPlayVideoOnWifiNetwork")
                //wifi 视频
                SPHelper.default.save(SpConstants.SETTING_WIFI_VIDEO_SWITCH,isOn)
              }else if(item.itemType=='suspensionState_switch'){
                trackButtonClick("settingPagePlayerFloatingWindowSwitchClick")
                //悬浮窗
                SPHelper.default.save(SpConstants.SETTING_SUSPENSION_SWITCH,isOn)
              }
            })
        }.width('40%')
        .margin({ right: `${this.calcHeight(29)}lpx` })
        .justifyContent(FlexAlign.End)

      }
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.SpaceBetween)
    }.height(`${this.calcHeight(54)}lpx`)
  }

  // 右文字+箭头cell
  @Builder getArrowCell(item:MineMainSettingFunctionItem, index:number) {
    Column() {

      Row() {
        // 左侧logo和标题
        Row() {
          Text(`${item.title}`)
            .margin({ top: `${this.calcHeight(8)}lpx` })
            .height(`${this.calcHeight(38)}lpx`)
            .fontColor('#333333')
            .fontSize(`${this.calcHeight(29)}lpx`)
        }.width('60%')

        // 右侧文案和右箭头
        Row() {
          Text((item.itemType=='clear_cache') ? this.cacheSize.toFixed(2) + 'M' : '')
            .fontColor('#999999')
            .maxLines(1)
          Image($r('app.media.mine_user_arrow_2'))
            .width(`${this.calcHeight(27)}lpx`)
            .height(`${this.calcHeight(27)}lpx`)
            .objectFit(ImageFit.Auto)
            .interpolation(ImageInterpolation.High)
          Column().width(`${this.calcHeight(29)}lpx`)
        }.width('40%')
        .margin({ right: `${this.calcHeight(29)}lpx` })
        .justifyContent(FlexAlign.End)

      }
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.SpaceBetween)

    }
    .height(`${this.calcHeight(54)}lpx`)
    .onClick(() => {
      if (item.itemType == 'account') {
        trackButtonClick("settingPageAccountManagement")
        let params: Params = {
          pageID: 'AccountAndSecurityLayout'
        }
        WDRouterRule.jumpWithPage(WDRouterPage.settingPage, params)
      } else if (item.itemType == 'private_setting') {
        WDRouterRule.jumpWithPage(WDRouterPage.privacySettingPage)
        trackButtonClick("settingPagePrivacySettings")
      } else if (item.itemType == 'clear_cache') {
        trackButtonClick("settingPageClearCache")
        this.dialogController.open()
      }
    })

  }

  //删除缓存
  deleteCache() {
    let context = getContext(this) as common.UIAbilityContext
    let application = context.getApplicationContext();
    let appPath = application.cacheDir
    Logger.debug("MineSettingComponent", appPath)
    fs.rmdir(appPath).then(() => {
      this.getCacheSize()
    })
    let path = context.cacheDir
    Logger.debug("MineSettingComponent", path)
    fs.rmdir(path).then(() => {
      this.getCacheSize()
    })
  }

  getCacheSize() {
    // 获取缓存数据
    storageStatistics.getCurrentBundleStats((err: BusinessError, bundleStats: storageStatistics.BundleStats) => {
      if (err) {
        console.error(`Invoke getCurrentBundleStats failed, code is ${err.code}, message is ${err.message}`);
      } else {
        this.cacheSize = bundleStats.cacheSize / 1024.00 / 1024.00;
      }
    });
  }

  async addLoginStatusObserver(){
    this.preferences = await SPHelper.default.getPreferences();
    let observer = (key: string) => {
      if(key == SpConstants.USER_ID){
        this.getSettingPageData()
      }
    }
    this.preferences.on('change', observer);
  }

  calcHeight(value:number): number{
    return value * this.percent
  }
}

function trackButtonClick(buttonName: string){
  TrackingButton.click(buttonName, TrackConstants.PageName.Setting, TrackConstants.PageName.Setting)
}