import { RouterUrls } from '../../../../common/RouterUrls';
import { VipMealEntity } from '../../../../entity/VipMealEntity'
import { LoginManager } from '../../../../manager/LoginGlobalManager';
import { ConfigManager } from '../../../../manager/UserConfigManager';
import { ToastUtils } from '../../../../utils/ToastUtils';
import { TitleBar } from '../../../../view/TitleBar'
import { LevelMode, router } from '@kit.ArkUI';
import { OnWXResp, WXApi, WXEventHandler } from '../../../../utils/wechat/WXApiEventHandlerImpl';
import { PayOrderEntity } from '../../../../entity/OrderPayEntity';
import { PayUtils } from '../../../../utils/PayUtils';
import { BusinessError } from '@kit.BasicServicesKit';
import { NumberUtil, ObjectUtil, StrUtil } from '@pura/harmony-utils';
import { ErrCode, PayResp } from '@tencent/wechat_open_sdk';
import { DiamondViewModel } from '../../../../viewModel/DiamondViewModel';
import { LoadingDialog } from '../../../../dialog/LoadingDialog';
import { DiamondDetailEntity } from '../../../../entity/DiamondDetailEntity';
import { DiamondItemView } from '../../../../view/DiamondItemView';
import { DiamondRuleDialog } from '../../../../dialog/DiamondRuleDialog';
import { EventReportGlobalManager } from '../../../../manager/EventReportGlobalManager';
import { EventConstants } from '../../../../common/EventConstants';
import { OrderEntity } from '../../../../entity/OrderEntity';
import { TipDialog } from '../../../../dialog/TipDialog';

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

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

  diamondRuleDialogController?: CustomDialogController | null;

  viewModel: DiamondViewModel = new DiamondViewModel(this.getUIContext());
  orderEntity?: PayOrderEntity;

  //从微信返回的回调
  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.PAY_CANCEL,
          `weixin:${this.origin}`, `{type:\"diamond\", orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.diamondInfo)}}`
        )
      }
    }
    LoadingDialog.dismiss();
  }

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

  @Monitor('viewModel.goodsList')
  onGoodsListChange(monitor: IMonitor) {
    const list = monitor.value()?.now as Array<VipMealEntity>;
    this.diamondList = list.map(item => ObjectUtil.assign(new VipMealEntity(), item) as VipMealEntity);
    if (this.diamondList.length > 0) {
      this.vipMeal = this.diamondList.find(item => item.checked === true);
      if (!this.vipMeal) {
        this.vipMeal = this.diamondList[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:${this.origin}`, `{type:\"diamond\", orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.diamondInfo)}}`
      )
      this.viewModel.getDiamondInfo()
    }
  }

  aboutToAppear() {
    WXEventHandler.registerOnWXRespCallback(this.onWXResp)
    this.initParams();
    this.viewModel.getDiamondInfo()
    this.viewModel.mealList();
  }

  aboutToDisappear() {
    WXEventHandler.unregisterOnWXRespCallback(this.onWXResp)
    this.diamondRuleDialogController = null
    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;
    }
  }

  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:${this.origin}`, `{type:\"diamond\", orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.diamondInfo)}}`
      )
    } else {
      ToastUtils.show('支付失败');
      EventReportGlobalManager.eventReport(
        EventConstants.ERROR_CLIENT_ALIPAY_ERR,
        `{orderId:${this.orderEntity?.orderId}, meal:${JSON.stringify(this.diamondInfo)}}`, resultStatus
      )
    }
  }

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

  showRuleDialog() {
    this.diamondRuleDialogController = new CustomDialogController({
      builder: DiamondRuleDialog(),
      width: '100%',
      cornerRadius: 20,
      maskColor: '#CC000000',
      levelMode: LevelMode.EMBEDDED,
      backgroundBlurStyle: BlurStyle.NONE,
      alignment: DialogAlignment.Bottom
    })
    this.diamondRuleDialogController.open();
  }

  build() {
    Stack({alignContent: Alignment.Top}) {
      Column() {
        Scroll() {
          Stack({alignContent: Alignment.Top}) {
            Image($r('app.media.ic_diamond_top_bg')).width('100%').aspectRatio(1.524)

            Column() {
              RelativeContainer() {
                Image(StrUtil.isNotEmpty(LoginManager.getUserInfo()?.avater) ? LoginManager.getUserInfo()?.avater : $r('app.media.ic_default_avatar'))
                  .width(46)
                  .height(46)
                  .borderRadius(25)
                  .margin({ left: 4 })
                  .id('iv_avatar')
                Text(LoginManager.getUserInfo()?.vip === 1 ? '非会员' : LoginManager.getUserInfo()?.vip === 3 ? '终身会员' : LoginManager.getUserInfo()?.vip_name)
                  .fontColor(Color.White)
                  .fontSize(10)
                  .textAlign(TextAlign.Center)
                  .width(46)
                  .height(16)
                  .borderRadius(3)
                  .backgroundColor('#F94747')
                  .alignRules({
                    top: { anchor: 'iv_avatar', align: VerticalAlign.Bottom },
                    left: { anchor: 'iv_avatar', align: HorizontalAlign.Start },
                    right: { anchor: 'iv_avatar', align: HorizontalAlign.End }
                  })
                  .margin({ top: -9 })
                Text(LoginManager.getUserInfo()?.name)
                  .fontColor(Color.White)
                  .fontSize(15)
                  .fontWeight(FontWeight.Medium)
                  .alignRules({
                    top: { anchor: 'iv_avatar', align: VerticalAlign.Top },
                    bottom: { anchor: 'iv_avatar', align: VerticalAlign.Center },
                    left: { anchor: 'iv_avatar', align: HorizontalAlign.End }
                  })
                  .margin({ left: 12 })
                  .id('tv_username')
                Text('ID:' + LoginManager.getUserInfo()?.user_id).fontColor(Color.White).fontSize(12)
                  .alignRules({
                    left: { anchor: 'tv_username', align: HorizontalAlign.Start },
                    top: { anchor: 'iv_avatar', align: VerticalAlign.Center },
                    bottom: { anchor: 'iv_avatar', align: VerticalAlign.Bottom }
                  })

                Column() {
                  Text() {
                    Span(`${this.diamondInfo?.remain}`).fontSize(22).fontFamily('ddp500m')
                    Span(' 次').fontSize(12)
                  }.fontColor(Color.White)
                  Text('剩余总次数').fontColor(Color.White).fontSize(12)
                }
                .alignRules({
                  top: { anchor: 'iv_avatar', align: VerticalAlign.Top },
                  right: { anchor: '__container__', align: HorizontalAlign.End },
                  bottom: { anchor: 'iv_avatar', align: VerticalAlign.Bottom }
                })
              }
              .aspectRatio(2.584)
              .margin({ top: 120, left: 26, right: 26 })
              .padding({ top: 16, left: 12, right: 12 })
              .backgroundImage($r('app.media.ic_diamond_vip_bg1'))
              .backgroundImageSize({ width: '100%' })

              Image($r('app.media.ic_diamond_vip_bg2')).width('100%').aspectRatio(4.866)
                .margin({ top: -45 })

              Column() {
                Text('M币消耗数量').fontColor($r('app.color.color_1a1a1a')).fontSize(16).fontWeight(FontWeight.Medium).margin({ top: 4 })

                Column() {
                  Row() {
                    Text('本月固定M币数量').fontColor($r('app.color.color_1a1a1a')).fontSize(14)
                    Text('每月重置')
                      .textAlign(TextAlign.Center)
                      .fontColor('#5B70F6')
                      .fontSize(12)
                      .height(18)
                      .padding({ left: 4, right: 4 })
                      .borderWidth(1)
                      .borderRadius(4)
                      .borderColor('#5B70F6')
                      .margin({left: 8})
                    Blank().layoutWeight(1)
                    Text() {
                      Span(`${this.diamondInfo?.month_used}`).fontColor('#5B70F6').fontSize(20).fontFamily('ddp500m')
                      Span(`/${this.diamondInfo?.month_total}`).fontColor($r('app.color.color_1a1a1a')).fontSize(14)
                    }
                  }

                  Progress({ value: this.diamondInfo?.month_used, total: this.diamondInfo?.month_total, type: ProgressType.Linear })
                    .width('100%')
                    .height(10)
                    .style({ strokeWidth: 10, strokeRadius: 5 })
                    .color('#5C6FF6')
                    .borderRadius(5)
                    .margin({top: 16})

                  Row() {
                    Text('兑换M币数量').fontColor($r('app.color.color_1a1a1a')).fontSize(14)
                    Text('用完即止')
                      .textAlign(TextAlign.Center)
                      .fontColor('#5B70F6')
                      .fontSize(12)
                      .height(18)
                      .padding({ left: 4, right: 4 })
                      .borderWidth(1)
                      .borderRadius(4)
                      .borderColor('#5B70F6')
                      .margin({left: 8})
                    Blank().layoutWeight(1)
                    Text() {
                      Span(`${this.diamondInfo?.buy_used}`).fontColor('#5B70F6').fontSize(20).fontFamily('ddp500m')
                      Span(`/${this.diamondInfo?.buy_total}`).fontColor($r('app.color.color_1a1a1a')).fontSize(14)
                    }
                  }.margin({top: 24})

                  Progress({ value: this.diamondInfo?.buy_used, total: this.diamondInfo?.buy_total, type: ProgressType.Linear })
                    .width('100%')
                    .height(10)
                    .style({ strokeWidth: 10, strokeRadius: 5 })
                    .color('#FF9026')
                    .borderRadius(5)
                    .margin({top: 16})
                }
                .backgroundColor(Color.White)
                .borderRadius(8)
                .margin({ top: 10 })
                .padding({
                  left: 12,
                  top: 16,
                  right: 12,
                  bottom: 16
                })
              }
              .alignItems(HorizontalAlign.Start)
              .height('auto')
              .padding(10)
              .margin({ top: -45, left: 16, right: 16 })
              .backgroundImage($r('app.media.ic_diamond_used_count_bg'))
              .backgroundImageSize({ width: '100%' })
              .borderRadius(10)
              .clip(true)

              Text('M币套餐').fontColor($r('app.color.color_1a1a1a')).fontSize(16).fontWeight(FontWeight.Medium).margin({left: 16, top: 26})
                .alignSelf(ItemAlign.Start)

              List({space: 12}) {
                ForEach(this.diamondList, (item: VipMealEntity) => {
                  ListItem() {
                    DiamondItemView({ goodInfo: item })
                  }
                  .onClick(() => {
                    let goodsInfo = this.diamondList.find(item => item.checked) as VipMealEntity
                    goodsInfo.checked = false
                    item.checked = true
                    this.vipMeal = item
                    this.releasePayType()
                  })
                })
              }
              .width('auto')
              .height('auto')
              .margin({left: 16, top: 14, right: 16, bottom: 15 })
            }
          }
        }
        .layoutWeight(1)
        .scrollBar(BarState.Off)

        Column() {
          Row() {
            Row() {
              Image($r('app.media.ic_wx_pay3')).width(26).height(26)
              Text('微信').fontColor($r('app.color.color_1a1a1a')).fontSize(15).margin({left: 10})
              Blank().layoutWeight(1)
              Image(this.payType === 0 ? $r('app.media.ic_check_true') : $r('app.media.ic_check_false')).width(18).height(18)
            }.layoutWeight(1)
            .visibility(this.vipMeal?.pay_type.includes('weixin') ? Visibility.Visible : Visibility.None)
            .onClick(() => {
              this.payType = 0;
            })
            Divider().width(1).strokeWidth(1).height(26).color('#EEEEEE').margin({left: 20, right: 20})
            Row() {
              Image($r('app.media.ic_ali_pay3')).width(26).height(26)
              Text('支付宝').fontColor($r('app.color.color_1a1a1a')).fontSize(15).margin({left: 10})
              Blank().layoutWeight(1)
              Image(this.payType === 1 ? $r('app.media.ic_check_true') : $r('app.media.ic_check_false')).width(18).height(18)
            }.layoutWeight(1)
            .visibility(this.vipMeal?.pay_type.includes('alipay') ? Visibility.Visible : Visibility.None)
            .onClick(() => {
              this.payType = 1;
            })
          }

          Button('立即支付', {type: ButtonType.Capsule, stateEffect: true})
            .width('100%')
            .height(46)
            .fontColor(Color.White)
            .fontSize(16)
            .fontWeight(FontWeight.Medium)
            .backgroundColor('#5C6FF6')
            .margin({top: 17})
            .onClick(() => {
              if (this.vipMeal) {
                this.createOrder()
              }
            })
        }.backgroundColor(Color.White)
        .padding({left: 16, top: 8, right: 16, bottom: 30})
        .shadow({radius: 6, offsetY: -2, color: '#1d000000'})
      }

      TitleBar({
        title: '次数兑换',
        isDark: false,
        rightText: '规则说明',
        rightColor: $r('app.color.color_1a1a1a'),
        onRightClick: () => {
          this.showRuleDialog()
        }
      }).id('titleBar')
    }
    .width('100%')
    .height('100%')
    .backgroundColor(Color.White)
  }
}