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 { plainToInstance } from 'class-transformer';
import AppConstants from '../../app/AppConstant';
import { FeedBackBean } from '../../model/requestModel/MessageRequestModel';
import { getMyFeedBackList } from '../../request/Api';
import { 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
@Preview
@HMRouter({ pageUrl: 'MyFeedBackPage' })
export struct MyFeedBackPage {
  @State feedBackList: Array<FeedBackBean> = new Array<FeedBackBean>();
  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)
  }

  getData() {
    getMyFeedBackList(this.pageNum)
      .then((res) => {
        console.debug('get My Feedback', 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.feedBackList = items
                this.controller.finishRefresh()
                this.isRefreshStatus = 0
              }
              if (this.isRefreshStatus == 2) {
                this.controller.finishLoadMore()
                this.isRefreshStatus = 0
                items.forEach(item => {
                 let bean = plainToInstance(FeedBackBean,item)

                  this.feedBackList.push(bean)
                })
              }
              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((err: AxiosError) => {
        console.error('get My Feedback', JSON.stringify(err))
        this.handErrorOrEmPty(-1, err.message)

      })
  }

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

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

      LitheRefresh({
        scroller: this.scroller,
        controller: this.controller,
        itemLayout: () => {
          this.listView()
        },
        onRefresh: () => {
          this.controller.closeLoadMore = false;
          this.pageNum = 1;
          this.isRefreshStatus = 1;
          this.getData()
        },
        onLoadMore: () => {
          if (this.pageNum * 20 >= this.total) {
            this.controller.finishLoadMore()
            this.controller.closeLoadMore = true;
            ToastUtil.showToast("没有更多数据!")
            return
          }
          this.pageNum++;
          this.isRefreshStatus = 2;
          this.getData()
        }
      })
        .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.feedBackList, (item: FeedBackBean) => {
        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.content })
          }
        } else {
          ListItem() {
            this.itemUI(item)
          }
          .onClick(()=>{
            HMRouterMgr.push({ navigationId: 'startNavigation', pageUrl: "FeedBackDetailsPage",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
  itemUI(item: FeedBackBean) {
    Column() {
      Column() {
        Text(item.title)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_16'))
          .fontWeight(FontWeight.Bold)
          .width(AppConstants.PERCENTAGE_MAX)
          .textAlign(TextAlign.Start)
          .maxLines(1)
          .height($r('app.float.default_40'))
          .ellipsisMode(EllipsisMode.END)

        Row() {
          Text(this.getTypeStr(item.type))
            .fontColor($r('app.color.colorYellow7'))
            .fontSize($r('app.float.text_size_10'))
            .padding({
              left: $r('app.float.default_5'),
              right: $r('app.float.default_5'),
              top: $r('app.float.default_2'),
              bottom: $r('app.float.default_2')
            })
            .border({
              width: $r('app.float.default_1'),
              color: $r('app.color.colorYellow7'),
              radius: $r('app.float.default_8')
            })
          Text(item.applicationName)
            .fontColor($r('app.color.colorBluen7'))
            .fontSize($r('app.float.text_size_10'))
            .padding({
              left: $r('app.float.default_5'),
              right: $r('app.float.default_5'),
              top: $r('app.float.default_2'),
              bottom: $r('app.float.default_2')
            })
            .border({
              width: $r('app.float.default_1'),
              color: $r('app.color.colorBluen7'),
              radius: $r('app.float.default_8')
            })
            .margin({ left: $r('app.float.default_8') })
            .visibility(StringUtils.isNullOrEmpty(item.applicationName) ? Visibility.None : Visibility.Visible)

          Text(this.getReplyStatusStr(item.replyStatus))
            .fontColor(item.replyStatus == 0 ? $r('app.color.colorGrey6') : $r('app.color.colorGreen6'))
            .fontSize($r('app.float.text_size_10'))
            .padding({
              left: $r('app.float.default_5'),
              right: $r('app.float.default_5'),
              top: $r('app.float.default_2'),
              bottom: $r('app.float.default_2')
            })
            .border({
              width: $r('app.float.default_1'),
              color: item.replyStatus == 0 ? $r('app.color.colorGrey6') : $r('app.color.colorGreen6'),
              radius: $r('app.float.default_8')
            })
            .margin({ left: $r('app.float.default_8') })
        }
        .alignItems(VerticalAlign.Center)
        .justifyContent(FlexAlign.Start)
        .margin({ top: $r('app.float.default_5') })


        Text(item.content)
          .fontColor($r('app.color.colorGrey6'))
          .fontSize($r('app.float.text_size_14'))
          .fontWeight(FontWeight.Bold)
          .width(AppConstants.PERCENTAGE_MAX)
          .textAlign(TextAlign.Start)
          .maxLines(1)
          .height($r('app.float.default_40'))
          .ellipsisMode(EllipsisMode.END)

      }
      .padding($r('app.float.default_10'))
      .width(AppConstants.PERCENTAGE_MAX)
      .height("auto")
      .alignItems(HorizontalAlign.Start)
      .backgroundColor($r('app.color.white'))
      .border(cardRoundBorderStyle)
    }
    .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10'), top: $r('app.float.default_10') })
    .width(AppConstants.PERCENTAGE_MAX)
    .height("auto")
    .alignItems(HorizontalAlign.Start)
  }

  getTypeStr(type: number): string {
    switch (type) {
      case 1:
        return "个人建议";
      case 2:
        return "软件问题";
      case 3:
        return "硬件问题";
      case 4:
      default:
        return "其它";
    }
  }

  getReplyStatusStr(replyStatus: number): string {
    return replyStatus == 0 ? "未回复" : "已回复";
  }
}