import { LitheRefresh, RefreshController } from "@abner/lithe_refresh";
import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { AxiosError } from "@ohos/axios";
import { ToastUtil } from "@pura/harmony-utils";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import AppConstants from "../../app/AppConstant";
import { RuanseeAbilityStag } from "../../app/RuanseeAbilityStag";
import { AppDataModel } from "../../model/resultModel/ApplicationResultModel";
import { AnHuiAddressModel } from "../../model/uiModel/AnHuiAddressModel";
import { getAppGuideList } from "../../request/Api";
import { cardRoundBorderGreyStyle, cardRoundBorderStyle } from "../../style/BorderStyle";
import { StringUtils } from "../../util/StringUtils";
import { ToastUtils } from "../../util/ToasUtils";
import { BaseTopBar } from "../custom/BaseTopTar";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { createWaterMark } from "../custom/Watermark";

/**
 * 应用指南
 */
@Component
@HMRouter({ pageUrl: 'ApplicationGuidePage' })
export struct ApplicationGuidePage {
  @State inputContent: string | undefined = undefined
  @State cityName: string = "省厅"
  @State appListData: Array<AppDataModel> = []
  cityCode: string = ""
  controller: RefreshController = new RefreshController()
  scroller: Scroller = new Scroller()
  total: number = 0;
  pageNum: number = 1;
  isRefreshStatus: number = 0;
  @State isShowPopup: boolean = false
  @State cityList: Array<Array<string>> = []

  aboutToAppear(): void {
    this.cityCode = RuanseeAbilityStag.userCache.getDepartmentCode + "00000000";
    this.cityName = RuanseeAbilityStag.userCache.getDepartmentName;
    this.cityList = new AnHuiAddressModel().address
    setTimeout(() => {
      this.controller.isAutoRefresh = true;
    }, 800)
  }

  getAppListData() {
    getAppGuideList(StringUtils.get(this.inputContent, ""), this.cityCode, this.pageNum)
      .then((res) => {
        console.debug("getAppGuide", JSON.stringify(res))
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            this.total = data.counts
            let items = data.items;
            if (items) {
              if (this.isRefreshStatus == 1) {
                this.appListData = items
                this.controller.finishRefresh()
                this.isRefreshStatus = 0
              }
              if (this.isRefreshStatus == 2) {
                this.controller.finishLoadMore()
                this.isRefreshStatus = 0
                items.forEach(item => {
                  this.appListData.push(item)
                })
              }
              if (this.pageNum * 20 >= this.total) {
                this.controller.closeLoadMore = true;
              }
            } else {
              this.handErrorOrEmPty(0, "暂无应用")
            }
          } else {
            this.handErrorOrEmPty(0, "暂无应用")
          }
        } else {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, ""))
        }
      })
      .catch((error: AxiosError) => {
        console.error("getAppGuide", JSON.stringify(error))
        this.handErrorOrEmPty(-1, error.message)
      })
  }

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

  @Builder
  selectCity() {
    Column() {
      Grid() {
        ForEach(this.cityList, (item: Array<string>) => {
          GridItem() {
            Column() {
              Text(item[0])
                .fontColor($r('app.color.colorGrey8'))
                .fontSize($r('app.float.text_size_14'))
            }
            .backgroundColor($r('app.color.white'))
            .padding({
              left: $r('app.float.default_10'),
              right: $r('app.float.default_10'),
              top: $r('app.float.default_5'),
              bottom: $r('app.float.default_5')
            })
            .height($r('app.float.default_40'))
            .width(AppConstants.PERCENTAGE_MAX)
            .alignItems(HorizontalAlign.Center)
            .justifyContent(FlexAlign.Center)
            .border(cardRoundBorderGreyStyle)
          }.onClick(() => {
            this.cityCode = item[1]+"00000000";
            this.cityName = item[0];
            this.isShowPopup = false;
            this.controller.isAutoRefresh = true;
          })
        })
      }.width('90%')
      .columnsTemplate('1fr 1fr 1fr')
      .columnsGap(10)
      .rowsGap(10)

    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height($r('app.float.default_350'))
    .padding({
      top: $r('app.float.default_10'),
      right: $r('app.float.default_10')
    })
    .backgroundColor($r('app.color.page_background'))
    .border({
      radius: $r('app.float.default_3'),
    })
  }

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

      Row() {
        TextInput({ text: this.inputContent, placeholder: "请输入应用名称进行搜索" })
          .placeholderColor($r('app.color.colorGrey6'))
          .fontSize($r('app.float.text_size_16'))
          .fontColor($r('app.color.colorGrey8'))
          .margin({
            left: $r('app.float.default_10'),
          })
          .padding({
            left: $r('app.float.default_5'),
            right: $r('app.float.default_5'),
          })
          .onChange((text: string) => {
            this.inputContent = text;
          })
          .height($r('app.float.default_40'))
          .layoutWeight(1)
          .textAlign(TextAlign.Start)
          .border(cardRoundBorderGreyStyle)
          .enterKeyType(EnterKeyType.Search)// 设置为搜索按钮
          .onSubmit((enterKey: EnterKeyType, event: SubmitEvent) => {
            // 点击搜索按钮时触发
            this.controller.isAutoRefresh = true;
          });

        Row() {
          Image($r('app.media.ic_filter'))
            .width($r('app.float.default_14'))
            .height($r('app.float.default_14'))
          Text(this.cityName)
            .fontColor($r('app.color.colorGrey8'))
            .fontSize($r('app.float.text_size_14'))
        }
        .width("auto")
        .alignItems(VerticalAlign.Center)
        .justifyContent(FlexAlign.Center)
        .padding({
          left: $r('app.float.default_8'),
          top: $r('app.float.default_3'),
          right: $r('app.float.default_8'),
          bottom: $r('app.float.default_3')
        })
        .height($r('app.float.default_40'))
        .onClick(() => {
          if (this.isRefreshStatus != 0) {
            return
          }
          this.isShowPopup = true;
        })
        .bindPopup(this.isShowPopup, {
          builder: () => this.selectCity(),
          placement: Placement.Top,
          mask: { color: 0x80000000 },
          maskColor: 0x80000000,
          onStateChange: (v) => {
            this.isShowPopup = v.isVisible;
          },
          onWillDismiss: () => {
            this.isShowPopup = false;
          }
        })

        .border({
          width: $r('app.float.default_1'),
          color: $r('app.color.colorGrey2'),
          radius: $r('app.float.default_8')
        })
        .margin({ left: $r('app.float.default_8') })
      }
      .alignItems(VerticalAlign.Top)
      .padding({
        left: $r('app.float.default_10'),
        top: $r('app.float.default_5'),
        right: $r('app.float.default_10'),
        bottom: $r('app.float.default_5')
      })
      .height('auto')
      .backgroundColor($r('app.color.white'))

      LitheRefresh({
        scroller: this.scroller,
        controller: this.controller,
        itemLayout: () => {
          this.listView()
        },
        onRefresh: () => {
          this.controller.closeLoadMore = false;
          this.pageNum = 1;
          this.isRefreshStatus = 1;
          this.getAppListData()
        },
        onLoadMore: () => {
          if (this.pageNum * 20 >= this.total) {
            this.controller.finishLoadMore()
            this.controller.closeLoadMore = true;
            ToastUtil.showToast("没有更多数据!")
            return
          }
          this.pageNum++;
          this.isRefreshStatus = 2;
          this.getAppListData()
        }
      })
        .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: AppDataModel) => {
        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.remark });
          }
        } else {
          ListItem() {
            this.itemView(item)
          }
          .onClick(() => {
            HMRouterMgr.push({pageUrl:"ApplicationDetailsPage",param:item})
          })
        }
      })
    }
    .listDirection(Axis.Vertical)
    .scrollBar(BarState.Off)
    .edgeEffect(EdgeEffect.None)
    .width(AppConstants.PERCENTAGE_MAX)
    .layoutWeight(1)
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.PARENT_FIRST
    })
  }

  @Builder
  itemView(item: AppDataModel) {
    Column() {
      Column() {
        Row() {
          Image(BASE_IMAGE_URL + item.icon)
            .width($r('app.float.default_46'))
            .height($r('app.float.default_46'))

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

            Text(item.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("查看指南")
            .fontSize($r('app.float.text_size_14'))
            .fontColor($r('app.color.colorGrey7'))
            .layoutWeight(1)
            .ellipsisMode(EllipsisMode.END)

          Image($r('app.media.ic_look'))
            .width($r('app.float.default_26'))
            .height($r('app.float.default_26'))
        }
        .width(AppConstants.PERCENTAGE_MAX)
        .backgroundColor("#F8F9FC")
        .height($r('app.float.default_45'))
        .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
        .margin({ top: $r('app.float.default_10') })
        .border(cardRoundBorderStyle)

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .height("auto")
      .padding($r('app.float.default_10'))
      .backgroundColor($r('app.color.white'))
      .border(cardRoundBorderGreyStyle)

    }
    .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
    .height("auto")
    .width(AppConstants.PERCENTAGE_MAX)
  }
}