import { authStore, themeManager,hdHttp } from '@itcast/basic'
import { router } from '@kit.ArkUI'
import { preferenceStore,DataWebModel, logger,HdResponse } from '@itcast/basic'
import { BasicConstant } from '@itcast/basic'
import { BusinessError } from '@kit.BasicServicesKit';
import { StartBean } from '../models/StartModel'
@Entry
@Component
struct BootPage {
  @StorageProp('topHeight')
  topHeight: number = 0
  @State
  time: number = 3
  timer: number | null = null
  @State
  isFirstRun:boolean=preferenceStore.getItemBooleanT('isFirstRun')
  @State
  isLogin:boolean=preferenceStore.getItemBooleanF('isLogin')
  @State
  photoUrl:ResourceStr=$r('app.media.startIcon')
  @State
  newUrl:string='';
  aboutToAppear(): void {
    themeManager.initThemeSetting()
    themeManager.enableFullScreen()
    authStore.initUser()


    getContext().getApplicationContext().getRunningProcessInformation()
    if(this.isFirstRun)
      {
      }
      else if(this.isLogin)
      {
        this.getPhoto()
      }
  }

  dialog = new CustomDialogController({
    builder: PrivacyDialog(),
    cornerRadius: 4,
  })

  startTick()
  {
    this.timer = setInterval(() => {
      this.time--
      if (this.time <= 0) {

        this.goNextPage();
      }
    }, 1000)
  }
  goNextPage()
  {
    clearInterval(this.timer)
      router.replaceUrl({ url: 'pages/Home' })

  }

  onPageShow(): void {

      if(this.isFirstRun)
      {
        this.dialog.open()
      }
      else if(this.isLogin)
      {
        this.startTick()
      }
      else
      {
        router.replaceUrl({ url: 'pages/LoginPage/LoginPage' })
      }
  }
  onPageHide(): void {

      if(this.isFirstRun)
      {
        this.dialog.close()
      }
  }

  aboutToDisappear(): void {
    clearInterval(this.timer)
  }

  build() {
    RelativeContainer() {
      if(this.isFirstRun)
      {

      }
      else
      {
        if(this.newUrl!='')
        {
          Text( this.time + 's' + ' | 跳过')
            .width(70)
            .height(30)
            .borderRadius(15)
            .textAlign(TextAlign.Center)
            .fontSize(14)
            .backgroundColor('#33000000')
            .fontColor($r('app.color.white'))
            .alignRules({
              right: { anchor: "__container__", align: HorizontalAlign.End }
            })
            .margin({ right: 20, top: this.topHeight + 20 })
            .onClick(()=>{
              this.goNextPage()


            })
          Row()
          {
            Text('点击跳转至详情页')
              .height(70)
              .textAlign(TextAlign.Center)
              .fontSize(21)
              .fontColor($r('app.color.white'))
            Image($r('app.media.gohere'))
              .width(22)
              .margin({left:2})
          }
          .backgroundColor('#80000000')
          .borderRadius(39)
          .border({
            width: 3,
            color: $r('app.color.white')
          })
          .alignRules({
            bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
            middle: { anchor: "__container__", align:HorizontalAlign.Center }
          })
          .margin({bottom:200})
          .padding({right:55,left:55})
          .height(70)
          .onClick(()=>{
            clearInterval(this.timer)
            this.goNextPage()
            try {
              router.pushUrl({
                url: 'pages/WebView/LivebroadcastPages',
                params: { url: this.newUrl ,title:'肝胆相照',type:'live'}
              }, router.RouterMode.Standard);
            } catch (err) {
              console.error(`跳转失败: ${err.code}, ${err.message}`);
            }
          })
        }

      }

    }
    .width('100%')
    .height('100%')
    .backgroundImage(this.photoUrl)
    .backgroundImageSize(ImageSize.FILL)
    .geometryTransition("boot")
    .transition(TransitionEffect.OPACITY)
  }

  getPhoto()
  {
    hdHttp.httpReqSimply<string>(BasicConstant.getStartpage).then(async (res: HdResponse<string>) => {

      logger.info('Response StartBean'+res);
      let json:StartBean = JSON.parse(res+'') as StartBean;
      //
      if(json.code=='1')
      {
        this.photoUrl=BasicConstant.urlHtml+json.data.path
        this.newUrl=json.data.url
        logger.info('Response photoUrl'+this.photoUrl);

      }


    }).catch((err: BusinessError) => {

      console.info(`Response login succeeded: ${err}`);

    })
  }

}

@CustomDialog
struct PrivacyDialog {

  controller: CustomDialogController

  build() {
    Column({ space: 10 }) {
      Text('温馨提示')
        .fontSize(18)
      Text() {
        Span('欢迎使用肝胆相照，在使用本软件前，请认真阅读').fontColor($r('app.color.common_gray_03'))
        Span('《隐私政策》').fontColor('#ff0000').onClick(() => {
          this.controller.close()
          ToWeb(BasicConstant.getyyzc,'《隐私政策》')
        })
        Span('，您同意并接受全部条款后方可使用肝胆相照App。').fontColor($r('app.color.common_gray_03'))
      }
      .fontSize(16)
      Flex({ justifyContent: FlexAlign.SpaceAround }) {
        Button("不同意并退出")
          .onClick(() => {
            if (this.controller != undefined) {
              this.controller.close()
              router.back()
            }
          }).backgroundColor(0xffffff).fontColor($r('app.color.top_title'))
        Button("同意")
          .onClick(() => {
            preferenceStore.setItemBoolean('isFirstRun',false)
            if (this.controller != undefined ) {
              this.controller.close()
              router.replaceUrl({ url: 'pages/Index' })
            }

          }).backgroundColor(0xffffff).fontColor(Color.Black)
      }.margin({ bottom: 10 })
    }
    .justifyContent(FlexAlign.Center)
    .backgroundColor($r('app.color.white'))
    .padding(20)
  }
}

function  ToWeb(u:string,t:string)
{
  let paramsInfo: DataWebModel = {
    url:u ,
    title:t

  };
  router.pushUrl({
    url: 'pages/WebView/WebPage', // 目标url
    params: paramsInfo // 添加params属性，传递自定义参数
  })
}