import { promptAction } from '@kit.ArkUI';
import { fileIo, storageStatistics } from '@kit.CoreFileKit';
import { TipsDialog } from '@ohos/common/src/main/ets/dialog/TipsDialog';
import { TitleBarComponent } from '../view/TitleBarComponent';
import { common, contextConstant } from '@kit.AbilityKit';
import { routerLogin } from '@ohos/common/src/main/ets/router/RouterManager';
import { USER_PROFILE } from '@ohos/common/src/main/ets/constants/AppConstants';
import { UserProfile } from '@ohos/common/src/main/ets/viewmodel/DataBean';
import { emitter } from '@kit.BasicServicesKit';
import { EVT_USER_INFO } from '@ohos/common/src/main/ets/constants/EventConstants';
import { ToastUtils } from '@ohos/common/src/main/ets/dialog/ToastUtils';
import { MainService } from '../viewmodel/MainService';

@Builder
export function SettingBuilder() {
  SettingLayout()
}

/**
 * 设置页面
 */
@Component
export struct SettingLayout {
  @StorageProp('statusBarHeight') statusBarHeight: number = 0;
  @Consume('pageInfos') pageStack: NavPathStack;
  @State appCacheSize: string = '';
  @State isLogin: boolean = false;

  dialogController: CustomDialogController = new CustomDialogController({
    builder: TipsDialog({
      title: '清除缓存',
      content: '清除缓存后可能会丢失聊天数据',
      cancel: () => { console.info('用户点击取消') },
      confirm: () => {
        clearAllCache(getContext(this) as common.UIAbilityContext).then(value => {
          if(value){
            getAppCacheSize().then(v => this.appCacheSize = v);
            ToastUtils.normalToast({
              message: '清除缓存成功',    // 提示文字
              duration: 2000,           // 显示时长 (ms)，默认 1500
              bottom: '50%'
            });
          }else{
            ToastUtils.normalToast({
              message: '清除缓存失败',    // 提示文字
              duration: 2000,           // 显示时长 (ms)，默认 1500
              bottom: '50%'
            });
          }
        })

      }
    }),
    alignment: DialogAlignment.Center, // 居中显示
    customStyle: true, // 使用自定义样式，去掉系统默认背景
    autoCancel: true // 点击遮罩层可关闭
  })

  aboutToAppear() {
    getAppCacheSize().then(v => this.appCacheSize = v);
    this.isLogin = !AppStorage.get<UserProfile>(USER_PROFILE)?.temp;

    // 事件监听
    emitter.on({ eventId: EVT_USER_INFO }, (eventData: emitter.EventData) => {
      const payload = eventData.data;
      if (payload) {
        const result = payload["result"] as boolean;
        if (result === true) {
          //记得一定要延迟更新，否则接口未请求完成
          setTimeout(() => {
            this.isLogin = !AppStorage.get<UserProfile>(USER_PROFILE)?.temp;
          }, 1000);
        }
      }
    });
  }

  build() {
    NavDestination() {
      Stack() {
        Scroll(){
          Column() {
            //标题栏
            TitleBarComponent({titleName:'设置', isShowTitle:true, isShowBack:true})

            // 内容区
            Column(){
              Column() {
                Row() {
                  Text('清除缓存')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)


                  Row(){
                    Text(this.appCacheSize)
                      .fontSize(14)
                      .fontColor('#4d767676')
                      .textAlign(TextAlign.Center)
                      .borderRadius(12)
                    Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                  }
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  // 弹出确认窗
                  this.dialogController.open()
                })

                Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

                Row() {
                  Text('账号绑定')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)

                  Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  this.pageStack.pushPathByName("AccountBindLayout", null);
                })

                Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

                Row() {
                  Text('账号管理')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)

                  Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  this.pageStack.pushPathByName("AccountManagerLayout", null);
                })

                Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

                Row() {
                  Text('关于我们')
                    .fontSize(16)
                    .fontColor('#FF1A1A1A')
                    .textAlign(TextAlign.Start)
                    .borderRadius(12)
                    .fontWeight(1)
                    .align(Alignment.Center)
                    .layoutWeight(1)

                  Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                }
                .width('100%')
                .height('52vp')
                .padding({ left: 14})
                .onClick(() => {
                  this.pageStack.pushPathByName("AboutUsLayout", null);
                })

                if(this.isLogin){
                  Divider().height(0.5).backgroundColor('#4dd8d8d8').margin({ left: 14, right: 14})

                  Row() {
                    Text('注销账号')
                      .fontSize(16)
                      .fontColor('#FF1A1A1A')
                      .textAlign(TextAlign.Start)
                      .borderRadius(12)
                      .fontWeight(1)
                      .align(Alignment.Center)
                      .layoutWeight(1)

                    Image($r('app.media.ic_mine_arrow_right')).width('14vp').height('14vp').margin({ left: 8, right: 14})
                  }
                  .width('100%')
                  .height('52vp')
                  .padding({ left: 14})
                  .onClick(() => {
                    // 注销账号
                    this.pageStack.pushPathByName("DeleteAccountLayout", null);
                  })
                }

              }
              .backgroundColor(Color.White)
              .width('100%')
              .borderRadius(12)
              .margin({ top: 30})
            }
            .padding({ left: 16, right: 16})

          }
          .width('100%')
          .height('100%')
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)
        //底部按钮
        Stack() {
          if(this.isLogin){
            Column(){
              Button('账号切换')
                .width('100%')
                .height(48)
                .fontSize(16)
                .fontColor('#FF1A1A1A')
                .backgroundColor('#FFFFFF')
                .borderColor('#FF1A1A1A')
                .borderWidth(0.5)
                .borderRadius(359)
                .margin({ bottom: 16 })
                .onClick(() => {
                  this.pageStack.pushPathByName("AccountManagerLayout", null);
                })
              Button('退出登录')
                .width('100%')
                .height(48)
                .fontSize(16)
                .fontColor('#FFC2FF43')
                .backgroundColor('#FF252525')
                .borderRadius(359)
                .onClick(() => {
                  // 退出登录

                  MainService.logout({
                    onSuccess: (_) => {
                      routerLogin('logout',true)
                    },
                    onFailure:(_) =>{
                      ToastUtils.normalToast({ message: '退出失败啦~' });
                    }
                  })
                })
            }
          }
        }
        .margin({ left: 16, right: 16, bottom: 32 })
      }
      .width('100%')
      .height('100%')
      .alignContent(Alignment.Bottom)
      .backgroundColor('#FFF9F9F9')
    }
    .hideTitleBar(true)
  }
}

/**
 * 获取当前应用的缓存大小
 * @returns 格式化后的字符串 (如 "12.50 MB")
 */
async function getAppCacheSize(): Promise<string> {
  try {
    // 获取当前应用的存储状态（包括数据大小、缓存大小等）
    let bundleStats = await storageStatistics.getCurrentBundleStats();
    let cacheSizeByte = bundleStats.cacheSize; // 单位是 Byte (字节)

    // 转换为 MB 并保留两位小数
    let cacheSizeMB = (cacheSizeByte / (1024 * 1024)).toFixed(2);
    return `${cacheSizeMB} MB`;
  } catch (err) {
    let error: BusinessError = err as BusinessError;
    console.error('获取缓存失败: ' + JSON.stringify(error));
    return '0.00 MB';
  }
}

/**
 * 彻底清理所有区域的缓存目录
 */
async function clearAllCache(context: common.UIAbilityContext): Promise<boolean> {
  context.getApplicationContext().area = contextConstant.AreaMode.EL1;
  context.area = contextConstant.AreaMode.EL1;
  const el1AppCacheDir = context.getApplicationContext().cacheDir
  const el1HapCacheDir = context.cacheDir
  context.getApplicationContext().area = contextConstant.AreaMode.EL2;
  context.area = contextConstant.AreaMode.EL2;
  const el2AppCacheDir = context.getApplicationContext().cacheDir
  const el2HapCacheDir = context.cacheDir

  const clearTask = [
    clearCacheTask(el1AppCacheDir),
    clearCacheTask(el1HapCacheDir),
    clearCacheTask(el2AppCacheDir),
    clearCacheTask(el2HapCacheDir)
  ]

  await Promise.all(clearTask)
  return true
}
// 清除缓存任务
function  clearCacheTask(dir: string): Promise<boolean> {
  return new Promise((resolve) => {
    fileIo.access(dir).then((exist: boolean) => {
      if (exist) {
        fileIo.rmdir(dir)
      }
      resolve(true)
    })
  })
}