import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { ToastUtil } from "@pura/harmony-utils/src/main/ets/action/ToastUtil";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import AppConstants from "../../app/AppConstant";
import { AppDataModel, AppGuideDetailsBean } from "../../model/resultModel/ApplicationResultModel";
import { StringUtils } from "../../util/StringUtils";
import { BaseTopBar } from "../custom/BaseTopTar";
import { createWaterMark } from "../custom/Watermark";
import { call } from "@kit.TelephonyKit";
import { StrUtil } from "@pura/harmony-utils/src/main/ets/utils/StrUtil";
import { LitheRefresh, RefreshController } from "@abner/lithe_refresh";
import { downLoadFile, operationGuideList } from "../../request/Api";
import { AxiosError, AxiosResponse } from "@ohos/axios";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { ToastUtils } from "../../util/ToasUtils";
import { plainToInstance } from "class-transformer";
import { cardRoundBorderStyle } from "../../style/BorderStyle";
import { FileUtil } from "@pura/harmony-utils";
import { FileUtils } from "../../util/FileUtils";
import { common } from "@kit.AbilityKit";
import { DialogHelper } from "@pura/harmony-dialog";

@Component
@HMRouter({ pageUrl: "ApplicationDetailsPage" })
export struct ApplicationDetailsPage {
  context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  @State param: AppDataModel | undefined = undefined
  @State appListData: AppGuideDetailsBean[] = []
  controller: RefreshController = new RefreshController()
  scroller: Scroller = new Scroller()
  isRefreshStatus: number = 0;

  aboutToAppear(): void {
    this.param = HMRouterMgr.getCurrentParam() as AppDataModel;
    if (!this.param) {
      ToastUtil.showToast("参数错误!")
      HMRouterMgr.pop()
      return
    }
    setTimeout(() => {
      this.controller.isAutoRefresh = true
    }, 800)
  }

  /**
   * 错误或空处理
   */
  handErrorOrEmPty(type: number, msg: string) {
    ToastUtils.toastBottom(msg)
    if (this.isRefreshStatus == 1) {
      this.controller.finishRefresh()
      this.isRefreshStatus = 0
      let bean = new AppGuideDetailsBean()
      bean.baseType = type;
      bean.remark = msg;
      this.appListData = new Array<AppGuideDetailsBean>();
      this.appListData.push(bean)
    }
  }

  //342401199412220026
  getAppDetails() {
    operationGuideList(this.param!.id)
      .then((res) => {
        this.controller.finishRefresh()
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            this.appListData = new Array<AppGuideDetailsBean>();
            this.isRefreshStatus = 0
            data.forEach((bean) => {
              let item = plainToInstance(AppGuideDetailsBean, bean)
              this.appListData.push(item);
            })
          } else {
            this.handErrorOrEmPty(0, "暂无数据")
          }
        } else {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, ""))
        }
      })
      .catch((err: AxiosError) => {
        this.handErrorOrEmPty(-1, err.message)
      })
  }

  openOrDownLoad(item: AppGuideDetailsBean) {
    if (FileUtil.accessSync(FileUtils.FILE_DIR + "/" + item.getName())) {
      FileUtils.openWithThirdPartyApp(this.context,FileUtils.FILE_DIR + "/" + item.getName());
      return
    }
    //自定义文字内容
    let dialogId = DialogHelper.showLoadingDialog({
      loadColor: Color.White,
      content: "正在下载,请稍后...",
      fontSize: 15,
      backgroundColor: '#ED000000',
      autoCancel: true,
      onWillDismiss: () => {
        DialogHelper.closeDialog(dialogId)
        dialogId = ''
      }
    })
    downLoadFile(BASE_IMAGE_URL+item.filePath, FileUtils.FILE_DIR + "/" + item.getName(), (progressEvent) => {
      console.info("下载进度: ", progressEvent && progressEvent.loaded && progressEvent.total ?
      Math.ceil(progressEvent.loaded / progressEvent.total * 100) +"%" : 0 +"%");
    })
      .then((res:AxiosResponse) => {
        DialogHelper.closeDialog(dialogId)
        if (res.status == 200) {
          this.openOrDownLoad(item)
        } else {
          ToastUtils.toastBottom(`下载失败:${res.status}`)
        }
      })
      .catch((err: AxiosError) => {
        DialogHelper.closeDialog(dialogId)
        ToastUtils.toastBottom(`下载失败:${err.message}`)
      })
  }

  build() {
    Column() {
      BaseTopBar({
        title: $r('app.string.title_guide_details')
      })
      Column() {

        Row() {
          Image(BASE_IMAGE_URL + this.param!.icon)
            .width($r('app.float.default_46'))
            .height($r('app.float.default_46'))

          Column() {
            Text(this.param!.name)
              .fontSize($r('app.float.text_size_16'))
              .fontColor($r('app.color.colorGrey8'))
              .maxLines(1)
              .ellipsisMode(EllipsisMode.END)

            Text(this.param!.serviceProvider)
              .fontSize($r('app.float.text_size_14'))
              .fontColor($r('app.color.colorGrey6'))
              .margin({ top: $r('app.float.default_5') })
              .maxLines(1)
              .ellipsisMode(EllipsisMode.END)
          }
          .alignItems(HorizontalAlign.Start)
          .justifyContent(FlexAlign.Center)
          .layoutWeight(1)
          .margin({ left: $r('app.float.default_8') })
          .height($r('app.float.default_60'))

        }
        .width(AppConstants.PERCENTAGE_MAX)

        Row() {
          Text('运维人员:')
            .fontColor($r('app.color.colorGrey8'))
            .fontSize($r('app.float.text_size_14'))
          Text(StringUtils.get(this.param!.operationPerson, "暂无"))
            .fontColor($r('app.color.colorGrey8'))
            .fontSize($r('app.float.text_size_14'))

          Blank()
            .layoutWeight(1)
          Text('联系电话:')
            .fontColor($r('app.color.colorGrey8'))
            .fontSize($r('app.float.text_size_14'))
          Text(StringUtils.get(this.param!.phoneNumber, "暂无"))
            .fontColor($r('app.color.bull'))
            .fontSize($r('app.float.text_size_14'))
            .decoration({
              type: TextDecorationType.Underline,
              color: Color.Blue,
              style: TextDecorationStyle.SOLID
            })
            .onClick(() => {
              if (StrUtil.isNotEmpty(this.param!.phoneNumber)) {
                this.callPhone((StringUtils.get(this.param!.phoneNumber, "暂无")))
              }
            })
        }
        .width(AppConstants.PERCENTAGE_MAX)
        .margin({ top: $r('app.float.default_10') })

        Divider()
          .color($r('app.color.colorGrey2'))
          .backgroundColor($r('app.color.colorGrey2'))
          .margin({ top: $r('app.float.default_10') })

        Text("应用介绍：")
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))
          .margin({ top: $r('app.float.default_10') })
          .textAlign(TextAlign.Start)
          .width(AppConstants.PERCENTAGE_MAX)

        Text(StringUtils.get(this.param!.remark, "暂无"))
          .fontColor($r('app.color.colorGrey6'))
          .fontSize($r('app.float.text_size_14'))
          .margin({ top: $r('app.float.default_10') })
          .textAlign(TextAlign.Start)
          .width(AppConstants.PERCENTAGE_MAX)
          .margin({ top: $r('app.float.default_10') })

      }
      .padding({
        top: $r('app.float.default_10'),
        bottom: $r('app.float.default_10'),
        left: $r('app.float.default_10'),
        right: $r('app.float.default_10')
      })
      .width(AppConstants.PERCENTAGE_MAX)
      .backgroundColor($r('app.color.white'))

      LitheRefresh({
        scroller: this.scroller,
        controller: this.controller,
        enableLoadMore: false,
        itemLayout: () => {
          this.listView()
        },
        onRefresh: () => {
          this.isRefreshStatus = 1;
          this.getAppDetails()
        }
      })
        .width(AppConstants.PERCENTAGE_MAX)
        .layoutWeight(1)

    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .overlay(createWaterMark())
    .backgroundColor($r('app.color.page_background'))
  }

  @Builder
  listView() {
    List({ scroller: this.scroller, space: 10 }) {
      ForEach(this.appListData, (item: AppGuideDetailsBean) => {
        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.remark });
          }
        } else {
          ListItem() {
            this.itemView(item)
          }
          .onClick(() => {
            this.openOrDownLoad(item)
          })
        }
      })
    }
    .listDirection(Axis.Horizontal)
    .scrollBar(BarState.Off)
    .edgeEffect(EdgeEffect.None)
    .width(AppConstants.PERCENTAGE_MAX)
    .layoutWeight(1)
    .margin({ top: $r('app.float.default_10'), bottom: $r('app.float.default_20') })
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.PARENT_FIRST
    })
  }

  @Builder
  itemView(item: AppGuideDetailsBean) {
    if (item.type == 1) {
      Column() {
        Image(BASE_IMAGE_URL + item.filePath)
          .width($r('app.float.default_110'))
          .height($r('app.float.default_180'))

        Text(item.getName())
          .textAlign(TextAlign.Center)
          .fontColor($r('app.color.colorBluen7'))
          .width($r('app.float.default_110'))
          .fontSize($r('app.float.text_size_14'))
          .margin({ top: $r('app.float.default_10') })

      }
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
      .width($r('app.float.default_160'))
      .margin({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .padding($r('app.float.default_10'))
      .height(AppConstants.PERCENTAGE_MAX)
      .backgroundColor($r('app.color.white'))
      .border(cardRoundBorderStyle)
    } else if (item.type == 2) {
      Column() {
        Video({
          src: BASE_IMAGE_URL + item.filePath,
          previewUri: BASE_IMAGE_URL + item.filePath
        })
          .width($r('app.float.default_110'))
          .height($r('app.float.default_180'))

        Text(item.getName())
          .textAlign(TextAlign.Center)
          .fontColor($r('app.color.colorBluen7'))
          .fontSize($r('app.float.text_size_14'))
          .width($r('app.float.default_110'))
          .margin({ top: $r('app.float.default_10') })
      }
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
      .width($r('app.float.default_160'))
      .margin({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .padding($r('app.float.default_10'))
      .layoutWeight(1)
      .backgroundColor($r('app.color.white'))
      .border(cardRoundBorderStyle)
    } else {
      Column() {
        Image(item.getFileIcon(item.filePath))
          .width($r('app.float.default_110'))
          .height($r('app.float.default_180'))

        Text(item.getName())
          .textAlign(TextAlign.Center)
          .fontColor($r('app.color.colorBluen7'))
          .fontSize($r('app.float.text_size_14'))
          .width($r('app.float.default_110'))
          .margin({ top: $r('app.float.default_10') })

      }
      .alignItems(HorizontalAlign.Center)
      .justifyContent(FlexAlign.Center)
      .width($r('app.float.default_160'))
      .margin({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .padding($r('app.float.default_10'))
      .layoutWeight(1)
      .backgroundColor($r('app.color.white'))
      .border(cardRoundBorderStyle)
    }
  }

  callPhone(phone: string) {
    if (!call.hasVoiceCapability()) {
      console.error('设备不支持拨号功能');
      return;
    }

    call.makeCall("tel:" + phone, (err: Error) => {
      if (err) {
        console.error(`跳转失败：${err.message}`);
      }
    });

  }
}

