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.dkcontractDao = system.getObject("db.dkcontractDao")
        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");

        this.dkcompanyDao = system.getObject("db.dkcompanyDao");

    }

    //两方
    async autoSigns(params, qbg) {
        let ecid = params.ecid;
        // 验证身份证是否签约过
        let todays = moment().format("YYYY-MM-DD") + " 00:00:00";
        // dkecompany
        var dkcompany = await this.dkcompanyDao.findById(qbg.ecompany_id);

        let contractId = await this.dkcontractDao.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.eaccountid) {
            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.eaccountid = 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,  //企业账号（E签宝）
            accountId: eaccount.eaccountid,             //个人账号（E签宝）
            channel: 1,
            entSealId: qbg.seal_id,
            contractName: dkcompany.name,   //合同名称
            simpleFormFields: {
                nameA: dkcompany.name,      //甲方 必填
                addressA: dkcompany.addr,   // 甲方地址
                phoneA: dkcompany.phone,    // 甲方电话

                nameB: params.idName,       //乙方姓名 必填
                phoneB: params.mobile,      //乙方电话 必填

                nameC: params.idName,      // 乙方姓名
                banknoC: params.bankno,    // 乙方电话
                phoneC: params.mobile,     // 乙方身份证
                idcardC: params.idNo,      // 乙方银行卡号

                signdate: today,           // 签约日期
            },
            templateId: qbg.template_id    //ecid（E签宝）
        }

        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 dkecontract = {
            name: qbg.merchant_name,
            dktemplate_id: ecid,
            user_id: eaccount.user_id,
            usereaccount_id: eaccount.id,
            dkcompany_id: qbg.ecompany_id,
            edocid: "",
            eflowid: "",
            esignUrl: "",
            eflowstatus: "1",
        }
        dkecontract = await this.dkcontractDao.create(dkecontract);
        if (econtr && econtr.data && econtr.data.status == 0) {
            dkecontract.eflowid = econtr.data.data.flowId;
            dkecontract.edocid = econtr.data.data.docId;
            dkecontract.eflowstatus = '2';
            dkecontract.eflowstatusname = "已完成";

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


    /**
     * 三方静默签
     * @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.eaccountid) {
            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.eaccountid = 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.eaccountid,
            channel: 1,
            entSealId: qbg.seal_id,
            contractName: qbg.merchant_name,
            simpleFormFields: {
                nameA: qbg.ecompany_name,
                nameB: params.idName,
                unit: qbg.merchant_name,
                signDateA: today,
                signDateB: today
            },
            templateId: qbg.template_id
        }

        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: ecid,
            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();
            this.redisClient.rpushBCD({id: econtract.id, sve: "e"});
            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;
