import util from '@ohos.util';
import wantConstant from '@ohos.app.ability.wantConstant';
import Url from '@ohos.url';
import router from '@ohos.router';
import { UPHttpManager } from './network/UPHttpManager';
import * as UPHttpRequest from './network/UPHttpRequest';
import UPUtil from './utils/UPUtil';
import UPLogger from '../ets/utils/UPLogger';
import UPWebPage from './pages/UPWebPage';
import UPConstant from './common/UPConstant';
import UPPayEncrypt from './utils/UPPayEncrypt';
import UPSysInfoUtil from './utils/UPSysInfoUtil';
export var UPPayResultStatus;
(function (a10) {
    a10[a10["SUCCESS"] = 0] = "SUCCESS";
    a10[a10["FAIL"] = 1] = "FAIL";
    a10[a10["CANCEL"] = 2] = "CANCEL";
})(UPPayResultStatus || (UPPayResultStatus = {}));
export class UPPayment {
    constructor() {
        this.configHandled = false;
    }
    startPay(n9, o9, p9, q9, r9) {
        if (n9 && o9 && p9) {
            this.configHandled = false;
            UPUtil.getApplicationContext().eventHub.off(UPConstant.WEB_PAYRESULT_NOTIFICATION + n9);
            UPUtil.getApplicationContext().eventHub.on(UPConstant.WEB_PAYRESULT_NOTIFICATION + n9, (z9) => {
                this.sendWebPayResult(p9, q9, z9);
            });
            let s9 = setTimeout(() => {
                this.getLocalConfig(r9).then((y9) => {
                    this.handleConfig(n9, o9, p9, y9, q9);
                }).catch((x9) => {
                    UPLogger.error('处理本地Config失败:' + JSON.stringify(x9));
                });
                UPLogger.info("getRemoteConfig超时");
            }, 800);
            this.getRemoteConfig(s9, n9, o9, p9, q9, r9);
        }
    }
    async getRemoteConfig(r8, s8, t8, u8, v8, w8) {
        UPLogger.info('进入getRemoteConfig');
        try {
            let y8 = await UPHttpRequest.getConfigReqMsg(s8, t8, w8);
            let z8;
            let a9;
            let b9 = new UPHttpManager();
            b9.sendPostRequest(y8).then((h9) => {
                a9 = h9;
                let i9 = new util.Base64Helper();
                let j9 = i9.decodeSync(h9.configs);
                let k9 = util.TextDecoder.create('utf-8');
                let l9 = k9.decodeWithStream(j9);
                z8 = JSON.parse(l9);
                l9 = l9 + s8;
                let m9 = UPUtil.verifySign(t8, l9, h9.sign);
                return m9;
            }).then(() => {
                UPLogger.info('getRemoteConfig验签成功');
                clearTimeout(r8);
                a9.tn = s8;
                a9.mode = t8;
                let g9 = JSON.stringify(a9);
                this.handleConfig(s8, t8, u8, z8, v8);
                UPUtil.writeDataToFile(g9, UPUtil.configPath(w8));
            }).catch((f9) => {
                UPLogger.error('getRemoteConfig失败，失败原因：' + JSON.stringify(f9));
            });
        }
        catch (x8) {
            UPLogger.error('getRemoteConfig失败，失败原因：' + JSON.stringify(x8));
        }
    }
    async getLocalConfig(x7) {
        UPLogger.info('进入getLocalConfig');
        let y7 = '[{\"package_info\":[{\"schema\":\"uppaywallet:\/\/\",\"package\":\"com.unionpay.hmos.wallet\",\"sort\":100},{\"schema\":\"uppayvendor:\/\/\",\"package\":\"com.huawei.hmos.wallet\",\"sort\":101}],\"sort\":100,\"type\":\"app\"}]';
        let z7 = UPUtil.readDataFromFile(UPUtil.configPath(x7));
        if (z7) {
            try {
                let h8 = JSON.parse(z7);
                let i8 = new util.Base64Helper();
                let j8 = i8.decodeSync(h8.configs);
                let k8 = util.TextDecoder.create('utf-8');
                let l8 = k8.decodeWithStream(j8);
                let m8;
                m8 = JSON.parse(l8);
                if (m8 !== null && m8 !== undefined && typeof m8 === 'object') {
                    let n8 = h8.tn;
                    let o8 = h8.mode;
                    let p8 = h8.sign;
                    let q8 = l8 + n8;
                    await UPUtil.verifySign(o8, q8, p8);
                    z7 = l8;
                    UPLogger.info('解析localConfigStr成功');
                }
                else {
                    z7 = y7;
                    UPLogger.error('解析localConfigStr失败');
                }
            }
            catch (g8) {
                z7 = y7;
                UPLogger.error('解析localConfigStr失败，原因：' + JSON.stringify(g8));
            }
        }
        else {
            z7 = y7;
            UPLogger.error('解析localConfigStr失败');
        }
        let a8 = new Array();
        let b8;
        try {
            a8 = JSON.parse(z7);
        }
        catch (f8) {
            b8 = f8;
            UPLogger.error('解析localConfigStr失败，原因：' + JSON.stringify(f8));
        }
        return new Promise((d8, e8) => {
            if (b8) {
                e8(b8);
            }
            else {
                d8(a8);
            }
        });
    }
    async handleConfig(m7, n7, o7, p7, q7) {
        if (this.configHandled) {
            return;
        }
        this.configHandled = true;
        p7.sort((v7, w7) => v7.sort - w7.sort);
        for (let s7 = 0; s7 < p7.length; s7++) {
            let t7 = p7[s7];
            if (t7.type === 'app') {
                UPLogger.info('进入 app type');
                try {
                    await this.handlePackageInfos(q7, t7, m7, n7, o7);
                    UPLogger.info('open app成功');
                    return;
                }
                catch (u7) {
                    UPLogger.info('open app失败，失败原因：' + JSON.stringify(u7));
                }
            }
            else if (t7.type === 'link') {
                UPLogger.info('进入 link type');
                this.openLink(m7, t7.url);
                return;
            }
            else if (t7.type === 'wap') {
                UPLogger.info('进入 wap type');
                this.openWapPay(m7, n7, t7.url);
                return;
            }
        }
    }
    async handlePackageInfos(v6, w6, x6, y6, z6) {
        let a7 = undefined;
        let b7 = false;
        if (w6.package_info) {
            let f7 = w6.package_info;
            f7.sort((k7, l7) => k7.sort - l7.sort);
            for (let h7 = 0; h7 < f7.length; h7++) {
                let i7 = f7[h7];
                try {
                    await this.openAppPay(v6, i7, x6, y6, z6, w6.app_server);
                    b7 = true;
                    break;
                }
                catch (j7) {
                    a7 = j7;
                }
            }
        }
        else {
            a7 = {
                code: UPConstant.PARAM_ERROR_CODE,
                name: UPConstant.ERROR_NAME,
                message: UPConstant.PARAM_ERROR_MSG
            };
        }
        return new Promise((d7, e7) => {
            if (b7) {
                d7();
            }
            else {
                e7(a7);
            }
        });
    }
    openAppPay(j6, k6, l6, m6, n6, o6) {
        let p6 = {
            tn: l6,
            mode: m6,
            bundleName: UPSysInfoUtil.systemBundleName(),
            fromScheme: n6,
            server: o6,
        };
        let q6 = JSON.stringify(p6);
        let r6 = UPPayEncrypt.encryptPayData(q6);
        let s6 = r6.split('&');
        let t6 = UPUtil.toCorrectScheme(k6.schema) + 'uppay?paydata=' + s6[0] + '&s=' + s6[1];
        let u6 = {
            deviceId: '',
            bundleName: k6.package,
            uri: t6,
            flags: wantConstant.Flags.FLAG_START_WITHOUT_TIPS
        };
        return j6.startAbility(u6);
    }
    openWapPay(d6, e6, f6) {
        if (f6) {
            let g6 = UPUtil.strToHexStr(d6);
            let h6 = UPUtil.rsaEncryptMsg(e6, g6);
            let i6 = f6 + '?s=' + h6;
            router.pushNamedRoute({
                name: UPWebPage,
                params: {
                    webSrc: i6,
                    tn: d6,
                }
            });
        }
    }
    openLink(a6, b6) {
        let c6 = '';
        if (b6) {
            c6 = b6;
        }
        router.pushNamedRoute({
            name: UPWebPage,
            params: {
                webSrc: c6,
                tn: a6,
            }
        });
    }
    sendWebPayResult(q5, r5, s5) {
        let t5 = s5['code'] ? s5['code'] : '';
        let u5 = s5['data'] ? s5['data'] : '';
        let v5 = UPUtil.toCorrectScheme(q5) + 'uppayresult?code=' + t5 + '&data=' + u5;
        let w5 = {
            deviceId: '',
            bundleName: UPSysInfoUtil.systemBundleName(),
            uri: v5,
            flags: wantConstant.Flags.FLAG_START_WITHOUT_TIPS
        };
        r5.startAbility(w5).then(() => {
            UPLogger.info('sendWebPayResult成功');
        }).catch((z5) => {
            UPLogger.error('sendWebPayResult失败，原因' + JSON.stringify(z5));
        });
    }
    handlePaymentResult(i5, j5) {
        UPLogger.info('解析支付结果');
        let k5 = {};
        try {
            let m5 = Url.URL.parseURL(i5);
            let n5 = new Url.URLParams(m5.search.slice(1));
            let o5 = n5.get('code');
            let p5 = n5.get('data');
            k5.data = p5;
            switch (o5) {
                case 'fail':
                    k5.code = UPPayResultStatus.FAIL;
                    break;
                case 'success':
                    k5.code = UPPayResultStatus.SUCCESS;
                    break;
                case 'cancel':
                    k5.code = UPPayResultStatus.CANCEL;
                    break;
                default:
                    k5.code = UPPayResultStatus.CANCEL;
                    break;
            }
        }
        catch (l5) {
            k5.code = UPPayResultStatus.FAIL;
            UPLogger.error('支付结果解析失败,原因：' + JSON.stringify(l5));
        }
        if (j5) {
            j5(k5);
        }
    }
}
