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, ApplicationModel } from "../../model/resultModel/ApplicationResultModel";
import { BaseResultModel, PagingModel } from "../../model/resultModel/BaseResultModel";
import { AnHuiAddressModel } from "../../model/uiModel/AnHuiAddressModel";
import { H5OperationType, WebAppPageParam } from "../../model/uiModel/WebAppPageParam";
import { applicationPage } from "../../request/Api";
import { cardRoundBorderGreyStyle, cardRoundBorderStyle } from "../../style/BorderStyle";
import { StringUtils } from "../../util/StringUtils";
import { ToastUtils } from "../../util/ToasUtils";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { createWaterMark } from "../custom/Watermark";

/**
 * 应用工作台页面
 */
@Component
@HMRouter({ pageUrl: 'ApplicationWorkbenchPage' })
export struct ApplicationWorkbenchPage {
  @State selectValue: Array<AppDataModel> = new Array<AppDataModel>();
  @State inputAppName: string = "";
  @State leftImage: Resource = $r('app.media.icon_back3')
  cityCode: string = ""
  @State cityName: string = "省厅"
  @State isShowPopup: boolean = false
  @State cityList: Array<Array<string>> = []
  controller: RefreshController = new RefreshController()
  scroller: Scroller = new Scroller()
  total: number = 0;
  pageNum: number = 1;
  isRefreshStatus: number = 0;
  @State gridColumns: string = '1fr 1fr 1fr 1fr'

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

  getAppListData() {
    applicationPage(this.cityCode, this.pageNum, 50, this.inputAppName)
      .then((res) => {
        console.debug("获取应用列表成功", JSON.stringify(res))
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            this.total = data.counts
            let list = data.items;
            if (list) {
              if (this.isRefreshStatus == 1) {
                this.gridColumns = '1fr 1fr 1fr 1fr'
                this.isRefreshStatus = 0
                this.controller.finishRefresh()
                this.selectValue = new Array<AppDataModel>();
                list.forEach((item) => {
                  this.selectValue.push(item)
                })
              }
              if (this.isRefreshStatus == 2) {
                this.isRefreshStatus = 0
                this.controller.finishLoadMore()
                list.forEach((item) => {
                  this.selectValue.push(item)
                })
              }
            } else {
              this.handErrorOrEmPty(0, "暂无数据")
            }
          } else {
            this.handErrorOrEmPty(0, "暂无数据")
          }
        } else {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, ""))
        }
      })
      .catch((err: AxiosError) => {
        console.debug("获取应用列表成功", JSON.stringify(err))
        this.handErrorOrEmPty(-1, err.message)
      })
  }

  /**
   * 错误或空处理
   */
  handErrorOrEmPty(type: number, msg: string) {
    ToastUtils.toastBottom(msg)
    if (this.isRefreshStatus == 1) {
      this.gridColumns = '1fr'
      this.controller.finishRefresh()
      this.isRefreshStatus = 0
      let bean = new AppDataModel()
      bean.baseType = type;
      bean.remark = msg;
      this.selectValue = new Array<AppDataModel>();
      this.selectValue.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.autoRefresh(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'),
    })
  }

  @Builder
  listView() {
    Grid(this.scroller) {
      ForEach(this.selectValue, (item: AppDataModel, index) => {
        if (item.baseType == 0 || item.baseType == -1) {
          GridItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.remark })
          }
        } else {
          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'))
                .textAlign(TextAlign.Center)
                .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(this.gridColumns) //一行有4列，等分
    .columnsGap($r('app.float.default_10')) //行间距
    .rowsGap($r('app.float.default_10')) //列间距
    .scrollBar(BarState.Off)
    .edgeEffect(EdgeEffect.None)
    .width(AppConstants.PERCENTAGE_MAX)
    .layoutWeight(1)
    .padding({ left: 20, right: 20 })
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.PARENT_FIRST
    })

  }

  build() {
    Column() {
      Blank()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_30'))
        .backgroundColor($r('app.color.bull'))
      this.topBar()

      Column(){

        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)
          .height(AppConstants.PERCENTAGE_MAX)
          .width(AppConstants.PERCENTAGE_MAX)
          .backgroundColor($r('app.color.white'))
          .border(cardRoundBorderStyle)
      }
      .padding($r('app.float.default_10'))
      .layoutWeight(1)
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .backgroundColor($r('app.color.page_background'))
    .overlay(createWaterMark())
  }

  @Builder
  topBar() {
    Row() {
      Row() {
        Image(this.leftImage)
          .width($r('app.float.default_24'))
          .height($r('app.float.default_24'))
      }
      .height("100%")
      .width('auto')
      .alignItems(VerticalAlign.Center)
      .padding({ left: $r('app.float.default_10') })
      .onTouch((event) => {
        if (event.type === TouchType.Down) {
          this.leftImage = $r('app.media.icon_back2');
        } else if (event.type === TouchType.Up) {
          this.leftImage = $r('app.media.icon_back3');
        }
      })
      .onClick(() => {
        HMRouterMgr.pop()
      })

      Row() {
        Image($r('app.media.icon_search'))
          .width($r('app.float.default_18'))
          .height($r('app.float.default_18'))

        TextInput({ text: this.inputAppName, placeholder: '请输入应用名称' })
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_14'))
          .height($r('app.float.default_38'))
          .backgroundColor(Color.Transparent)
          .cancelButton({
            style: CancelButtonStyle.INPUT, // 设置清除按钮样式为图标
            icon: {
              src: $r('app.media.icon_clean'), // 自定义图标资源路径
              size: $r('app.float.default_18') // 图标尺寸（单位vp，若省略则默认24vp）
            }
          })
          .layoutWeight(1)
          .textAlign(TextAlign.Start)
          .onChange((value: string) => {
            this.inputAppName = value;
          })
          .enterKeyType(EnterKeyType.Search)// 设置为搜索按钮
          .onSubmit((enterKey: EnterKeyType, event: SubmitEvent) => {
            // 点击搜索按钮时触发
            this.controller.autoRefresh(true)
          });
      }
      .alignItems(VerticalAlign.Center)
      .layoutWeight(1)
      .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .height($r('app.float.default_38'))
      .margin({ left: $r('app.float.default_5') })
      .backgroundColor($r('app.color.white'))
      .border({
        width: $r('app.float.default_1'),
        color: $r('app.color.white'),
        radius: $r('app.float.default_8')
      })

      Row() {
        Image($r('app.media.ic_dropup'))
          .width($r('app.float.default_24'))
          .height($r('app.float.default_24'))

        Text(this.cityName)
          .fontColor($r('app.color.white'))
          .fontSize($r('app.float.text_size_16'))
      }
      .alignItems(VerticalAlign.Center)
      .height("100%")
      .margin({ left: $r('app.float.default_5') })
      .width('auto')
      .padding({ right: $r('app.float.default_10') })
      .bindPopup(this.isShowPopup, {
        builder: () => this.selectCity(),
        placement: Placement.Top,
        mask: { color: 0x80000000 },
        maskColor: 0x80000000,
        onStateChange: (v) => {
          this.isShowPopup = v.isVisible;
        },
        onWillDismiss: () => {
          this.isShowPopup = false;
        }
      })
      .onClick(() => {
        this.isShowPopup = true
      })
    }
    .alignItems(VerticalAlign.Center)
    .width('100%')
    .backgroundColor($r('app.color.bull'))
    .height($r('app.float.default_58'))
  }
}