import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import { AlertController, IonicModule, ToastController } from '@ionic/angular';
import { ActivatedRoute } from '@angular/router';
import { AccountService } from '../../../services/account.service';
import { HttpClient } from '@angular/common/http';
declare var wx: any;

@Component({
  selector: 'app-pay-comp',
  templateUrl: './pay-comp.component.html',
  styleUrls: ['./pay-comp.component.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule],
})
export class PayCompComponent implements OnInit {
  @Input('price') price!: number;
  @Input('tradeNo') tradeNo: string = 'C20241215050401'; //支付单号
  @Output() onChange: EventEmitter<any> = new EventEmitter<any>();
  isOpen: boolean = true; //打开弹窗
  checkpay: string = 'wxpay';
  userAgent?: string; //获取当前浏览器环境

  constructor(
    private accServ: AccountService,
    private toastController: ToastController,
    private alertCtrl: AlertController,
    private http: HttpClient,
    private activRoute: ActivatedRoute
  ) {}

  ngOnInit() {
    this.activRoute.paramMap.subscribe((params) => {
      let ua = navigator.userAgent.toLowerCase();
      if (ua.indexOf('micromessenger') != -1) {
        this.userAgent = 'weixin';
        this.accServ.getWXSignPackageInWechat();
      } else if (ua.indexOf('windows') != -1 || ua.indexOf('Macintosh') != -1) {
        this.userAgent = 'pc';
      }
    });
  }
  onchangPay(val: string) {
    this.checkpay = val;
    console.log(val);
  }
  async showCodeModal(type: string) {
    switch (type) {
      case 'wxpay':
        this.openWxPay();
        break;
      default:
        break;
    }
  }
  /* 校验支付方式 */
  openWxPay() {
    let ua = navigator.userAgent.toLowerCase();
    let isWeixin = ua.indexOf('micromessenger') != -1;
    if (isWeixin) {
      //JSAPI 支付
      this.wxPayH5();
    } else {
      this.wxPay();
    }
  }
  /* pc端支付 */
  async wxPay() {
    this.tradeNo = this.accServ.setTradeNo();
    // this.navCtrl.navigateRoot('account/payment');
    //console.log(this.company, this.tradeNo);
    let params = {
      company: this.accServ.company,
      out_trade_no: this.tradeNo,
      total_fee: this.price,
      body: '充值',
    };
    try {
      let _this = this;
      Parse.Cloud.run('pay_code2', params).then(async (res) => {
        let nonce_str = res.nonce_str;
        let codeLink = res.code_url[0];
        let order = await this.accServ.setOrder('service', {
          out_trade_no: this.tradeNo,
          payType: 'wxpay-pc',
          total_fee: this.price,
          code: codeLink,
        });
        window.open(
          `${location.protocol}//${location.host}/account/payment/${order.objectId}/${nonce_str}`
        );
        this.isOpen = false;
      });
    } catch (error) {
      alert(error);
    }
  }
  isDisabled: boolean = false; //防抖

  /* h5环境 */
  async wxPayH5() {
    if (this.isDisabled) return;
    try {
      this.isDisabled = true;
      this.tradeNo = this.accServ.setTradeNo();
      //console.log(this.company, this.tradeNo);
      let wechat = Parse.User.current()?.get('wechat');
      let openid =
        localStorage.getItem('openid') || wechat['wxb4193c93ae9aa696']?.openid;
      if (openid) {
        let params = {
          company: this.accServ.company,
          out_trade_no: this.tradeNo,
          total_fee: +this.price,
          openid: openid,
          appid: 'wxb4193c93ae9aa696',
        };
        await this.accServ.setOrder('service', {
          out_trade_no: this.tradeNo,
          payType: 'wxpay-h5',
          total_fee: this.price,
        });
        let _this = this;
        this.http
          .post(`https://server.fmode.cn/api/wxpay/neworder`, params)
          .subscribe((response) => {
            let payinfo: any = response;
            wx.chooseWXPay({
              timestamp: payinfo.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
              nonceStr: payinfo.nonceStr, // 支付签名随机串，不长于 32 位
              package: payinfo.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
              signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
              paySign: payinfo.paySign, // 支付签名
              success: async (res: any) => {
                // 支付成功后的回调函数
                if (res) {
                  let info = {
                    out_trade_no: _this.tradeNo,
                    nonce_str: payinfo.nonceStr,
                    company: this.accServ.company,
                  };

                  // this.accServ.saveAccountLog(info, _this.order.objectId, _this.company, _this.message);
                  _this.toast('支付成功', 'success');
                  _this.isOpen = false;
                }
              },
            });
            this.isDisabled = false;
          });
      } else {
        // alert('缺少openid,请重新登录')
        this.isDisabled = false;
        let alert = await this.alertCtrl.create({
          header: '提示',
          subHeader: '',
          message: '缺少openid,请刷新页面或重新登录',
          buttons: [
            {
              role: 'ok',
              text: '确认',
              handler: () => {
                location.reload();
              },
            },
          ],
        });
        alert.present();
      }
    } catch (err: any) {
      this.isDisabled = false;
      let alert = await this.alertCtrl.create({
        header: '异常错误',
        subHeader: '',
        message: err.message,
        buttons: [
          {
            role: 'ok',
            text: '确认',
            handler: () => {},
          },
        ],
      });
      alert.present();
    }
  }

  onClose() {
    this.isOpen = false;
    const result = {
      code: 0,
      type: this.checkpay,
    };
    this.onChange.emit(result);
  }
  async toast(text: string, type?: string) {
    const toast = await this.toastController.create({
      message: text,
      color: type ?? 'warning',
      duration: 1500,
    });
    toast.present();
  }
}
