import { AxiosError } from "@ohos/axios";
import {  ToastUtil } from "@pura/harmony-utils";
import AppConstants from "../../app/AppConstant";
import { cardRoundBorderGreyStyle } from "../../style/BorderStyle";
import { StringUtils } from "../../util/StringUtils";
import { ToastUtils } from "../../util/ToasUtils";
import { BaseTopBar } from "../custom/BaseTopTar";
import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { createWaterMark } from "../custom/Watermark";
import { AppDataModel } from "../../model/resultModel/ApplicationResultModel";
import { getAppList } from "../../request/Api";
import { LitheRefresh, RefreshController } from "@abner/lithe_refresh";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { SelectAppItem } from "../view/SelectAppItem";
import { BasePageResult } from "../../model/uiModel/PageResultModel";
import { plainToInstance } from "class-transformer";

/**
 * 选择任务
 */
@Preview
@Component
@HMRouter({ pageUrl: 'SelectAppListPage' })
export struct SelectAppListPage {
  @State inputContent: string | undefined = undefined
  @State selectValue: Array<AppDataModel> = new Array<AppDataModel>();
  private selectItem: AppDataModel | undefined;
  controller: RefreshController = new RefreshController()
  scroller: Scroller = new Scroller()
  total: number = 0;
  pageNum: number = 1;
  isRefreshStatus: number = 0;

  aboutToAppear(): void {
    setTimeout(() => {
      this.controller.isAutoRefresh = true
    }, 800)
  }

  getAppListData() {
    getAppList(StringUtils.get(this.inputContent, ""), this.pageNum)
      .then((res) => {
        console.debug(JSON.stringify(res))
        if (res.code != 20041) {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, ""))
          return
        }
        let data = res.data;
        if (!data) {
          this.handErrorOrEmPty(0, StringUtils.get(res.msg, "暂无应用"))
          return
        }
        this.total = data.counts;
        let dataList = data.items;
        if (!dataList || dataList.length < 1) {
          this.handErrorOrEmPty(0, StringUtils.get(res.msg, "暂无应用"))
          return
        }
        if (this.isRefreshStatus == 1) {
          this.controller.finishRefresh()
          this.isRefreshStatus = 0
          this.selectValue = new Array<AppDataModel>();
          dataList.forEach(item => {
            this.selectValue.push(plainToInstance(AppDataModel, item));
          })
        }
        if (this.isRefreshStatus == 2) {
          this.controller.finishLoadMore()
          this.isRefreshStatus = 0
          dataList.forEach(item => {
            this.selectValue.push(item);
          })
        }
        if (this.pageNum * 20 >= this.total) {
          this.controller.closeLoadMore = true
        }
      })
      .catch((e: AxiosError) => {
        this.handErrorOrEmPty(-1, `查询任务失败:${e.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.selectValue = new Array<AppDataModel>();
      this.selectValue.push(bean)
    }
    if (this.isRefreshStatus == 2) {
      this.controller.finishLoadMore()
      this.isRefreshStatus = 0
    }
  }

  submit() {
    if (!this.selectItem) {
      ToastUtil.showLong("请先选择应用")
      return
    }
    let param = new BasePageResult()
    param.type = 1;
    param.data = this.selectItem
    HMRouterMgr.pop({ pageUrl: "OpinionsSuggestionsPages", param: param })
  }

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

      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'),
          right: $r('app.float.default_10'),
          top: $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'))
        .width('96%')
        .textAlign(TextAlign.Start)
        .border(cardRoundBorderGreyStyle)
        .enterKeyType(EnterKeyType.Search)// 设置为搜索按钮
        .onSubmit((enterKey: EnterKeyType, event: SubmitEvent) => {
          // 点击搜索按钮时触发
          this.controller.isAutoRefresh = true;
        });

      // ListView({
      //   data: this.selectValue,
      // })

      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)

      Button("完成", { type: ButtonType.Normal, stateEffect: true })
        .fontSize($r('app.float.text_size_16'))
        .fontColor($r('app.color.white'))
        .backgroundColor($r('app.color.bull'))
        .borderRadius(8)
        .margin({
          left: $r('app.float.default_10'),
          right: $r('app.float.default_10'),
          bottom: $r('app.float.default_28'),
        })
        .onClick(() => {
          this.submit();
        })
        .width('95%');

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

  @Builder
  listView() {
    List({ scroller: this.scroller, space: 10 }) {
      ForEach(this.selectValue, (item: AppDataModel) => {
        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.remark })
          }
        } else {
          ListItem() {
            SelectAppItem({
              item: item,
              onSelect: (item: AppDataModel) => {
                this.selectItem = item;
                this.updateCardDataStatus(item)
              }
            })
          }
        }
      })
    }
    .divider({
      strokeWidth: $r('app.float.default_1'),
      color: $r('app.color.colorGrey2'),
      startMargin: $r('app.float.default_63')
    })
    .listDirection(Axis.Vertical)
    .scrollBar(BarState.Off)
    .edgeEffect(EdgeEffect.None)
    .width(AppConstants.PERCENTAGE_MAX)
    .layoutWeight(1)
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.PARENT_FIRST
    })
  }

  updateCardDataStatus(item: AppDataModel) {
    // 遍历所有项，只将当前选中的项设为true，其他设为false
    this.selectValue.forEach(selectedItem => {
      selectedItem.isSelect = (item.id === selectedItem.id);
    });
  }
}