import { authStore, HdNav , preferenceStore} from '@itcast/basic';
import { bundleManager, common, ConfigurationConstant, Want } from '@kit.AbilityKit';
import { fileIo, storageStatistics } from '@kit.CoreFileKit';
import { promptAction, router } from '@kit.ArkUI';
import call from '@ohos.telephony.call';

@Entry
@Preview
@Component
struct SettingPage {
  @State version: string = ''
  @State cache: string = ''
  @State settingList : Array<string> = [
    '修改登录密码',
    '更换手机号',
    '版本',
    '关于肝胆相照',
    // '分享肝胆相照APP',
    '肝胆相照直播群',
    '清除缓存',
    '意见反馈',
    '注销账户',
    '注册协议',
    '隐私政策',
    '项目办公室电话'
  ];

  aboutToAppear(): void {
    this.getVersion()
    this.calcCache()
  }

  getVersion() {
    bundleManager.getBundleInfoForSelf(
      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION |
      bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA
    )
      .then((res) => {
        this.version = 'v' + res.versionName
      })
  }

  calcCache() {
    storageStatistics.getCurrentBundleStats()
      .then(res => {
        this.cache = (res.cacheSize / (1000 * 1000)).toFixed(2) + 'MB'
      })
  }

  clearCache() {
    const ctx = getContext()
    const ctxCacheDir = ctx.cacheDir
    const ctxExist = fileIo.accessSync(ctxCacheDir)
    if (ctxExist) {
      fileIo.rmdirSync(ctxCacheDir)
    }
    const app = ctx.getApplicationContext()
    const appCacheDir = app.cacheDir
    const appExist = fileIo.accessSync(appCacheDir)
    if (appExist) {
      fileIo.rmdirSync(appCacheDir)
    }
    promptAction.showToast({ message: '清理完毕' })
    this.calcCache()
  }

  build() {
    Column(){
      HdNav({ title: '设置与帮助', showRightIcon: false, hasBorder: true })

      Blank()

      List(){
        ForEach(this.settingList,(item:string,index:number)=>{
          ListItem() {
            Column() {
              Row() {
                Text(item)
                  .fontSize(16)
                  .fontColor('#333333')
                  .margin({ left: 10 })
                Blank()
                if (item=='版本') {
                  Text(this.version)
                    .fontSize(16)
                    .fontColor($r('app.color.main_color'))
                    .margin({ right: 10 })
                } else if (item == '清除缓存') {
                  Text(this.cache)
                    .fontSize(16)
                    .fontColor($r('app.color.main_color'))
                    .margin({ right: 10 })
                  Image($r('sys.media.ohos_ic_public_arrow_right'))
                    .width(15)
                    .height(15)
                    .margin({ right: 10 })
                } else if (item == '项目办公室电话') {
                  Text('010-87573022')
                    .fontSize(16)
                    .fontColor($r('app.color.main_color'))
                    .margin({ right: 10 })
                } else  {
                  Image($r('sys.media.ohos_ic_public_arrow_right'))
                    .width(15)
                    .height(15)
                    .margin({ right: 10 })
                }
              }
              .width('100%')
              .height(52)
              .justifyContent(FlexAlign.SpaceBetween)
              Divider()
                .color('#F4F4F4')
                .strokeWidth(1)
                .height(1)
                .margin({left:10,top:0})
            }
            .justifyContent(FlexAlign.Start)
          }
          .height(53)
          .onClick(()=>{
            if (index == 0) {
              router.pushUrl({url:'pages/MinePage/ChangePassword'})
            } else if (index == 1) {
              router.pushUrl({url:'pages/MinePage/ChangePhonePage'})
            } else if (index == 2) {
              console.info('当前版本：',this.settingList[index]);
            } else if (index == 3) {
              try {
                router.pushUrl({
                  url: 'pages/WebView/WebPage',
                  params: { url: 'http://doc.igandan.com/app/html/about/2017/about2.html' ,title:'关于肝胆相照'}
                }, router.RouterMode.Standard);
              } catch (err) {
                console.error(`跳转失败: ${err.code}, ${err.message}`);
              }
            } else if (index == 4) {
              try {
                router.pushUrl({
                  url: 'pages/WebView/WebPage',
                  params: { url: 'http://wx.igandan.com/qun/gdxzqun' ,title:'肝胆相照直播群'}
                }, router.RouterMode.Standard);
              } catch (err) {
                console.error(`跳转失败: ${err.code}, ${err.message}`);
              }
            } else if (index == 5) {
              this.clearCache();
            } else if (index == 6) {
              router.pushUrl({url:'pages/MinePage/FeedbackPage'})
            } else if (index == 7) {
              router.pushUrl({url:'pages/MinePage/CancelAccount'})
            } else if (index == 8) {
              try {
                router.pushUrl({
                  url: 'pages/WebView/WebPage',
                  params: { url: 'http://app.igandan.com/expert_zcxy.jsp' ,title:'注册协议'}
                }, router.RouterMode.Standard);
              } catch (err) {
                console.error(`跳转失败: ${err.code}, ${err.message}`);
              }
            } else if (index == 9) {
              try {
                router.pushUrl({
                  url: 'pages/WebView/WebPage',
                  params: { url: 'https://doc.igandan.com/app/integral/permission_expert.html' ,title:'隐私政策'}
                }, router.RouterMode.Standard);
              } catch (err) {
                console.error(`跳转失败: ${err.code}, ${err.message}`);
              }
            } else {
              if (call.hasVoiceCapability()) {
                call.makeCall('010-87573022',(err)=>{
                  if (err) {
                    promptAction.showToast({message:'拨号失败'})
                  } else {
                    promptAction.showToast({message:'拨号成功'})
                  }
                })
              } else {
                promptAction.showToast({message:'不支持通话'})
              }
            }
          })
        })
      }
      .height('auto')

      Button({ type: ButtonType.Normal }){
        Text('退出登录')
      }
      .width('90%')
      .height(53)
      .fontSize(16)
      .borderWidth(1)
      .borderRadius(8)
      .fontColor($r('app.color.main_color'))
      .borderColor($r('app.color.main_color'))
      .backgroundColor(Color.White)
      .margin({top:10,left:10,right:10})
      .onClick(()=>{
        authStore.delUser();
        preferenceStore.setItemBoolean('isLogin',false)
        router.back()
        router.replaceUrl({
          url: 'pages/LoginPage/LoginPage', // 目标url
        },router.RouterMode.Single)
      })
    }
  }
}