import { AxiosError, AxiosResponse } from "@ohos/axios";
import { FileUtil, JSONUtil, ToastUtil } from "@pura/harmony-utils";
import { BASE_IMAGE_URL } from "../../app/AppCache";
import AppConstants from "../../app/AppConstant";
import { UserCache } from "../../app/UserCache";
import { ApplicationModel } from "../../model/resultModel/ApplicationResultModel";
import { MainMessageBean } from "../../model/resultModel/MessageResultModel";
import {
  downLoadUserPhoto,
  getMessageList,
  getRecommendApplication,
  readMessage,
  saveAppOperationLog
} from "../../request/Api";
import { cardRoundBorderGreyStyle, cardRoundBorderStyle } from "../../style/BorderStyle";
import { FileUtils } from "../../util/FileUtils";
import { StringUtils } from "../../util/StringUtils";
import { EmptyOrErrorItemView } from "../custom/EmptyOrErrorItemView";
import { RuanseeAbilityStag } from "../../app/RuanseeAbilityStag";
import { fileUri } from "@kit.CoreFileKit";
import { HMRouterMgr } from "@hadss/hmrouter";
import { common } from "@kit.AbilityKit";
import { H5OperationType, WebAppPageParam } from "../../model/uiModel/WebAppPageParam";

/**
 * 主页组件
 */
@Preview({
  title: 'ContentTable'
})
@Component
export struct HomeFragment {
  @State appListData: Array<ApplicationModel> = []
  @State tjyyHeight: Resource = $r('app.float.default_98');
  @State msgListData: Array<MainMessageBean> = []
  @State userPhoto: string | Resource = $r('app.media.icon_police_woman')
  context = getContext(this) as common.UIAbilityContext;
  allMessage?: () => void

  aboutToAppear(): void {
    setTimeout(() => {
      this.getImage()
      this.getRecommendApplicationList()
      this.getMsgList();
    }, 800)
    this.context.eventHub.on("updateUserPhoto", () => {
      this.userPhoto = fileUri.getUriFromPath(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
    })
  }

  aboutToDisappear(): void {
    this.context.eventHub.off("updateUserPhoto")
  }

  getImage() {
    if (FileUtil.accessSync(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)) {
      this.userPhoto = fileUri.getUriFromPath(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
      return
    }
    downLoadUserPhoto(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
      .then((res: AxiosResponse) => {
        console.info("result:" + JSON.stringify(res.data));
        if (res.status == 200) {
          this.userPhoto =
            fileUri.getUriFromPath(FileUtils.IMAGE_DIR + '/' + RuanseeAbilityStag.userCache.getProfilePhoto)
        }
      })
      .catch((error: AxiosError) => {
        console.error("error:" + JSON.stringify(error));
      })
  }

  getMsgList() {
    getMessageList(0, 1, 6)
      .then((res) => {
        console.log("get 消息列表成功", JSONUtil.beanToJsonStr(res))
        if (res.code == 20041) {
          let data = res.data
          if (data) {
            data.counts;
            let items = data.items;
            if (items) {
              this.msgListData = items;
            }
            if (!this.msgListData || this.msgListData.length < 1) {
              this.handErrorOrEmPty(0, "暂无新消息！")
            }
          } else {
            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) {
    let bean = new MainMessageBean()
    bean.baseType = type;
    bean.msgContent = msg;
    this.msgListData = new Array<MainMessageBean>();
    this.msgListData.push(bean)
  }

  /**
   * 获取推荐应用列表
   */
  getRecommendApplicationList() {
    getRecommendApplication()
      .then((res) => {
        console.log("get 推荐应用列表成功", JSONUtil.beanToJsonStr(res))
        if (res.code == 20041) {
          let data = res.data;
          if (data) {
            let listData = new Array<ApplicationModel>()

            let tjyy = data.推荐应用;
            if (tjyy) {
              tjyy.forEach((item) => {
                listData.push(item)
              })
            }
            let zxyy = data.最新应用;
            if (zxyy) {
              zxyy.forEach((item) => {
                listData.push(item)
              })
            }
            if (listData.length < 1) {
              let bean = new ApplicationModel()
              bean.baseType = 91
              bean.name = "应用指南"
              bean.locationIcon = $r('app.media.ic_zfjc')
              this.appListData.push(bean)
              let bean1 = new ApplicationModel()
              bean1.baseType = 92
              bean1.name = "常见问题"
              bean1.locationIcon = $r('app.media.ic_zazh')
              this.appListData.push(bean1)
              let bean2 = new ApplicationModel()
              bean2.baseType = 93
              bean2.name = "意见反馈"
              bean2.locationIcon = $r('app.media.ic_zazh')
              this.appListData.push(bean2)
              bean = new ApplicationModel()
              bean.baseType = 99
              bean.name = "更多应用"
              bean.locationIcon = $r('app.media.icon_gd2')
              this.appListData.push(bean)
              // ToastUtil.showToast("暂无推荐应用")
              return
            }
            if (listData.length >= 8) {
              this.appListData = listData.slice(8)
              let bean = this.appListData[7]
              bean.baseType = 99
              bean.name = "更多应用"
              bean.locationIcon = $r('app.media.icon_gd2')
            } else {
              this.appListData = listData
              let bean = new ApplicationModel()
              bean.baseType = 99
              bean.name = "更多应用"
              bean.locationIcon = $r('app.media.icon_gd2')
              this.appListData.push(bean)
            }
            if (listData.length > 4) {
              this.tjyyHeight = $r('app.float.default_160')
            } else {
              this.tjyyHeight = $r('app.float.default_105')
            }
          }
        }
      })
      .catch((err: AxiosError) => {
        console.error("get 推荐应用列表失败", err)
      })
  }

  skipMyUserInfo() {
    HMRouterMgr.push({ navigationId: 'startNavigation', pageUrl: "MyUserInfoPage" })
  }

  readMsg(item: MainMessageBean) {
    readMessage(item.id)
      .then((res) => {
        console.debug("发送点击：", JSONUtil.beanToJsonStr(res))
        if (res.code == 20041) {
          this.getMsgList()
        }
      })
      .catch((error: AxiosError) => {
        console.error("发送点击：", JSONUtil.beanToJsonStr(error))
      })
  }

  build() {
    Stack({ alignContent: Alignment.TopStart }) {
      this.underlyingBackground()
      this.mainContent()
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
    .backgroundColor($r('app.color.page_background'))
  }

  /**
   * 主界面
   */
  @Builder
  mainContent() {
    Column() {
      this.userInfoUI()
      this.recommendedApplicationUI()
      this.pendingMessageUI()
    }
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)

  }

  /**
   * 待办消息区域
   */
  @Builder
  pendingMessageUI() {
    Column() {
      Row() {
        Text("待办消息")
          .fontSize($r('app.float.text_size_16'))
          .fontColor($r('app.color.colorGrey8'))
          .layoutWeight(1)
          .textAlign(TextAlign.Start)

        Text("全部消息")
          .fontSize($r('app.float.text_size_14'))
          .fontColor($r('app.color.colorGrey6'))
          .textAlign(TextAlign.Start)
          .onClick(() => {
            if (this.allMessage) {
              this.allMessage()
            }
          })

        Image($r('app.media.arrow_right'))
          .width($r('app.float.default_18'))
          .height($r('app.float.default_18'))
          .margin({ left: $r('app.float.default_8') });
      }
      .alignItems(VerticalAlign.Center)
      .width(AppConstants.PERCENTAGE_MAX)
      .padding({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .height($r('app.float.default_40'))

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

      List() {
        ForEach(this.msgListData, (item: MainMessageBean, index) => {
          if (item.baseType == 0 || item.baseType == -1) {
            ListItem() {
              EmptyOrErrorItemView({ type: item.baseType, msg: item.msgContent })
            }
          } else {
            ListItem() {
              this.msgItem(item)
            }
            .onClick(() => {
              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 })
            })
          }
        })
      }
      .margin({ left: $r('app.float.default_10'), right: $r('app.float.default_10') })
      .width("95%")
      .layoutWeight(1)

    }
    .margin($r('app.float.default_10'))
    .width('95%')
    .layoutWeight(1)
    .backgroundColor($r('app.color.white'))
    .border(cardRoundBorderStyle)
  }

  /**
   * 消息列表
   * @param item
   */
  @Builder
  msgItem(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($r('app.media.icon_not_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'))
            .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({ top: $r('app.float.default_10') })
    .border(cardRoundBorderGreyStyle)
  }

  /**
   * 错误或者空的消息列表显示
   */
  @Builder
  msgItemError(type: number, msg: string) {
    Column() {
      Image(type == 0 ? $r('app.media.icon_empty') : $r('app.media.icon_error2'))
        .width($r('app.float.default_80'))
        .height($r('app.float.default_80'))

      Text(msg)
        .fontSize($r('app.float.text_size_14'))
        .fontColor($r('app.color.colorGrey6'))
        .textAlign(TextAlign.Center)
        .margin({ top: $r('app.float.default_10') })

    }
    .justifyContent(FlexAlign.Center)
    .alignItems(HorizontalAlign.Center)
    .width(AppConstants.PERCENTAGE_MAX)
    .height(AppConstants.PERCENTAGE_MAX)
  }

  /**
   * 推荐应用区域
   */
  @Builder
  recommendedApplicationUI() {
    Column() {
      Grid() {
        ForEach(this.appListData, (item: ApplicationModel, index) => {
          GridItem() {
            Column() {
              Image((item.baseType == 99 || item.baseType == 91 || item.baseType == 92 || item.baseType == 93) ?
              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)
                .textAlign(TextAlign.Center)
                .fontSize($r('app.float.text_size_14'))
                .fontColor($r('app.color.colorGrey8'))
                .margin({ top: $r('app.float.default_8') });
            }
            .height('auto')
            .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('1fr 1fr 1fr 1fr') //一行有4列，等分
      .columnsGap($r('app.float.default_10')) //行间距
      .rowsGap($r('app.float.default_10')); //列间距

    }
    .padding($r('app.float.default_10'))
    .margin({ top: $r('app.float.default_10'), right: $r('app.float.default_10'), left: $r('app.float.default_10') })
    .width('95%')
    .height(this.tjyyHeight)
    .backgroundColor($r('app.color.white'))
    .border(cardRoundBorderStyle)
  }

  /**
   * 用户信息区域
   */
  @Builder
  userInfoUI() {
    Row() {
      Image(this.userPhoto)
        .size({
          width: $r('app.float.default_63'),
          height: $r('app.float.default_63')
        })
        .border({
          radius: 50
        })
        .margin({ left: $r('app.float.default_15') });

      Column() {
        Row() {
          Text(UserCache.getUserCache().getUserName)
            .fontSize($r('app.float.default_16'))
            .fontColor($r('app.color.white'));

          Text(UserCache.getUserCache().getUserCode)
            .fontSize($r('app.float.text_size_12'))
            .fontColor($r('app.color.colorBluen8'))
            .padding({
              left: $r('app.float.default_8'),
              right: $r('app.float.default_8'),
              top: $r('app.float.default_2'),
              bottom: $r('app.float.default_2')
            })
            .backgroundColor('#E9F4F3')
            .border({
              radius: 10
            });
        }
        .alignItems(VerticalAlign.Center)
        .justifyContent(FlexAlign.Start)
        .onClick(() => {
          this.skipMyUserInfo()
        });

        Text(UserCache.getUserCache().getDeptName)
          .fontSize($r('app.float.default_16'))
          .fontColor($r('app.color.white'))
          .margin({ top: $r('app.float.default_8') })
          .onClick(() => {
            this.skipMyUserInfo()
          });

      }
      .margin({ left: $r('app.float.default_10') })
      .alignItems(HorizontalAlign.Start)
      .layoutWeight(1);
    }
    .alignItems(VerticalAlign.Center)
    .justifyContent(FlexAlign.Start)
    .margin({ top: $r('app.float.default_28') })
    .width(AppConstants.PERCENTAGE_MAX)
    .height('13%')
    .onClick(() => {
      this.skipMyUserInfo()
    })
  }

  /**
   * 背景图片
   */
  @Builder
  underlyingBackground() {
    Column() {
      Image($r('app.media.bg_two'))
        .width(AppConstants.PERCENTAGE_MAX)
        .height('28%')
    }
  }
}