import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import * as Parse from "parse";
import { HttpClient } from "@angular/common/http";
import { Router } from "@angular/router";
import { catchError } from "rxjs/operators";
import { LoadingController, ToastController, Platform,IonicModule } from '@ionic/angular';
import { Wechat } from "@ionic-native/wechat/ngx";
import { NavComponent } from '../../../app/components/nav/nav.component';
declare var wx: any;

@Component({
	selector: 'app-recharge',
	templateUrl: './recharge.component.html',
	styleUrls: ['./recharge.component.scss'],
	standalone: true,
  imports: [IonicModule,NavComponent,FormsModule],
})
export class RechargeComponent implements OnInit {
	constructor(private http: HttpClient, public toastController: ToastController,
		public loadingController: LoadingController,
		// private wxSDK: Wechat,
		private router: Router,
		private platform: Platform,
	) { }
	price: any = 0
	loading: any
	company = localStorage.getItem('company')
	account?: Parse.Object
	public modal: boolean = false
	public method: any = { value: 'wx', name: '微信支付' }
	public alertInputs = [
    {
      label: '微信支付',
      type: 'radio',
      value: 'wx',
    },
    {
      label: '其他支付',
      type: 'radio',
      value: 'zfb',
    },
  ];
	public alertButtons = [
    {
      text: 'Cancel',
      role: 'cancel',
      handler: () => {
        console.log('Alert canceled');
      },
    },
    {
      text: 'OK',
      role: 'confirm',
      handler: () => {
        this.confirmRechare()
      },
    },
  ];
	public data: Array<object> = [
		{ value: 'wx', name: '微信支付', icon: 'https://file-cloud.fmode.cn/uiZD6NisQm/20220810/kvp1el034906.png' },
		{ value: 'zfb', name: '其他支付', icon: 'https://file-cloud.fmode.cn/uiZD6NisQm/20220810/6pr338034905.png' }
	];
	wxpayEnabled = false;
	wxAppId = "";
	ngOnInit() {
		let ua = navigator.userAgent.toLowerCase();
		let isWeixin = ua.indexOf('micromessenger') != -1;
		if (isWeixin) {
			this.getWXSignPackageInWechat();
		}
		this.getAccount()
	}


	// 获取微信签名
	getWXSignPackageInWechat() {
		let that = this;
		let params = {
			company: localStorage.getItem("company"),
			href: encodeURIComponent(location.href.split("#")[0]),
		};
		this.http
			.post(`https://test.fmode.cn/api/wechat/getconfig`, params)
			.subscribe((response) => {
				// 返回的签名信息
				let res: any = response;
				const signPackage = res.data;
				that.wxAppId = signPackage.appid;
				this.wxpayEnabled = true;
				wx.config({
					debug: false, // 开启调试模式
					appId: signPackage.appid, // 必填，公众号的唯一标识
					timestamp: signPackage.timestamp, // 必填，生成签名的时间戳
					nonceStr: signPackage.nonceStr, // 必填，生成签名的随机串
					signature: signPackage.signature, // 必填，签名，见附录1
					jsApiList: [
						"chooseWXPay", // JSAPI微信支付
					], // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
				});
				wx.ready(() => { });
				wx.error(() => { });
			});
	}

	back() {
		history.back();
	}
	async getAccount() {
		let Account = new Parse.Query("Account")
		Account.include("user")
		Account.equalTo("user", Parse.User.current()?.id)
		this.account = await Account.first()
		console.log(this.account);
	}

	onChange(event:any){
		this.method = JSON.parse(JSON.stringify(event))
		console.log(this.method);
	}


	async showPay() {
		if (this.price <= 0 || isNaN(this.price)) {
			return this.presentToast(`充值错误，请重新确认充值金额！`, 1500, "danger");
		}
		if (this.price > 100000) {
			return this.presentToast('单笔充值最多不超过100000元！', 1500, 'danger')
		}
		this.modal = true
		this.price = parseInt(this.price)
	}

	async confirmRechare() {
		let now = new Date();
		let tradeNo = "C" +
			String(now.getFullYear()) +
			(now.getMonth() + 1) +
			now.getDate() +
			now.getHours() +
			now.getMinutes() +
			now.getSeconds() +
			Math.random().toString().slice(-6); //生成六位随机数
		console.log('订单编号：', tradeNo);
		console.log(this.method.value);

		// if (this.method.value == 'outline') {
		// 	await this.updataOrder(tradeNo, 'outline')
		// 	this.presentToast(`请选择支付方式`, 1500, "success");
		// 	return
		// } else 
		if (this.method.value == 'wx') {
			let ua = navigator.userAgent.toLowerCase();

			let isWeixin = ua.indexOf('micromessenger') != -1;
			if (isWeixin) { // 微信支付
				await this.wxPay(tradeNo)
			} else if (this.platform.is("cordova")) { // APP 调起微信支付
				this.presentToast(`APP内暂不支持微信支付请前往微信端网页进行支付`, 3000, "success");
				return
				await this.openWxPay(tradeNo)
			} else {
				this.presentToast(`微信支付请在微信进入应用`, 1500, "success");
			}
		} else {
			this.presentToast(`待开通支付通道`, 1500, "success");
		}
	}

	// 调起微信支付
	async openWxPay(tradeNo:string) {
		let loading = await this.loadingController.create({
			cssClass: "my-custom-class",
			message: "支付跳转...",
			duration: 1500,
		});
		loading.present();
		let params = {
			company: this.company,
			out_trade_no: tradeNo,
			total_fee: this.price,
		};
		try {
			this.http
				.post(`https://server.fmode.cn/api/wxpay/newsdkorder`, params)
				.pipe(
					catchError(async (e) => { // 显示报错
						loading.present();
						await this.presentToast(`服务器请求错误，请稍后重试`, 1500, "danger");
					})
				)
				.subscribe(async (response) => {
					let payParams: any = response;
					console.log(payParams);

					// this.wxSDK
					// 	.sendPaymentRequest({
					// 		appid: payParams.appid, // merchant id
					// 		partnerid: payParams.partnerid, // merchant id
					// 		prepayid: payParams.prepayid, // prepay id
					// 		package: payParams.package, // nonce
					// 		noncestr: payParams.noncestr, // nonce
					// 		timestamp: payParams.timestamp, // timestamp
					// 		sign: payParams.sign, // signed string
					// 	})
					// 	.then(async (data) => {
					// 		if (data) {
					// 			loading.present();
					// 			console.log('支付成功返回结果：', data);
					// 			await this.updataOrder(tradeNo, '微信')
					// 		}
					// 	})
					// 	.catch(async (error) => {
					// 		loading.present();
					// 		await this.presentToast(`支付失败`, 1500, "danger");
					// 		console.log('调起微信失败', error);
					// 	});
				});
		} catch (error) {
			loading.present();
			await this.presentToast(`支付失败`, 1500, "danger");
			console.log(error);
		}
	}



	// 微信浏览器内支付
	async wxPay(tradeNo:string) {
		let openid = localStorage.getItem('openid')
		if (openid) {
			let params = {
				company: this.company,
				out_trade_no: tradeNo,
				total_fee: this.price,
				openid: openid,
				appid: "wxb4579e09e263afa9"
			};
			let that = this
			this.http
				.post(`https://test.fmode.cn/api/wxpay/neworder`, params)
				.subscribe(async (response) => {
					let accountLog: any = await this.updataOrder(tradeNo, '微信')
					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) {
								accountLog.set("isVerified", true)
								await accountLog.save()
								that.presentToast(`充值成功`, 1500, "success");
								that.modal = false
								that.price = 0
							}
						},
					});
				});
		}


	}

	async presentToast(title:string, time:number, color:string) {
		const toast = await this.toastController.create({
			message: title,
			duration: time,
			color: color
		});
		toast.present();
	}
	//充值记录
	async updataOrder(tradeNo:string, type:string) {
		let AccountLog = Parse.Object.extend('AccountLog')
		let account = new AccountLog()
		account.set("isVerified", false)
		account.set("company", {
			__type: "Pointer",
			className: "Company",
			objectId: this.company
		})
		account.set("targetAccount", {
			__type: "Pointer",
			className: "Account",
			objectId: this.account?.id
		})
		account.set("fromName", "system")
		account.set("fromAccountName", "system")
		account.set("orderNumber", tradeNo)
		account.set("desc", `${type}充值${this.price}`)
		account.set("assetType", 'balance')
		account.set("orderType", `${type}recharge`)
		account.set("assetCount", this.price)
		account.save().then((res: any) => {
			return res
			// res.set("isVerified", true)
			// res.save().then(res => {
			// 	this.presentToast(`充值成功`, 1500, "success");
			// 	this.modal = false
			// 	this.price = 0
			// })
		})
	}

	onClose() {
		this.modal = false;
	}
}
