import { AppUtil, NumberUtil, StrUtil } from '@pura/harmony-utils';
import { ErrCode, PayResp } from '@tencent/wechat_open_sdk';
import { Constants } from '../../../../common/Constants';
import { RouterUrls } from '../../../../common/RouterUrls';
import { LoadingDialog } from '../../../../dialog/LoadingDialog';
import { PayOrderEntity } from '../../../../entity/OrderPayEntity';
import { VipMealEntity } from '../../../../entity/VipMealEntity';
import { LoginManager } from '../../../../manager/LoginGlobalManager';
import { ConfigManager } from '../../../../manager/UserConfigManager';
import { PayUtils } from '../../../../utils/PayUtils';
import { ToastUtils } from '../../../../utils/ToastUtils';
import { OnWXResp, WXApi, WXEventHandler } from '../../../../utils/wechat/WXApiEventHandlerImpl';
import { TitleBar } from '../../../../view/TitleBar';
import { VipGoodsItemView } from '../../../../view/VipGoodsItemView';
import { VipViewModel } from '../../../../viewModel/VipViewModel';
import { BusinessError, systemDateTime } from '@kit.BasicServicesKit';
import router from '@ohos.router';
import { EventConstants } from '../../../../common/EventConstants';
import { EventReportGlobalManager } from '../../../../manager/EventReportGlobalManager';
import { SimpleTipDialog } from '../../../../dialog/SimpleTipDialog';
import { OrderEntity } from '../../../../entity/OrderEntity';
import { TipDialog } from '../../../../dialog/TipDialog';
import { window } from '@kit.ArkUI';
import { MenuEntity, vipTipsList } from '../../../../entity/MenuEntity';

@Entry
@ComponentV2
struct VipPage {
  @Local origin: string = 'center';
  @Local isGuide: boolean = false;
  @Local vipMealList: Array<VipMealEntity> = [];
  @Local vipMeal?: VipMealEntity;
  @Local isAgree: boolean = false;
  @Local payType: number = 0; //0微信支付 1支付宝支付
  @Local totalPrice: number = 0;

  windowStage: window.WindowStage = AppStorage.get("windowStage") as window.WindowStage;

  showQueryTip: boolean = false //是否显示支付状态查询提示

  viewModel: VipViewModel = new VipViewModel(this.getUIContext());
  orderEntity?: PayOrderEntity;
  pageStartTime: number = systemDateTime.getTime()

  //从微信返回的回调
  onWXResp: OnWXResp = (resp) => {
    //微信返回的数据
    if (resp instanceof PayResp) {
      const payResult = JSON.stringify(resp ?? {}, null, 2);
      const errCode = JSON.parse(payResult).errCode as number;
      if (errCode === ErrCode.ERR_OK) {
        this.viewModel.getOrderInfo(this.orderEntity!!.orderId)
      } else {
        ToastUtils.show(JSON.parse(payResult).errStr);
        EventReportGlobalManager.eventReport(
          EventConstants.ERROR_CLIENT_WXPAY_ERR,
          `{isGuide:${this.isGuide}, orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.vipMeal)}}`,
          JSON.parse(payResult).errStr
        )
      }
    }
    LoadingDialog.dismiss();
  }

  @Monitor('viewModel.goodsList')
  onGoodsListChange(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<VipMealEntity>;
    this.vipMealList = list;
    if (this.vipMealList.length > 0) {
      this.vipMeal = this.vipMealList.find(item => item.checked === true);
      if (!this.vipMeal) {
        this.vipMeal = this.vipMealList[0];
      }
      if (this.vipMeal) {
        this.totalPrice = NumberUtil.toNumber(this.vipMeal.price);
        this.releasePayType();
      }
    }
  }

  @Monitor('viewModel.payOrderEntity')
  onPayOrderChange(monitor: IMonitor) {
    const payOrderEntity = monitor.value()?.now as PayOrderEntity;
    this.orderEntity = payOrderEntity;
    if (this.payType === 0) {
      if (StrUtil.isNotEmpty(this.vipMeal?.weixinMpOriId)) {
        PayUtils.toWXMPPay(payOrderEntity.outTradeNo, this.vipMeal!!.weixinMpOriId)
        this.showQueryTip = true
      } else {
        PayUtils.toWXPay(payOrderEntity);
      }
    } else {
      PayUtils.toAliPay(payOrderEntity.payParam)
        .then((result) => {
          this.parseAlipayResult(result);
        })
        .catch((error: BusinessError) => {
          console.log(error.message);
          ToastUtils.show('支付失败');
        });
    }
  }

  @Monitor('viewModel.orderInfoEntity')
  onOrderInfoChange(monitor: IMonitor) {
    const orderEntity = monitor.value()?.now as OrderEntity;
    if (orderEntity.status == "2") {
      ToastUtils.show('支付成功');
      EventReportGlobalManager.eventReport(
        EventConstants.PAY_SUCCESS,
        'alipay', `{isGuide:${this.isGuide}, orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.vipMeal)}}`
      )
      this.doBack();
    }
  }

  aboutToAppear() {
    this.windowStage.getMainWindowSync().setWindowSystemBarProperties({
      statusBarColor: '#00000000',
      statusBarContentColor: '#FFFFFF'
    });
    WXEventHandler.registerOnWXRespCallback(this.onWXResp)
    this.initParams();
    this.viewModel.mealList();
  }

  aboutToDisappear() {
    this.windowStage.getMainWindowSync().setWindowSystemBarProperties({
      statusBarColor: '#00000000',
      statusBarContentColor: '#000000'
    });
    WXEventHandler.unregisterOnWXRespCallback(this.onWXResp)
    this.viewModel.cancelInterval()
  }

  onPageShow(): void {
    if (this.showQueryTip) {
      TipDialog.show(this.getUIContext(), { title: '温馨提示', content: '是否已完成支付', leftText: '未支付', rightText: '已支付', callback: {
        confirm: () => {
          this.viewModel.getOrderInfo(this.orderEntity!!.orderId)
        }
      } }, false)
      this.showQueryTip = false
    }
  }

  initParams() {
    const params = this.getUIContext().getRouter().getParams() as Record<string, Object>;
    if (params) {
      this.origin = params.origin as string;
      this.isGuide = this.origin === 'bootpage';
    }
  }

  createOrder() {
    if (!ConfigManager.isNoLoginPayEnable() && !LoginManager.isLogin()) {
      ToastUtils.show('请登录后支付');
      this.getUIContext().getRouter().pushUrl({ url: RouterUrls.LOGIN_PAGE, params: { from: 1 } }, router.RouterMode.Single);
      return;
    }
    if (this.payType === 0 && !WXApi.isWXAppInstalled()) {
      ToastUtils.show('请先下载安装微信客户端');
      return;
    }
    if (this.payType === 0) {
      if (StrUtil.isNotEmpty(this.vipMeal!!.weixinMpOriId)) {
        this.viewModel.createOrder(this.vipMeal?.goods_id!!, 'combo', this.origin, '');
      } else {
        this.viewModel.createOrder(this.vipMeal?.goods_id!!, 'weixin', this.origin, '');
      }
    } else {
      this.viewModel.createOrder(this.vipMeal?.goods_id!!, 'alipay', this.origin, '');
    }
  }

  parseAlipayResult(result: Map<string, string>) {
    const resultStatus = result.get('resultStatus');
    if (resultStatus === '9000') {
      this.viewModel.getOrderInfo(this.orderEntity!!.orderId)
    } else if (resultStatus === '6001') {
      ToastUtils.show('支付取消');
      EventReportGlobalManager.eventReport(
        EventConstants.PAY_CANCEL,
        'alipay', `{isGuide:${this.isGuide}, orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.vipMeal)}}`
      )
    } else {
      ToastUtils.show('支付失败');
      EventReportGlobalManager.eventReport(
        EventConstants.ERROR_CLIENT_ALIPAY_ERR,
        `{orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.vipMeal)}}`, resultStatus
      )
    }
  }

  formatPricePeriod(value?: string): string {
    if (value === '#') {
      return '/终生';
    } else if (value?.endsWith('m')) {
      const monthStr = value.replace('m', '');
      if (StrUtil.isNotEmpty(monthStr)) {
        const month = NumberUtil.toInt(monthStr);
        if (month >= 12) {
          return `/${month / 12 > 1 ? month / 12 : ''}年`
        } else if (month % 3 === 0) {
          return `/${month / 3 > 1 ? month / 3 : ''}季`
        } else {
          return `/${month > 1 ? month : ''}月`
        }
      }
    }
    return '';
  }

  releasePayType() {
    if (this.vipMeal?.pay_type.startsWith('alipay')) {
      this.payType = 1;
    } else if (this.vipMeal?.pay_type.startsWith('weixin')) {
      this.payType = 0;
    }
  }

  pageDuration(): string {
    let duration = systemDateTime.getTime() - this.pageStartTime
    if (duration < 1000) {
      return `停留时间:${duration}ms`
    } else {
      return `停留时间:${Math.trunc(duration / 1000)}s`
    }
  }

  doBack() {
    if (this.isGuide) {
      this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.MAIN_PAGE }, router.RouterMode.Single);
      AppUtil.getContext().eventHub.emit(EventConstants.HomeRefreshEvent);
      AppUtil.getContext().eventHub.emit(EventConstants.MineRefreshEvent);
    } else {
      this.getUIContext().getRouter().back();
    }
  }

  onBackPress(): boolean | void {
    if (this.isGuide) {
      EventReportGlobalManager.eventReport(EventConstants.GUIDE_SKIP, "back", this.pageDuration())
      this.getUIContext().getRouter().replaceUrl({ url: RouterUrls.MAIN_PAGE }, router.RouterMode.Single)
      return true;
    }
  }

  build() {
    RelativeContainer() {
      Column() {
        Scroll() {
          RelativeContainer() {
            Image($r("app.media.ic_vip_top_bg"))
              .width('100%')
              .aspectRatio(1.175)
              .id('iv_top_bg')

            Column() {
              List() {
                ForEach(this.vipMealList, (item: VipMealEntity) => {
                  ListItem() {
                    VipGoodsItemView({
                      entity: item,
                      isChecked: this.vipMeal?.goods_id === item.goods_id,
                      isGrid: this.vipMealList.length <= 3
                    })
                  }
                  .onClick(() => {
                    this.vipMealList.forEach((value) => {
                      value.checked = false;
                    })
                    item.checked = true;
                    this.vipMeal = item;
                    this.totalPrice = NumberUtil.toNumber(item.price);
                    this.releasePayType();
                    EventReportGlobalManager.eventReport(EventConstants.GOODS_SELECT, `${this.origin}:${item.goods_name}`, JSON.stringify(item))
                  })
                })
              }
              .width('auto')
              .height('auto')
              .listDirection(this.vipMealList.length > 3 ? Axis.Horizontal : Axis.Vertical)
              .alignListItem(ListItemAlign.Center)
              .margin({ left: 14, right: 14 })
              .lanes(this.vipMealList.length > 3 ? 1 : 3)

              RelativeContainer() {
                Column() {
                  Row(){
                    Image($r('app.media.ic_vip_tips_star')).width(14).height(14)
                    Row() {
                      Text('解锁以下会员权益').fontSize(16).fontFamily('almmsht')
                        .blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
                    }
                    .linearGradient({
                      direction: GradientDirection.Right,
                      colors: [['#FFEADB', 0.0], ['#FFFFFF', 0.3], ['#D9ECF8', 0.6], ['#C4C5F7', 1.0]]
                    })
                    .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)
                    .margin({left: 8, right: 8})
                    Image($r('app.media.ic_vip_tips_star')).width(14).height(14)
                  }

                  Image($r('app.media.ic_vip_tips_divider')).width('80%').height(1).margin({top: 20})

                  Grid(){
                    ForEach(vipTipsList().convertToArray(), (item: MenuEntity) => {
                      GridItem() {
                        Column() {
                          Image(item.icon).width(48).height(48)
                          Text(item.title).fontColor('#F0EFEB').fontSize(12).margin({top:6})
                        }
                      }
                    })
                  }
                  .scrollBar(BarState.Off)
                  .columnsTemplate('1fr 1fr 1fr 1fr')
                  .rowsGap(20)
                  .margin({top: 20})
                }
                .width('100%')
                .linearGradient({
                  colors: [['#343230', 0.0], ['#1F2430', 1.0]],
                  direction: GradientDirection.Right
                })
                .borderRadius(14)
                .margin({top: 24, bottom: 24})
                .padding({top: 20, bottom: 20})
                .id('layout_tips')

                Image($r('app.media.ic_vip_tips_light')).width(203).height(48)
                Image($r('app.media.ic_vip_tips_light')).width(203).height(48)
                  .alignRules({
                    right: {anchor: '__container__', align: HorizontalAlign.End},
                    bottom:{anchor: 'layout_tips', align: VerticalAlign.Bottom}
                  })
                  .margin({bottom: -24})
              }
              .width('100%')
              .height('auto')
              .padding({left: 20, right: 20})

              Row() {
                Image($r('app.media.ic_coupon')).width(30).height(30)
                Text('优惠券').fontColor(Color.White).fontSize(15).margin({ left: 12 })
                Blank().layoutWeight(1)
                Text('暂无可用的优惠券').fontColor($r('app.color.color_50ffffff')).fontSize(13)
                Image($r('app.media.ic_arrow_dp16')).width(16).height(16)
              }
              .padding({ left: 20, right: 16 })
              .margin({ top: 22 })
              .visibility(Visibility.None)

              Row() {
                Text('支付方式').fontSize(14).fontWeight(FontWeight.Medium)
                  .blendMode(BlendMode.DST_IN, BlendApplyType.OFFSCREEN)
              }
              .linearGradient({
                direction: GradientDirection.Right,
                colors: [['#FFEADB', 0.0], ['#FFFFFF', 0.3], ['#D9ECF8', 0.6], ['#C4C5F7', 1.0]]
              })
              .blendMode(BlendMode.SRC_OVER, BlendApplyType.OFFSCREEN)
              .margin({ left: 20 })
              .alignSelf(ItemAlign.Start)

              Row() {
                Image($r('app.media.ic_wx_pay')).width(30).height(30)
                Text('微信').fontColor(Color.White).fontSize(15).margin({ left: 12 })
                Blank().layoutWeight(1)
                Image(this.payType === 0 ? $r('app.media.ic_check_true') : $r('app.media.ic_check_false'))
                  .width(18)
                  .height(18)
              }
              .margin({ left: 20, top: 4, right: 20 })
              .padding({ top: 16, bottom: 16 })
              .visibility(this.vipMeal?.pay_type.includes('weixin') ? Visibility.Visible : Visibility.None)
              .onClick(() => {
                this.payType = 0;
                EventReportGlobalManager.eventReport(EventConstants.PAY_SELECT, 'weixin', this.origin)
              })

              Divider().color($r('app.color.color_10ffffff')).strokeWidth(1)

              Row() {
                Image($r('app.media.ic_ali_pay')).width(30).height(30)
                Text('支付宝').fontColor(Color.White).fontSize(15).margin({ left: 12 })
                Blank().layoutWeight(1)
                Image(this.payType === 1 ? $r('app.media.ic_check_true') : $r('app.media.ic_check_false'))
                  .width(18)
                  .height(18)
              }
              .margin({ left: 20, right: 20 })
              .padding({ top: 16, bottom: 16 })
              .visibility(this.vipMeal?.pay_type.includes('alipay') ? Visibility.Visible : Visibility.None)
              .onClick(() => {
                this.payType = 1;
                EventReportGlobalManager.eventReport(EventConstants.PAY_SELECT, "alipay", this.origin)
              })

              Divider().color($r('app.color.color_10ffffff')).strokeWidth(1)

              Row() {
                Image(this.isAgree ? $r('app.media.ic_check_true') : $r('app.media.ic_check_false'))
                  .width(16)
                  .height(16)
                Text() {
                  Span('我已阅读并同意')
                  Span('《会员服务协议规则》').fontColor($r("app.color.color_466afd"))
                    .onClick(() => {
                      this.getUIContext()
                        .getRouter()
                        .pushUrl({
                          url: RouterUrls.WEB_PAGE,
                          params: { title: '会员服务协议规则', url: Constants.USER_AGREEMENT }
                        })
                    })
                  if (StrUtil.isNotEmpty(this.vipMeal?.sign_value) && this.payType === 1) {
                    Span('和')
                    Span('《自动续费服务规则》').fontColor($r("app.color.color_466afd"))
                      .onClick(() => {
                        this.getUIContext()
                          .getRouter()
                          .pushUrl({
                            url: RouterUrls.WEB_PAGE,
                            params: { title: '自动续费服务规则', url: Constants.RENEW_AGREEMENT }
                          })
                      })
                  }
                }
                .fontColor($r('app.color.color_90ffffff'))
                .fontSize(12)
                .margin({ left: 4, top: 1 })
                .layoutWeight(1)
              }
              .alignItems(VerticalAlign.Top)
              .margin(20)
              .visibility(ConfigManager.isPayAgreementEnable() ? Visibility.Visible : Visibility.None)
              .onClick(() => {
                this.isAgree = !this.isAgree;
              })
            }
            .alignRules({
              top: { anchor: 'iv_top_bg', align: VerticalAlign.Bottom }
            })
            .margin({ top: -55 })
          }
          .height('auto')
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)

        Row() {
          Text() {
            Span('￥').fontSize(13)
            Span(`${this.totalPrice}`).fontSize(24).fontFamily('ddp500m')
            Span(this.formatPricePeriod(this.vipMeal?.value)).fontSize(13)
            Span('  ')
            Span('已优惠' + this.vipMeal?.origin_price + '元')
              .fontColor('#FFC4A6')
              .fontSize(12)
              .decoration({ type: TextDecorationType.LineThrough, color: $r('app.color.color_30ffffff') })
          }
          .fontColor('#F03535')

          Blank().layoutWeight(1)

          Text('立即开通')
            .width(148)
            .height(46)
            .textAlign(TextAlign.Center)
            .fontColor(Color.White)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .backgroundImage($r('app.media.ic_vip_pay_btn'))
            .backgroundImageSize({ width: '100%', height: '100%' })
            .onClick(() => {
              if (this.vipMeal) {
                if (ConfigManager.isPayAgreementEnable() && !this.isAgree) {
                  SimpleTipDialog.show(this.getUIContext(), { title: '提示', content: StrUtil.isNotEmpty(this.vipMeal?.sign_value) && this.payType === 1 ? '请阅读并同意《会员服务协议规则》和《自动续费服务规则》' : '请阅读并同意《会员服务协议规则》', callback: {
                    confirm: () => {
                      this.isAgree = true
                      this.createOrder();
                      EventReportGlobalManager.eventReport(EventConstants.PAY_PAY, this.payType === 0 ? 'weixin' : 'alipay', JSON.stringify(this.vipMeal))
                    }
                  }})
                } else {
                  this.createOrder();
                  EventReportGlobalManager.eventReport(EventConstants.PAY_PAY, this.payType === 0 ? 'weixin' : 'alipay', JSON.stringify(this.vipMeal))
                }
              }
            })
        }
        .backgroundColor('#1F2126')
        .borderRadius({ topLeft: 20, topRight: 20 })
        .padding({
          top: 9,
          left: 20,
          right: 20,
          bottom: 30
        })
      }
      .width('100%')
      .height('100%')

      TitleBar({
        isDark: true,
        onBackClick: () => {
          if (this.isGuide) {
            EventReportGlobalManager.eventReport(EventConstants.GUIDE_SKIP, "icon", this.pageDuration())
          }
          this.doBack();
        }
      }).width('100%')
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#0F1016')
  }
}