import { BusinessError, request } from '@kit.BasicServicesKit';
import { AppUtil, FileUtil, PasteboardUtil } from '@pura/harmony-utils';
import { ToastUtils } from '../utils/ToastUtils';
import { SaveUtils } from '../utils/SaveUtils';
import { LoginManager } from '../manager/LoginGlobalManager';
import { Want } from '@kit.AbilityKit';
import { WXApi } from '../utils/wechat/WXApiEventHandlerImpl';
import { Constants } from '../common/Constants';

@CustomDialog
export struct JoinWxGroupCourseDialog {
  controller: CustomDialogController;

  swiperController: SwiperController = new SwiperController()

  isPlayback: boolean = true

  images: Array<Resource> = [
    $r('app.media.ic_join_wx_group_tip1'),
    $r('app.media.ic_join_wx_group_tip2'),
    $r("app.media.ic_join_wx_group_tip3"),
    $r("app.media.ic_join_wx_group_tip4"),
    $r("app.media.ic_join_wx_group_tip5"),
  ];

  steps: Array<string> = ['第一步', '第二步', '第三步', '第四步', '第五步']

  qrCodePath = 'https://cdn.batiao8.com/kct/mp/scmf_qrcode.png'

  @State currentIndex: number = 0

  downloadImage() {
    try {
      const cachePath = FileUtil.getCacheDirPath() + FileUtil.separator + 'scmf_wx_group_qrcode.jpg';
      if (FileUtil.accessSync(cachePath)) {
        FileUtil.unlink(cachePath)
      }
      request.downloadFile(AppUtil.getContext(), {
        url: this.qrCodePath,
        filePath: cachePath
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          console.info('download complete');
          SaveUtils.saveImageVideoToAlbumDialog([cachePath], false)
            .then((saved) => {
              if (saved) {
                PasteboardUtil.setDataTextSync(`${LoginManager.getUserInfo()!!.user_id}|${Constants.APP_ID}`)
                ToastUtils.show('ID复制成功')
                this.jumpToWxScan()
                this.controller.close()
              } else {
                ToastUtils.show('二维码保存失败')
              }
            })
            .catch(() => {
              ToastUtils.show('二维码保存失败')
            })
        })
      }).catch((err: BusinessError) => {
        ToastUtils.show('二维码下载失败')
      });
    } catch (error) {
      ToastUtils.show('二维码下载失败')
    }
  }

  async jumpToWxScan() {
    let intent: Want = {
      action: 'ohos.want.action.viewData',
      uri: 'weixin://dl/scan' // 微信扫一扫的固定协议
    };
    try {
      await AppUtil.getContext().startAbility(intent);
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(err.message)
    }
  }

  build() {
    RelativeContainer() {
      Image($r('app.media.ic_join_wx_group_tip_bg')).width('100%').height(320)

      Text(this.isPlayback ? '添加直播回放助手流程' : '添加视频助手流程')
        .width('auto')
        .fontColor($r('app.color.color_1a1a1a'))
        .fontSize(16)
        .fontWeight(FontWeight.Medium)
        .margin({ top: 16 })
        .alignRules({
          left: { anchor: '__container__', align: HorizontalAlign.Start },
          right: { anchor: '__container__', align: HorizontalAlign.End }
        })
        .id('tv_title')

      List({space: 16}) {
        ForEach(this.steps, (item: string, index) => {
          ListItem() {
            Stack() {
              if (index === this.currentIndex) {
                Image($r('app.media.ic_join_wx_group_tip_indicator')).width(44).height(10)
                  .margin({top: 10, left: 5})
              }
              Text(item)
                .fontColor(index === this.currentIndex ? $r('app.color.color_466afd') : '#858D9F')
                .fontSize(index === this.currentIndex ? 16 : 14)
                .fontWeight(index === this.currentIndex ? FontWeight.Medium : FontWeight.Normal)
                .fontFamily(index === this.currentIndex ? 'almmsht' : '')
            }
          }
          .onClick(() => {
            this.swiperController.changeIndex(index, true)
          })
        })
      }
      .width('100%')
      .height(24)
      .listDirection(Axis.Horizontal)
      .alignListItem(ListItemAlign.Center)
      .alignRules({
        top: {anchor: 'tv_title', align: VerticalAlign.Bottom}
      })
      .margin({top: 20})
      .padding({left: 16, right: 16})
      .id('li_step')

      Swiper(this.swiperController) {
        ForEach(this.images, (item: Resource) => {
          Image(item).width('100%').aspectRatio(2.04).margin({ left: 16, right: 16 })
            .borderRadius(20)
        })
      }
      .indicator(false)
      .loop(true)
      .autoPlay(true)
      .interval(2000)
      .onChange((number) => {
        this.currentIndex = number
      })
      .alignRules({
        top: {anchor: 'li_step', align: VerticalAlign.Bottom}
      })
      .margin({top: 24})
      .id('swiper')

      Row() {
        Button('取消', { type: ButtonType.Capsule, stateEffect: false })
          .fontColor($r('app.color.color_1a1a1a'))
          .fontSize(15)
          .backgroundColor($r('app.color.color_eeeeee'))
          .width(126)
          .height(46)
          .onClick(() => {
            this.controller.close()
          })
        Blank().width(9)
        Button('前往微信扫码加群', { type: ButtonType.Capsule, stateEffect: false })
          .fontColor(Color.White)
          .fontSize(15)
          .backgroundColor($r('app.color.color_466afd'))
          .layoutWeight(1)
          .height(46)
          .onClick(() => {
            if (!WXApi.isWXAppInstalled()) {
              ToastUtils.show('未安装微信客户端，请先下载安装微信客户端');
              return;
            }
            this.downloadImage()
          })
      }
      .backgroundColor(Color.White)
      .alignRules({
        top: {anchor: 'swiper', align: VerticalAlign.Bottom}
      })
      .margin({top: 28})
      .padding({left: 16, top: 9, right: 16, bottom: 30})
    }
    .width('100%')
    .height('auto')
    .borderRadius(20)
    .backgroundColor($r('app.color.window_background'))
  }
}