const system = require("../../system");
const ServiceBase = require("../sve.base");
const settings = require("../../../config/settings");
const moment = require('moment');
const axios = require("axios");
const md5 = require("MD5");

class QbgconfigService extends ServiceBase {
    constructor() {
        super(ServiceBase.getDaoName(QbgconfigService));
        this.econtractDao = system.getObject("db.econtractDao")
        this.userDao = system.getObject("db.userDao")
        this.usereaccountDao = system.getObject("db.usereaccountDao")
        this.API = settings.signApi();
        this.restClient = system.getObject("util.restClient");
        this.EXCEPT_KEYS = ['sign', 'requestid', 'simpleFormFields'];
        this.redisClient = system.getObject("util.redisClient");
    }


    /**
     * 静默签 带三要素验证
     * @param {ecid, appId, userId, idName, mobile, idNo, bankno, nonceStr, sign} params
     */
    async autoSign(params, qbg) {
        let ecid = params.ecid;
        // 验证身份证是否签约过
        let todays = moment().format("YYYY-MM-DD") + " 00:00:00";
        let contractId = await this.econtractDao.findSignedContractId({
            idno: params.idNo,
            ecid: ecid,
            today: todays
        }) || 0;

        if (contractId) {
            return this.returnjson(0, "用户已经签约", {
                contractId: contractId
            });
        }
        //1、三要素验证
        var bankthreeParamss = {
            appId: params.appId,
            timestamp: new Date().getTime(),
            nonceStr: params.nonceStr,
            idName: params.idName,
            idNo: params.idNo,
            bankNo: params.bankno
        }
        bankthreeParamss.sign = await this.getsign(bankthreeParamss, qbg.key);
        let bankthrees = await axios({
            method: 'post',
            url: this.API.bankThree,
            data: bankthreeParamss,
        });

        console.log("三要素收费三要素请求返回===================================================", bankthrees);
        if (bankthrees.data.status == 0 && !bankthrees.data.data.pass) {
            return this.returnjson(-1, bankthrees.data.msg);
        }


        //2、 创建账户--p_user
        var unionId = params.appId + "_" + params.ecid + "_" + params.userId;
        var user = await this.userDao.findOne({
            unionId: unionId,
        });
        if (!user) {
            user = await this.userDao.create({
                appkey: params.appId,
                unionId: unionId,
                userId3rd: params.userId,
                userName: params.idName,
                mobile: params.mobile,
                utype: 0,
            });
        }

        // p_user_eaccount
        var eaccount = await this.usereaccountDao.findOne({
            user_id: user.id,
            personsSign: params.idNo,
        }) || {};

        eaccount.user_id = user.id;
        eaccount.userName = params.idName;
        eaccount.mobile = params.mobile;
        eaccount.bankno = params.bankno;
        eaccount.personsSign = params.idNo;
        if (eaccount.id) {
            await eaccount.save();
        } else {
            eaccount = await this.usereaccountDao.create(eaccount);
        }
        //创建账户
        if (eaccount.id && !eaccount.esign_account) {
            var createAccount = {
                appId: params.appId,
                timestamp: new Date().getTime(),
                nonceStr: params.nonceStr,
                idName: params.idName,
                idNo: params.idNo,
                mobile: params.mobile
            }
            createAccount.sign = await this.getsign(createAccount, qbg.key);

            let qbgaccount = await axios({
                method: 'post',
                url: this.API.createAccount,
                data: createAccount,
            });

            console.log(qbgaccount)
            if (qbgaccount.data.status == 0 && !qbgaccount.data.data.accountId) {
                return this.returnjson(-1, bankthrees.data.msg);
            }
            eaccount.esign_account = qbgaccount.data.data.accountId;
            eaccount.save();
        }


        var today = moment().format("YYYY-MM-DD")

        //发起签署
        var toecontract = {
            appId: params.appId,
            nonceStr: params.nonceStr,
            timestamp: new Date().getTime(),
            initiatorAccountId: qbg.initiator_account,
            accountId: eaccount.esign_account,
            channel: 1,
            contractName: qbg.merchant_name,
            simpleFormFields: {
                nameA: qbg.ecompany_name,
                nameB: params.idName,
                unit: qbg.merchant_name,
                signDateA: today,
                signDateB: today
            },
            templateId: params.ecid
        }

        var sign = await this.getsign(toecontract, qbg.key)
        toecontract.sign = sign;
        console.log(toecontract)
        let econtr = await axios({
            method: 'post',
            url: this.API.autoSign,
            data: toecontract,
        });


        console.log(econtr)
        // 创建合同
        let econtract = {
            name: qbg.merchant_name,
            eflowstatusname: "签约中",
            eflowstatus: "1",
            user_id: eaccount.user_id,
            usereaccount_id: eaccount.id,
            etemplate_id: qbg.template_id,
            ecompany_id: qbg.ecompany_id,
        };
        econtract = await this.econtractDao.create(econtract);
        if (econtr && econtr.data && econtr.data.status == 0) {
            econtract.eflowid = econtr.data.data.flowId;
            econtract.edocid = econtr.data.data.docId;
            econtract.eflowstatus = '2';
            econtract.eflowstatusname = "已完成";

            var signTime = new Date();
            econtract.completed_at = signTime;
            econtract.begin_at = signTime;
            var end_at = new Date();
            end_at.setFullYear(end_at.getFullYear() + 1);
            econtract.end_at = end_at;
            await econtract.save();
            return this.returnjson(0, "success", {
                contractId: econtract.id
            });
        }
        return this.returnjson(-1, econtr.data.msg || "签约失败", econtr.data.status);
    }


    async getsign(params, secret) {
        let keys = Object.keys(params).sort();
        let signArr = [];
        for (let k = 0; k < keys.length; k++) {
            let tKey = keys[k];
            if (this.EXCEPT_KEYS.indexOf(tKey) == -1 && params[tKey]) {
                signArr.push(tKey + "=" + params[tKey]);
            }
        }
        let signStr = signArr.join("&") + "&key=" + secret;
        let sign = md5(signStr).toUpperCase();
        return sign;
    }

    returnjson(code, msg, data) {
        return {
            code: code,
            msg: msg,
            data: data || null
        }
    }

}


module.exports = QbgconfigService;
