import { AppUtil, PasteboardUtil, StrUtil } from '@pura/harmony-utils';
import { EventConstants } from '../../../common/EventConstants';
import { RouterUrls } from '../../../common/RouterUrls';
import { UserEntity } from '../../../entity/UserEntity';
import { LoginManager } from '../../../manager/LoginGlobalManager';
import { ToastUtils } from '../../../utils/ToastUtils';
import MineViewModel from '../../../viewModel/MineViewModel';
import { CommonModifier, router } from '@kit.ArkUI';
import { fileIo, storageStatistics } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { LoadingDialog } from '../../../dialog/LoadingDialog';
import { DiamondDetailEntity } from '../../../entity/DiamondDetailEntity';
import { EventReportGlobalManager } from '../../../manager/EventReportGlobalManager';
import { WxServiceEntity } from '../../../entity/WxServiceEntity';
import { WXApi } from '../../../utils/wechat/WXApiEventHandlerImpl';
import * as WxOpenSdk from '@tencent/wechat_open_sdk';
import { Constants } from '../../../common/Constants';
import { MenuEntity, mineMenuList } from '../../../entity/MenuEntity';
import { MediaAction, MediaType } from '../../../manager/MediaManager';
import { VideoRecordPage } from '../record/VideoRecordPage';
import { ImageRecordPage } from '../record/ImageRecordPage';
import { AudioRecordPage } from '../record/AudioRecordPage';

@ComponentV2
export struct MinePage {
  @Local showChallenge: boolean = false;
  @Local showShare: boolean = false;
  @Local isLogin: boolean = LoginManager.isLogin();
  @Local userinfo?: UserEntity;
  @Local diamondInfo?: DiamondDetailEntity
  @Local currentIndex: number = 0;
  @Local tabBarModifier: CommonModifier = new CommonModifier()

  private viewModel: MineViewModel = new MineViewModel(this.getUIContext());

  private scroller: Scroller = new Scroller();
  private tabController: TabsController = new TabsController();
  private titles: Array<string> = ['视频', '图片', '音频'];


  @Monitor('viewModel.userEntity')
  onUserinfoChange(monitor: IMonitor) {
    this.userinfo = monitor.value()?.now as UserEntity;
  }

  @Monitor('viewModel.wxService')
  onWxServiceChange(monitor: IMonitor) {
    const info = monitor.value()?.now as WxServiceEntity
    if (StrUtil.isEmpty(info.corpid) || StrUtil.isEmpty(info.address)) {
      ToastUtils.show('获取客服信息错误')
    } else {
      this.contactWxService(info)
    }
  }

  @Monitor('viewModel.diamondInfo')
  onDiamondInfoChange(monitor: IMonitor) {
    this.diamondInfo = monitor.value()?.now as DiamondDetailEntity;
  }

  aboutToAppear(): void {
    this.tabBarModifier.align(Alignment.Start)
    this.initObserver();
    this.viewModel.userinfo();
    this.viewModel.getDiamondInfo()
  }

  initObserver() {
    AppUtil.getContext().eventHub.on(EventConstants.MineRefreshEvent, () => {
      this.isLogin = LoginManager.isLogin();
      this.viewModel.userinfo();
    });
  }

  /**
   * 跳转客服
   * @param service
   */
  contactWxService(service: WxServiceEntity) {
    let req = new WxOpenSdk.OpenCustomerServiceChatReq()
    req.corpId = service.corpid; // 企业ID
    req.url = service.address;	// 客服URL
    WXApi.sendReq(AppUtil.getContext(), req)
  }

  build() {
    Scroll(this.scroller) {
      Stack() {
        Image($r('app.media.ic_mine_top_bg'))
          .width('100%')
          .aspectRatio(1.465)
          .id('iv_top_bg')

        Column() {
          RelativeContainer() {
            Image(StrUtil.isNotEmpty(this.userinfo?.avater) ? this.userinfo?.avater : $r('app.media.ic_default_avatar'))
              .alignRules({
                left: { anchor: '__container__', align: HorizontalAlign.Start }
              })
              .margin({left: 16 })
              .padding(1)
              .borderRadius(28)
              .width(56)
              .height(56)
              .backgroundColor(Color.White)
              .id('iv_avatar')
              .onClick(() => {
                if (!LoginManager.isLogin()) {
                  this.getUIContext().getRouter().pushUrl({ url: RouterUrls.LOGIN_PAGE, params: { from : 1 }}, router.RouterMode.Single)
                  EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_LOGIN, 'center')
                } else {
                  this.getUIContext().getRouter().pushUrl({ url: RouterUrls.USER_SETTINGS_PAGE })
                }
              })

            Text('点击登录')
              .width(52)
              .height(18)
              .fontColor(Color.White)
              .fontSize(10)
              .textAlign(TextAlign.Center)
              .alignRules({
                left: { anchor: 'iv_avatar', align: HorizontalAlign.Start },
                right: { anchor: 'iv_avatar', align: HorizontalAlign.End },
                bottom: { anchor: 'iv_avatar', align: VerticalAlign.Bottom }
              })
              .margin({ bottom: -7 })
              .borderRadius(9)
              .backgroundColor($r('app.color.color_466afd'))
              .visibility(this.isLogin ? Visibility.None : Visibility.Visible)
              .id('tv_nologin_tip')

            Text(this.userinfo?.ip_area)
              .fontColor(Color.White)
              .fontSize(12)
              .alignRules({
                top: { anchor: '__container__', align: VerticalAlign.Top },
                left: { anchor: 'iv_avatar', align: HorizontalAlign.End }
              })
              .padding({
                left: 6,
                right: 6,
                bottom: 4
              })
              .margin({ left: -25 })
              .width('auto')
              .height(21)
              .backgroundImage($r('app.media.ic_area_bg'))
              .backgroundImageSize({width: 'auto', height:21})
              .visibility(StrUtil.isNotEmpty(this.userinfo?.ip_area) && this.userinfo?.ip_area !== 'CN' && LoginManager.isLogin() ? Visibility.Visible : Visibility.None)
              .id('tv_area')

            Text(StrUtil.isNotEmpty(this.userinfo?.name) ? this.userinfo?.name : '游客')
              .fontColor($r('app.color.color_212226'))
              .fontSize(17)
              .fontWeight(FontWeight.Medium)
              .margin({ left: 12, top: 4 })
              .alignRules({
                top: { anchor: 'iv_avatar', align: VerticalAlign.Top },
                left: { anchor: 'iv_avatar', align: HorizontalAlign.End },
                bottom: { anchor: 'tv_user_id', align: VerticalAlign.Top}
              })
              .width('auto')
              .height('auto')
              .id('tv_username')

            Row() {
              Text('ID:' + this.userinfo?.user_id)
                .fontColor('#53555D')
                .fontSize(14)
                .id('tv_user_id')
              Image($r('app.media.ic_copy_id'))
                .margin({ left: 4 })
                .width(14)
                .height(14)
            }
            .alignRules({
              top: { anchor: 'tv_username', align: VerticalAlign.Bottom },
              left: { anchor: 'tv_username', align: HorizontalAlign.Start },
              bottom: { anchor: 'iv_avatar', align: VerticalAlign.Bottom }
            })
            .margin({ bottom: 4 })
            .width('auto')
            .id('layout_copy_id')
            .onClick(() => {
              if (StrUtil.isNotEmpty(this.userinfo?.user_id)) {
                PasteboardUtil.setDataTextSync(`${this.userinfo?.user_id!!}|${Constants.APP_ID}`)
                ToastUtils.show('复制成功')
              }
            })

            Row() {
              Image($r('app.media.ic_mine_setting')).width(26).height(26)
                .onClick(() => {
                  this.getUIContext().getRouter().pushUrl({url: RouterUrls.SETTING_PAGE});
                  EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_SYSTEM_SETTING)
                })
            }
            .alignRules({
              bottom: {anchor: 'iv_avatar', align: VerticalAlign.Top},
              right: {anchor: '__container__', align: HorizontalAlign.End}
            })
            .margin({ right: 20 })
          }
          .margin({ top: 100 })
          .width('100%')
          .height(70)

          RelativeContainer() {
            Stack() {
              Image($r('app.media.ic_mine_vip_bg')).width('100%').aspectRatio(5.01)
            }
            .padding({left: 12, right: 12})
            .alignRules({
              bottom: { anchor: '__container__', align: VerticalAlign.Bottom}
            })
            .id('layout_bg')

            Image($r('app.media.ic_mine_vip_tag')).width(74).height(69).id('iv_vip_tag')

            Column() {
              Row() {
                Text(this.userinfo?.vip === 1 ?  '会员办理' : this.userinfo?.vip_name)
                  .fontSize(18)
                  .fontFamily('ysbth')
                  .blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
              }
              .linearGradient({
                direction: GradientDirection.Right,
                colors: [['#FBF1DE', 0.0], ['#C59F78', 1.0]]
              })
              .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)

              Text(this.userinfo?.vip === 1 ? '开通会员解锁所有功能' : this.userinfo?.vip === 2 ? this.userinfo.vip_expire + ' 会员到期' : '享受永久会员专属权益')
                .fontColor('#FBF1DE')
                .fontSize(13)
            }
            .alignRules({
              left: { anchor: 'iv_vip_tag', align: HorizontalAlign.End},
              top: { anchor: 'layout_bg', align: VerticalAlign.Top },
              bottom: { anchor: 'layout_bg', align: VerticalAlign.Bottom }
            })
            .margin({bottom: 12})
            .alignItems(HorizontalAlign.Start)
            .justifyContent(FlexAlign.Center)

            Button({ type: ButtonType.Capsule, stateEffect: true }) {
              Row() {
                Text(this.userinfo?.vip === 1 ? '开通会员' : this.userinfo?.vip === 2 ? '立即续费' : '永久会员').fontColor('#8F6131').fontSize(14).fontWeight(FontWeight.Medium)
                Image($r('app.media.ic_mine_vip_arrow')).width(14).height(14).margin({left: 1})
              }
            }
            .alignRules({
              top: { anchor: 'layout_bg', align: VerticalAlign.Top },
              bottom: { anchor: 'layout_bg', align: VerticalAlign.Bottom },
              right: { anchor: 'layout_bg', align: HorizontalAlign.End }
            })
            .linearGradient({
              colors: [['#FFCD9E', 0.0], ['#FFEFDE', 1.0]],
              direction: GradientDirection.Top
            })
            .width('auto')
            .height(30)
            .margin({right: 28, bottom: 12})
            .padding({left: 9, top: 6, right: 7, bottom: 6})
            .visibility(this.userinfo?.vip === 3 ? Visibility.None : Visibility.Visible)
            .id('btn_to_vip')
            .onClick(() => {
              this.getUIContext().getRouter().pushUrl({url: RouterUrls.VIP_PAGE, params: {origin: 'center'}})
              EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_MEMBER_RECHARGE, 'center')
            })
          }
          .width('100%')
          .aspectRatio(4.464)

          Stack({alignContent: Alignment.Top}) {
            Row()
              .width('100%')
              .aspectRatio(3.348)
              .linearGradient({
                colors: [['#FFFFFF', 0.0], ['#F3F5F9', 1.0]],
                direction: GradientDirection.Bottom
              })
              .borderRadius({ topLeft: 10, topRight: 10})

            Column() {
              Text('常用工具').fontColor($r('app.color.color_212226')).fontSize(16).fontWeight(FontWeight.Medium).margin({top: 20})

              Grid() {
                ForEach(mineMenuList().convertToArray(), (item: MenuEntity) => {
                  GridItem() {
                    Column() {
                      Image(item.icon)
                        .width(26)
                        .height(26)
                      Text(item.title)
                        .fontColor($r('app.color.color_212226'))
                        .fontSize(12)
                        .margin({ top: 8 })
                    }
                    .alignItems(HorizontalAlign.Center)
                  }
                  .width('25%')
                  .onClick(() => {
                    switch (item.alias) {
                      case 'history': {
                        this.getUIContext().getRouter().pushUrl({url: RouterUrls.DOWNLOAD_HISTORY_PAGE});
                        EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_DOWNLOAD_HISTORY, 'center')
                        break
                      }
                      case 'diamond': {
                        this.getUIContext().getRouter().pushUrl({url: RouterUrls.RECHARGE_DIAMOND_PAGE});
                        EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_RECHARGE_DIAMOND, 'center')
                        break
                      }
                      case 'feedback': {
                        this.getUIContext().getRouter().pushUrl({url: RouterUrls.FEEDBACK_PAGE});
                        EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_FEEDBACK, 'center')
                        break
                      }
                      case 'service': {
                        if (!WXApi.isWXAppInstalled()) {
                          ToastUtils.show('未安装微信客户端，请先下载安装微信客户端');
                          return;
                        }
                        this.viewModel.getWxService()
                        break
                      }
                    }
                  })
                })
              }
              .maxCount(4)
              .layoutDirection(GridDirection.Row)
              .backgroundColor(Color.White)
              .borderRadius(8)
              .padding({top: 16, bottom: 16})
              .margin({top: 10})
            }
            .width('100%')
            .padding({left: 12, right: 12})
            .alignItems(HorizontalAlign.Start)
          }
          .margin({top: -12})

          Column() {
            Row() {
              Text('我的相册')
                .fontColor($r('app.color.color_212226'))
                .fontSize(16)
                .fontWeight(FontWeight.Medium)
                .textAlign(TextAlign.Start)
                .layoutWeight(1)

              Text(this.currentIndex === 2 ? '文件管理/我的手机/Download/素材魔方' : '文件管理/我的手机/Download/图库')
                .fontColor($r('app.color.color_999999'))
                .fontSize(12)
                .onClick(() => {

                })
            }
            .margin({left:12, top: 27, right: 12})

            Stack({alignContent: Alignment.TopEnd}) {
              Tabs({ barPosition: BarPosition.Start, controller: this.tabController, barModifier: this.tabBarModifier }) {
                TabContent() {
                  VideoRecordPage()
                }
                .tabBar(this.tabBuilder(this.titles[0], 0))

                TabContent() {
                  ImageRecordPage()
                }
                .tabBar(this.tabBuilder(this.titles[1], 1))

                TabContent() {
                  AudioRecordPage()
                }
                .tabBar(this.tabBuilder(this.titles[2], 2))
              }
              .scrollable(false)
              .barMode(BarMode.Scrollable)
              .onTabBarClick((index) => {
                this.currentIndex = index;
              })

              Row() {
                Image($r('app.media.ic_clear_record')).width(11).height(13)
                Text('全部清空').fontColor($r('app.color.color_999999')).fontSize(12).margin({left: 4})
              }
              .height(50)
              .margin({ top: 3, right: 16 })
              .onClick(() => {
                switch (this.currentIndex) {
                  case 0: {
                    AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.VIDEO, MediaAction.CLEAR)
                  }
                  case 1: {
                    AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.IMAGE, MediaAction.CLEAR)
                  }
                  case 2: {
                    AppUtil.getContext().eventHub.emit(EventConstants.MediaActionEvent, MediaType.AUDIO, MediaAction.CLEAR)
                  }
                }
              })
              .visibility(this.currentIndex === 2 ? Visibility.Visible : Visibility.None)
            }
          }
          .width('100%')
          .height('100%')

          /*Column() {
            TextItemView({ image: $r("app.media.ic_mine_icon1"), leftText: '免单挑战' })
              .height(60)
              .id('item_challenge')
              .visibility(*//*this.showChallenge ? Visibility.Visible : Visibility.None*//*Visibility.None)
            TextItemView({ image: $r("app.media.ic_mine_icon2"), leftText: '兑换钻石' })
              .height(60)
              .id('item_diamond')
              .onClick(() => {
                this.getUIContext().getRouter().pushUrl({url: RouterUrls.RECHARGE_DIAMOND_PAGE});
                EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_RECHARGE_DIAMOND, 'center')
              })
              .visibility(this.diamondInfo && this.diamondInfo?.buy_total > 0 ? Visibility.Visible : Visibility.None)
            TextItemView({ image: $r("app.media.ic_mine_icon3"), leftText: '优惠券' }).height(60).id('item_coupon')
              .visibility(Visibility.None)
            TextItemView({ image: $r("app.media.ic_mine_icon4"), leftText: '分享APP' })
              .height(60)
              .id('item_share')
              .visibility(*//*this.showShare ? Visibility.Visible : Visibility.None*//*Visibility.None)
            TextItemView({ image: $r("app.media.ic_mine_icon5"), leftText: '联系客服' }).height(60).id('item_service')
              .onClick(() => {
                if (!WXApi.isWXAppInstalled()) {
                  ToastUtils.show('未安装微信客户端，请先下载安装微信客户端');
                  return;
                }
                this.viewModel.getWxService()
              })
            TextItemView({ image: $r("app.media.ic_mine_icon6"), leftText: '清除缓存', rightText: FileUtil.getFormatFileSize(this.cacheSize) }).height(60).id('item_cache')
              .onClick(() => {
                if (this.cacheSize > 0) {
                  TipDialog.show(this.getUIContext(), {title: '提示', content: '确定清除缓存？', callback: {
                    confirm: () => {
                      this.clearCache()
                    }
                  }})
                }
              })
            TextItemView({ image: $r("app.media.ic_mine_icon7"), leftText: '设置' }).height(60).id('item_setting')
              .onClick(() => {
                this.getUIContext().getRouter().pushUrl({url: RouterUrls.SETTING_PAGE});
                EventReportGlobalManager.eventReport(EventConstants.JUMP_TO_SYSTEM_SETTING)
              })
          }
          .margin({ top: 16, left: 16, right: 16 })
          .backgroundColor('#1E1D24')
          .borderRadius(8)*/

          Blank().layoutWeight(1)
        }
      }
      .alignContent(Alignment.Top)
    }
    .padding({ bottom: 20 })
    .scrollBar(BarState.Off)
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.window_background'))
  }

  @Builder
  tabBuilder(title: string, targetIndex: number) {
    Stack() {
      if (this.currentIndex === targetIndex) {
        Image($r('app.media.ic_tab_indicator')).width(27).height(11).margin({ top: 13 })
      }
      Text(title)
        .fontColor(this.currentIndex === targetIndex ? $r("app.color.color_212226") : $r('app.color.color_5c5f6c'))
        .fontSize(this.currentIndex === targetIndex ? 16 : 14)
        .fontWeight(this.currentIndex === targetIndex ? FontWeight.Medium : FontWeight.Regular)
    }
    .width('auto')
    .height(50)
    .margin({ left: targetIndex === 0 ? 12 : 30 })
  }
}