import { LitheRefresh, RefreshController } from "@abner/lithe_refresh";
import { AxiosError } from "@ohos/axios";
import { JSONUtil, ToastUtil } from "@pura/harmony-utils";
import AppConstants from "../../app/AppConstant"
import { MainMessageBean } from "../../model/resultModel/MessageResultModel";
import { getMessageList, readMessage, saveAppOperationLog } from "../../request/Api";
import { StringUtils } from "../../util/StringUtils";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import { cardRoundBorderGreyStyle } from "../../style/BorderStyle";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { HMRouterMgr } from "@hadss/hmrouter";
import { H5OperationType, WebAppPageParam } from "../../model/uiModel/WebAppPageParam";


/**
 * 主页组件
 */
@Preview({
  title: 'ContentTable'
})
@Component
export struct MessageListFragment {
  @State type: number = 0;
  @State msgListData: Array<MainMessageBean> = []
  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)
  }

  getMsgList() {
    getMessageList(this.type, this.pageNum, 30)
      .then((res) => {
        console.log("get 消息列表成功", JSONUtil.beanToJsonStr(res))
        if (res.code == 20041) {
          let data = res.data
          if (data) {
            let items = data.items;
            if (items && items.length > 0) {
              if (this.isRefreshStatus == 1) {
                this.isRefreshStatus = 0
                this.controller.finishRefresh()
                this.msgListData = items;
              }
              if (this.isRefreshStatus == 2) {
                this.isRefreshStatus = 0
                this.controller.finishLoadMore()
                items.forEach((item) => {
                  this.msgListData.push(item)
                })
              }
            } else {
              this.handErrorOrEmPty(0, "暂无新消息！")
            }
          } else {
            this.handErrorOrEmPty(0, "暂无新消息！")
          }
        } else if (res.code == 20040) {
          this.handErrorOrEmPty(0, "暂无新消息！")
        } else {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, ""))
        }
      })
      .catch((err: AxiosError) => {
        console.error("get 消息列表失败", err)
        this.handErrorOrEmPty(-1, err.message)
      })
  }

  /**
   * 错误或空处理
   */
  handErrorOrEmPty(type: number, msg: string) {
    // ToastUtil.showToast(msg)
    if (this.isRefreshStatus == 1) {
      this.isRefreshStatus = 0
      this.controller.finishRefresh()
      this.msgListData = new Array<MainMessageBean>();
      let bean = new MainMessageBean()
      bean.baseType = type;
      bean.msgContent = msg;
      this.msgListData.push(bean)
    }
    if (this.isRefreshStatus == 2) {
      this.isRefreshStatus = 0
      this.controller.finishLoadMore()
    }
  }

  build() {
    Column() {
      LitheRefresh({
        scroller: this.scroller,
        controller: this.controller,
        itemLayout: () => {
          this.listView()
        },
        onRefresh: () => {
          this.controller.closeLoadMore = false;
          this.pageNum = 1;
          this.isRefreshStatus = 1;
          this.getMsgList()
        },
        onLoadMore: () => {
          if (this.pageNum * 30 >= this.total) {
            this.controller.finishLoadMore()
            this.controller.closeLoadMore = true;
            ToastUtil.showToast("没有更多数据!")
            return
          }
          this.pageNum++;
          this.isRefreshStatus = 2;
          this.getMsgList()
        }
      })
        .width(AppConstants.PERCENTAGE_MAX)
        .layoutWeight(1)
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
  }

  @Builder
  listView() {
    List({ scroller: this.scroller, space: 10 }) {
      ForEach(this.msgListData, (item: MainMessageBean) => {
        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.msgContent })
          }
        } else {
          ListItem() {
            this.itemView(item)
          }
          .onClick(() => {
            if (this.type == 0) {
              this.readMsg(item)
            }
            if (item.appExhibition == 0) {
              let pageParam: WebAppPageParam = {
                appName: item.appName,
                appId: item.appId,
                secret: item.appSecret,
                linkUrl: item.appUrl,
                operationType: H5OperationType.readMessage,
                msgId: item.msgId,
                msgType: item.msgType,
              }
              HMRouterMgr.push({ pageUrl: 'WebAppPages', param: pageParam })
              return
            }
            HMRouterMgr.push({ pageUrl: 'MessageDetailsPage', param: 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
    })
  }

  readMsg(item: MainMessageBean) {
    readMessage(item.id)
      .then((res) => {
        console.debug("发送点击：", JSONUtil.beanToJsonStr(res))
        //java.lang.Integer cannot be cast to java.lang.String
        if (res.code == 20041) {
          this.controller.autoRefresh(true)
        }
      })
      .catch((error: AxiosError) => {
        console.error("发送点击：", JSONUtil.beanToJsonStr(error))
      })
  }

  @Builder
  itemView(item: MainMessageBean) {
    Column() {
      Row() {
        Text(item.msgTitle)
          .fontSize($r('app.float.text_size_16'))
          .fontColor($r('app.color.colorGrey8'))
          .textAlign(TextAlign.Start)
          .maxLines(1)
          .ellipsisMode(EllipsisMode.END)
          .layoutWeight(1)

        Image(this.type == 0 ? $r('app.media.icon_not_record') : $r('app.media.icon_record'))
          .width($r('app.float.default_38'))
          .height($r('app.float.default_30'))
          .margin({ left: $r('app.float.default_8') })
      }
      .alignItems(VerticalAlign.Center)
      .height($r('app.float.default_32'))
      .margin({ left: $r('app.float.default_8'), right: $r('app.float.default_8') })
      .width('95%')

      Text(item.msgContent)
        .fontSize($r('app.float.text_size_14'))
        .fontColor($r('app.color.colorGrey6'))
        .textAlign(TextAlign.Start)
        .maxLines(2)
        .ellipsisMode(EllipsisMode.END)
        .width('95%')
        .margin({ top: $r('app.float.default_5'), left: $r('app.float.default_8'), right: $r('app.float.default_8') })

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .margin({ top: $r('app.float.default_10') })
        .backgroundColor($r('app.color.colorGrey2'))

      Row() {
        RelativeContainer() {
          Image(BASE_IMAGE_URL + item.appIcon)
            .width($r('app.float.default_22'))
            .height($r('app.float.default_22'))
            .alignRules({
              middle: { anchor: '__container__', align: HorizontalAlign.Center }, // 水平居中
              center: { anchor: '__container__', align: VerticalAlign.Center }    // 垂直居中
            })
            .border({
              radius: $r('app.float.default_5'),
            })
          Image($r('app.media.ic_unread_doit'))
            .width($r('app.float.default_8'))
            .height($r('app.float.default_8'))
            .visibility(this.type == 0? Visibility.Visible: Visibility.None)
            .margin({ right: $r('app.float.default_2'), top: $r('app.float.default_2') })
            .alignRules({
              middle: { anchor: '__container__', align: HorizontalAlign.End }, // 水平居中
              center: { anchor: '__container__', align: VerticalAlign.Top }    // 垂直居中
            })
        }
        .width($r('app.float.default_22'))
        .height($r('app.float.default_22'))
        Text(item.appName)
          .fontSize($r('app.float.text_size_14'))
          .fontColor($r('app.color.colorGrey8'))
          .layoutWeight(1)
          .margin({ left: $r('app.float.default_8') })

        Text(item.sendingTime)
          .fontSize($r('app.float.text_size_14'))
          .fontColor($r('app.color.colorGrey6'))
          .margin({ left: $r('app.float.default_5') })
      }
      .alignItems(VerticalAlign.Center)
      .height($r('app.float.default_26'))
      .width('95%')
      .margin({ top: $r('app.float.default_5'), left: $r('app.float.default_8'), right: $r('app.float.default_8') })
    }
    .width("95%")
    .height('auto')
    .padding({ top: $r('app.float.default_10'), bottom: $r('app.float.default_10') })
    .backgroundColor($r('app.color.white'))
    .margin({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
    .border(cardRoundBorderGreyStyle)
  }
}