import { HMRouterMgr } from "@hadss/hmrouter";
import { AxiosError } from "@ohos/axios";
import { JSONUtil, ToastUtil } from "@pura/harmony-utils";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import AppConstants from "../../app/AppConstant";
import { ApplicationModel } from "../../model/resultModel/ApplicationResultModel";
import { H5OperationType, WebAppPageParam } from "../../model/uiModel/WebAppPageParam";
import { getRecommendApplication } from "../../request/Api";
import { cardRoundBorderStyle } from "../../style/BorderStyle";
import { AppUtils } from "../../util/AppUtils";
import { BaseTopBar } from "../custom/BaseTopTar";

/**
 * 主页组件
 */
@Preview({
  title: 'ContentTable'
})
@Component
export struct WorkbenchFragment {
  @State tjyyHeight: Resource = $r('app.float.default_92');
  @State appListData: Array<ApplicationModel> = []



  aboutToAppear(): void {
    setTimeout(() => {
      this.getRecommendApplicationList();
      // this.getLocationApplicationList();
    },800)
  }

  /**
   * 获取本地应用列表   you must specify an option at least.
   */
  getLocationApplicationList() {
    new AppUtils().getAppList()
      .then((res) => {

      })
  }

  /**
   * 获取推荐应用列表
   */
  getRecommendApplicationList() {
    getRecommendApplication()
      .then((res) => {
        console.log("get 推荐应用列表成功", JSONUtil.beanToJsonStr(res))
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            let listData = new Array<ApplicationModel>()
            let tjyy = data.推荐应用;
            if (tjyy) {
              tjyy.forEach((item) => {
                listData.push(item)
              })
            }
            let zxyy = data.最新应用;
            if (zxyy) {
              zxyy.forEach((item) => {
                listData.push(item)
              })
            }
            if (listData.length < 1) {
              let bean = new ApplicationModel()
              bean.baseType = 91
              bean.name = "应用指南"
              bean.locationIcon = $r('app.media.ic_zfjc')
              this.appListData.push(bean)
              let bean1 = new ApplicationModel()
              bean1.baseType = 92
              bean1.name = "常见问题"
              bean1.locationIcon = $r('app.media.ic_zazh')
              this.appListData.push(bean1)
              let bean2 = new ApplicationModel()
              bean2.baseType = 93
              bean2.name = "意见反馈"
              bean2.locationIcon = $r('app.media.ic_zazh')
              this.appListData.push(bean2)
              bean = new ApplicationModel()
              bean.baseType = 99
              bean.name = "更多应用"
              bean.locationIcon = $r('app.media.icon_gd2')
              this.appListData.push(bean)
              return
            }

            if (listData.length >= 8) {
              this.appListData = listData.slice(8)
              let bean = this.appListData[7]
              bean.baseType = 99
              bean.name = "更多应用"
              bean.locationIcon = $r('app.media.icon_gd2')
            }
              this.appListData = listData
            if (this.appListData.length > 4) {
              this.tjyyHeight = $r('app.float.default_150')
            } else {
              this.tjyyHeight = $r('app.float.default_98')
            }
          }
        }
      })
      .catch((err: AxiosError) => {
        console.error("get 推荐应用列表失败", err)
      })
  }

  build() {
    Column(){
      BaseTopBar({
        isBackImag:false,
        title: $r('app.string.title_Workbench')
      })

      Row(){
        Divider()
          .width($r('app.float.default_5'))
          .height($r('app.float.default_14'))
          .backgroundColor($r('app.color.bull'))
          .margin({ left: $r('app.float.default_10') })

        Text("推荐应用")
          .fontSize($r('app.float.text_size_16'))
          .fontColor($r('app.color.bull'))
          .margin({ left: $r('app.float.default_8') })

      }
      .alignItems(VerticalAlign.Center)
      .width(AppConstants.PERCENTAGE_MAX)
      .height($r('app.float.default_40'))

      this.recommendedApplicationUI()


      Row(){
        Divider()
          .width($r('app.float.default_5'))
          .height($r('app.float.default_14'))
          .backgroundColor($r('app.color.bull'))
          .margin({ left: $r('app.float.default_10') })

        Text("自定义应用")
          .fontSize($r('app.float.text_size_16'))
          .fontColor($r('app.color.bull'))
          .margin({ left: $r('app.float.default_8') })

      }
      .alignItems(VerticalAlign.Center)
      .width(AppConstants.PERCENTAGE_MAX)
      .margin({ top: $r('app.float.default_8')})
      .height($r('app.float.default_40'))

      this.locationApp();

    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
  }

  /**
   * 推荐应用区域
   */
  @Builder
  locationApp() {
    Column() {
      Grid() {
        ForEach(this.appListData, (item: ApplicationModel, index) => {
          GridItem() {
            Column() {
              Image(item.baseType == 99 ? item.locationIcon : BASE_IMAGE_URL + item.icon)
                .size({
                  width: $r('app.float.default_36'),
                  height: $r('app.float.default_36')
                })
                .margin({ top: $r('app.float.default_8') });
              Text(item.name)
                .fontSize($r('app.float.text_size_14'))
                .fontColor($r('app.color.colorGrey8'))
                .margin({ top: $r('app.float.default_8') });
            }
            .alignItems(HorizontalAlign.Center);
          };
        });
      }
      .columnsTemplate('1fr 1fr 1fr 1fr') //一行有4列，等分
      .columnsGap($r('app.float.default_10')) //行间距
      .rowsGap($r('app.float.default_10')); //列间距

    }
    .padding($r('app.float.default_10'))
    .margin({ top: $r('app.float.default_10'), right: $r('app.float.default_10'), left: $r('app.float.default_10') })
    .width('95%')
    .height(this.tjyyHeight)
    .backgroundColor($r('app.color.white'))
    .border(cardRoundBorderStyle)
  }

  /**
   * 推荐应用区域
   */
  @Builder
  recommendedApplicationUI() {
    Column() {
      Grid() {
        ForEach(this.appListData, (item: ApplicationModel, index) => {
          GridItem() {
            Column() {
              Image((item.baseType == 99||item.baseType == 91||item.baseType == 92||item.baseType == 93) ? item.locationIcon : BASE_IMAGE_URL + item.icon)
                .size({
                  width: $r('app.float.default_36'),
                  height: $r('app.float.default_36')
                })
                .margin({ top: $r('app.float.default_8') });
              Text(item.name)
                .fontSize($r('app.float.text_size_14'))
                .fontColor($r('app.color.colorGrey8'))
                .margin({ top: $r('app.float.default_8') });
            }
            .alignItems(HorizontalAlign.Center);
          }
          .onClick(() => {
            if (item.baseType == 99) {
              HMRouterMgr.push({pageUrl:'ApplicationWorkbenchPage'})
              return
            }
            if (item.baseType == 91) {
              HMRouterMgr.push({pageUrl:'ApplicationGuidePage'})
              return
            }
            if (item.baseType == 92) {
              HMRouterMgr.push({pageUrl:'FrequentlyQuestionsPage'})
              return
            }
            if (item.baseType == 93) {
              HMRouterMgr.push({pageUrl:'OpinionsSuggestionsPages'})
              return
            }
            let pageParam :WebAppPageParam= {
              appName: item.name,
              appId: item.clientId,
              secret: item.clientSecret,
              linkUrl: item.link,
              operationType:H5OperationType.login,
            }
            HMRouterMgr.push({pageUrl:'WebAppPages',param: pageParam})
          })
        });
      }
      .columnsTemplate('1fr 1fr 1fr 1fr') //一行有4列，等分
      .columnsGap($r('app.float.default_10')) //行间距
      .rowsGap($r('app.float.default_10')); //列间距

    }
    .padding($r('app.float.default_10'))
    .margin({ top: $r('app.float.default_10'), right: $r('app.float.default_10'), left: $r('app.float.default_10') })
    .width('95%')
    .height(this.tjyyHeight)
    .backgroundColor($r('app.color.white'))
    .border(cardRoundBorderStyle)
  }
}