import { LitheRefresh, RefreshController } from "@abner/lithe_refresh";
import { HMRouter, HMRouterMgr } from "@hadss/hmrouter";
import { AxiosError } from "@ohos/axios";
import {  ObjectUtil, ToastUtil } from "@pura/harmony-utils";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import AppConstants from "../../app/AppConstant";
import { QuestionBean, QuestionModel } from "../../model/resultModel/QuestionModel";
import { BasePageResult } from "../../model/uiModel/PageResultModel";
import { getQuestion } from "../../request/Api";
import { StringUtils } from "../../util/StringUtils";
import { BaseTopBar } from "../custom/BaseTopTar";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { createWaterMark } from "../custom/Watermark";
/**
 * 常见问题
 */
@Component
@HMRouter({ pageUrl: 'FrequentlyQuestionsPage' })
export struct FrequentlyQuestionsPage {
  @State dataList: Array<QuestionBean> = []
  controller: RefreshController = new RefreshController()
  scroller: Scroller = new Scroller()
  isRefreshStatus: number = 0;
  @State isShowBottomSheet:Array< boolean> = [];

  aboutToAppear(): void {
    setTimeout(() => {
      this.controller.autoRefresh(true)
    }, 500)
  }

  getDataList() {
    getQuestion()
      .then((res) => {
        this.controller.finishRefresh()
        this.isRefreshStatus = 0;
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            // let beanJG = new QuestionBean()
            // beanJG.baseType = 4;
            this.dataList = new Array()
            this.isShowBottomSheet = new Array<boolean>();
            data.forEach((item: QuestionModel) => {
              let bean = new QuestionBean()
              bean.baseType = 1;
              bean.problem = item.title
              this.dataList.push(bean)
              this.isShowBottomSheet.push(false)
              let beans = item.data;
              if (beans) {
                beans.forEach((item: QuestionBean) => {
                  let bean = ObjectUtil.objToClass(QuestionBean, item)
                  // let bean = plainToInstance(QuestionBean, item);
                  this.isShowBottomSheet.push(false)
                  bean.baseType = 2;
                  this.dataList.push(bean)
                })
                this.dataList[this.dataList.length-1].baseType = 3
              }
            })
            if (this.dataList.length < 1) {
              this.handErrorOrEmPty(0, "暂无常见问题！")
            }
          } else {
            this.handErrorOrEmPty(0, "暂无常见问题！")
          }
        } else {
          this.handErrorOrEmPty(-1, StringUtils.get(res.msg, res.code + ""))
        }
      })
      .catch((err: AxiosError) => {
        this.handErrorOrEmPty(-1, StringUtils.get(err.message, ""))
      })
  }

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

  @Builder
  bottomSheet(item: QuestionBean) {
    Column() {
      Text($r('app.string.title_frequently_questions'))
        .fontColor($r('app.color.bull'))
        .fontSize($r('app.float.text_size_16'))
        .width(AppConstants.PERCENTAGE_MAX)
        .fontWeight(FontWeight.Bold)
        .height($r('app.float.default_48'))
        .textAlign(TextAlign.Center)
        .align(Alignment.Center)

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey1'))

      Scroll(){
        Column() {
          Text(item.problem)
            .fontColor($r('app.color.colorBluen7'))
            .fontSize($r('app.float.text_size_16'))
            .width(AppConstants.PERCENTAGE_MAX)
            .height($r('app.float.default_38'))
            .textAlign(TextAlign.Start)
            .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
            .backgroundColor($r('app.color.white'))

          Divider()
            .width(AppConstants.PERCENTAGE_MAX)
            .height($r('app.float.default_1'))
            .backgroundColor($r('app.color.colorGrey1'))

          Text(StringUtils.get("\t\t"+item.reply.replace("\\n","\n").replace("\\t","\t"),"暂无"))
            .fontColor($r('app.color.colorGrey8'))
            .fontSize($r('app.float.text_size_14'))
            .width(AppConstants.PERCENTAGE_MAX)
            .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
            .height("auto")
            .margin({top: $r('app.float.default_10'),bottom: $r('app.float.default_10')})

          Divider()
            .width(AppConstants.PERCENTAGE_MAX)
            .height($r('app.float.default_1'))
            .backgroundColor($r('app.color.colorGrey1'))

          Text(item.extend)
            .fontColor($r('app.color.colorGrey6'))
            .fontSize($r('app.float.text_size_12'))
            .width(AppConstants.PERCENTAGE_MAX)
            .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
            .visibility(StringUtils.isNullOrEmpty(item.guidance)?Visibility.None:Visibility.Visible)
            .textAlign(TextAlign.Start)
            .margin({top: $r('app.float.default_10'),bottom: $r('app.float.default_10')})

          Image(BASE_IMAGE_URL+item.guidance)
            .width(AppConstants.PERCENTAGE_MAX)
            .visibility(StringUtils.isNullOrEmpty(item.guidance)?Visibility.None:Visibility.Visible)
            .height($r('app.float.default_240'))
        }
        .width(AppConstants.PERCENTAGE_MAX)
        .height(AppConstants.PERCENTAGE_MAX)
        .padding({bottom: $r('app.float.default_10')})

      }
      .width(AppConstants.PERCENTAGE_MAX)
      .layoutWeight(1)

    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .backgroundColor($r('app.color.white'))
    .border({
      radius: {
        topLeft: $r('app.float.default_10'),
        topRight: $r('app.float.default_10')
      }
    })
  }

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

      LitheRefresh({
        scroller: this.scroller,
        controller: this.controller,
        enableLoadMore: false,
        itemLayout: () => {
          this.listView()
        },
        onRefresh: () => {
          this.controller.closeLoadMore = false;
          this.isRefreshStatus = 1;
          this.getDataList()
        }
      })
        .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 }) {
      ForEach(this.dataList, (item: QuestionBean,index:number) => {

        if (item.baseType == 0 || item.baseType == -1) {
          ListItem() {
            EmptyOrErrorItemView({ type: item.baseType, msg: item.problem })
          }
        } else if (item.baseType == 1) {
          ListItem() {
            this.itemViewTop(item)
          }
        } else if (item.baseType == 2) {
          ListItem() {
            this.itemViewCenter(item)
          }
          .bindSheet(this.isShowBottomSheet[index], this.bottomSheet(item), {
            height:'66.6%',
            dragBar: true,
            // detents:[$r('app.float.default_3')],
            preferType: SheetType.BOTTOM,
            showClose:false,
            shouldDismiss: () => {
              this.isShowBottomSheet[index] = false;
            }
          })
          .onClick(() => {
            this.isShowBottomSheet[index] = true;
          })
        } else if (item.baseType == 3) {
          ListItem() {
            this.itemViewBottom(item)
          }
          .bindSheet(this.isShowBottomSheet[index], this.bottomSheet(item), {
            height:'66.6%',
            dragBar: true,
            showClose:false,
            preferType: SheetType.BOTTOM,
            shouldDismiss: () => {
              this.isShowBottomSheet[index] = false;
            }
          })
          .onClick(() => {
            this.isShowBottomSheet[index] = true;
          })
        }
      })
    }
    .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
  itemViewTop(item: QuestionBean) {
    Row() {
      Text(item.problem)
        .fontColor($r('app.color.white'))
        .fontSize($r('app.float.text_size_14'))
        .width(AppConstants.PERCENTAGE_MAX)
        .height(AppConstants.PERCENTAGE_MAX)
        .textAlign(TextAlign.Start)
        .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
        .backgroundColor($r('app.color.bull'))
        .border({
          radius: {
            topLeft: $r('app.float.default_5'),
            topRight: $r('app.float.default_5')
          }
        })
        .align(Alignment.Center)
    }
    .padding({ top: $r('app.float.default_10'), left: $r('app.float.default_10'), right: $r('app.float.default_10') })
    .width(AppConstants.PERCENTAGE_MAX)
    .height($r('app.float.default_46'))
  }

  @Builder
  itemViewCenter(item: QuestionBean) {
    Column() {
      Row() {
        Text(item.problem)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_14'))
          .height(AppConstants.PERCENTAGE_MAX)
          .layoutWeight(1)
          .textAlign(TextAlign.Start)
          .align(Alignment.Center)

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_20'))
          .height($r('app.float.default_20'))
          .margin({ left: $r('app.float.default_10') })
      }
      .alignItems(VerticalAlign.Center)
      .width(AppConstants.PERCENTAGE_MAX)
      .height($r('app.float.default_46'))
      .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .backgroundColor($r('app.color.white'))

      Divider()
        .width(AppConstants.PERCENTAGE_MAX)
        .height($r('app.float.default_1'))
        .backgroundColor($r('app.color.colorGrey2'))
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height($r('app.float.default_47'))
    .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
  }

  @Builder
  itemViewBottom(item: QuestionBean) {
    Row() {
      Row() {
        Text(item.problem)
          .fontColor($r('app.color.colorGrey8'))
          .fontSize($r('app.float.text_size_14'))
          .height(AppConstants.PERCENTAGE_MAX)
          .layoutWeight(1)
          .textAlign(TextAlign.Start)
          .align(Alignment.Center)

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_20'))
          .height($r('app.float.default_20'))
          .margin({ left: $r('app.float.default_10') })
      }
      .alignItems(VerticalAlign.Center)
      .width(AppConstants.PERCENTAGE_MAX)
      .height(AppConstants.PERCENTAGE_MAX)
      .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .backgroundColor($r('app.color.white'))
      .border({
        radius: {
          bottomLeft: $r('app.float.default_5'),
          bottomRight: $r('app.float.default_5')
        }
      })
    }
    .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
    .width(AppConstants.PERCENTAGE_MAX)
    .height($r('app.float.default_46'))
  }
}