const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const settings = require("../../../../config/settings");
const fs = require('fs');

class EcloudsignService extends ServiceBase {
    constructor() {
        super("sign", ServiceBase.getDaoName(EcloudsignService));

        this.ecloudsignDao = system.getObject("db.sign.ecloudsignDao");
        this.pverifyDao = system.getObject("db.sign.pverifyDao");
        this.signetDao = system.getObject("db.sign.signetDao");
        this.applycertDao = system.getObject("db.sign.applycertDao");
        this.templateDao = system.getObject("db.sign.templateDao");

        this.ecloudClient = system.getObject("util.sign.ecloudsignClient");
        this.reqClient = system.getObject("util.reqClient");
        this.ossClient = system.getObject("util.ossClient");

        this.APIURL = "https://testapi.ecloudsign.com";//"https://api.ecloudsign.com";
    }

    async apibankVerify(params) {
        try {
            return await this.bankVerify(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apiapplyCert(params) {
        try {
            return await this.applyCert(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apiaddSign(params) {
        try {
            return await this.addSign(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apicreateSeal(params) {
        try {
            return await this.createSeal(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apicreateSign(params) {
        try {
            return await this.createSign(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apisignPage(params) {
        try {
            return await this.signPage(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apiaddHtmlTemplate(params) {
        try {
            return await this.addHtmlTemplate(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apicreateContractByTemplate(params) {
        try {
            return await this.createContractByTemplate(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apisendSms(params) {
        try {
            return await this.sendSms(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apiauthorizeSign(params) {
        try {
            return await this.authorizeSign(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    async apidownloadCont(params) {
        try {
            return await this.downloadCont(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null, "接口异常");
        }
    }

    // -----------------------以此间隔，上面为API，下面为service---------------------------------

    async bankVerify(qobj) {
        var selIn = {};
        if (!qobj.realName) {
            return system.getResult(null, "请求参数为空");
        } else {
            selIn.realName = qobj.realName;
        }
        if (!qobj.bankNumber) {
            return system.getResult(null, "请求参数bankNumber为空");
        } else {
            selIn.bankNumber = qobj.bankNumber;
        }
        if (!qobj.idCardNumber) {
            return system.getResult(null, "请求参数idCardNumber为空");
        } else {
            selIn.idCardNumber = qobj.idCardNumber;
        }
        if (qobj.verifyType != 3 && qobj.verifyType != 4) {
            return system.getResult(null, "请求参数verifyType错误");
        } else {
            selIn.verifyType = qobj.verifyType;
        }
        if (qobj.verifyType == 4) {
            if (!qobj.mobile) {
                return system.getResult(null, "请求参数mobile为空");
            } else {
                selIn.mobile = qobj.mobile;
            }
        }
        let verifyData = await this.pverifyDao.model.findAll({where: selIn, raw: true});
        if (verifyData.length > 0) {
            return JSON.parse(verifyData[0].succeed);
        }
        const params = await this.ecloudClient.rformat({bankInfo: JSON.stringify(selIn)});
        const url = this.APIURL + "/ecs/auth/bankVerify.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body);
        selIn.succeed = body;
        this.pverifyDao.create(selIn).then(jane => {
            console.log(jane.id);
        });
        return JSON.parse(body);
    }


    async applyCert(qobj) {
        var result = {};
        var inse = {};
        if (!qobj.type) {
            return system.getResult(null, "请求参数type为空");
        } else {
            inse.type = qobj.type;
        }
        if (!qobj.cardType) {
            return system.getResult(null, "请求参数cardType为空");
        } else {
            inse.cardType = qobj.cardType;
        }
        if (!qobj.idCardNum) {
            return system.getResult(null, "请求参数idCardNum为空")
        } else {
            inse.idCardNum = qobj.idCardNum;
        }
        if (qobj.name) {
            inse.name = qobj.name;
        }
        if (qobj.mobilePhone) {
            inse.mobilePhone = qobj.mobilePhone;
        }

        let applyData = await this.applycertDao.model.findAll({where: inse, raw: true});

        if (applyData.length > 0) {
            result.code = applyData[0].code;
            result.message = applyData[0].message;
            if (applyData[0].code == 0) {
                result.data = {
                    userName: applyData[0].userName,
                    serialNumber: applyData[0].serialNumber,
                    certNotBefore: applyData[0].certNotBefore,
                    certNotAfter: applyData[0].certNotAfter,
                    issuer: applyData[0].issuer
                };
            }
            return result;
        }

        var params = await this.ecloudClient.rformat({info: JSON.stringify(qobj)});
        var url = this.APIURL + "/ecs/account/applyCert.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        body = JSON.parse(body);
        console.log(body)
        result.code = body.meta.code;
        result.msg = body.meta.message;
        inse.code = body.meta.code;
        inse.message = body.meta.message;
        if (body.meta.code === 0) {
            result.data = body.data;
            inse.userName = body.data.userName;
            inse.serialNumber = body.data.serialNumber;
            inse.certNotBefore = body.data.certNotBefore;
            inse.certNotAfter = body.data.certNotAfter;
            inse.issuer = body.data.issuer;
        }
        this.applycertDao.create(inse).then(jane => {
            console.log(jane.id);
        });
        return result;
    }


    async addSign(qobj) {
        var seleIn = {};
        if (!qobj.mobilePhone) {
            return system.getResult(null, "请求参数mobilePhone为空");
        } else {
            seleIn.mobilePhone = qobj.mobilePhone
        }
        if (!qobj.signType) {
            return system.getResult(null, "请求参数signType为空")
        } else {
            seleIn.signType = qobj.signType;
        }
        if (!qobj.signImg) {
            return system.getResult(null, "请求参数signImg为空")
        }
        let bitmap = fs.readFileSync(qobj.signImg);
        qobj.signImg = Buffer.from(bitmap, 'binary').toString('base64');//base64编码
        let signetData = await this.signetDao.model.findAll({where: seleIn, raw: true});
        if (signetData.length > 0) {
            return JSON.parse(signetData[0].succeed);
        }

        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/signInfo/addSign.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body);
        if ((JSON.parse(body)).meta.code === 0) {
            seleIn.signId = (JSON.parse(body)).data.signId;
        }
        seleIn.succeed = body;
        seleIn.signImg = qobj.signImg;
        this.signetDao.create(seleIn).then(jane => {
            console.log(jane.id);
        });
        return JSON.parse(body);
    }

    async createSeal(qobj) {
        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/signInfo/createSeal.jspa"; //短名称
        var url_L = this.APIURL + "/ecs/signInfo/createSealLong.jspa";//长名称
        if (qobj.unitName.length > 16) {
            url = url_L;
        }
        let seleIn = {
            mobilePhone: qobj.mobilePhone,
            unitName: qobj.unitName
        };
        let signetData = await this.signetDao.model.findAll({where: seleIn, raw: true});
        if (signetData.length > 0) {
            return JSON.parse(signetData[0].succeed);
        }
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body)
        if (JSON.parse(body).meta.code === 0) {
            seleIn.signId = JSON.parse(body).data.signId;
        }
        seleIn.succeed = body;
        seleIn.signType = 4;
        this.signetDao.create(seleIn).then(jane => {
            console.log(jane.id);
        });
        return JSON.parse(body);
    }


    async createSign(qobj) {
        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/signInfo/createSign.jspa"; //短名称
        let seleIn = {
            mobilePhone: qobj.mobilePhone,
            signName: qobj.signName
        };
        let signetData = await this.signetDao.model.findAll({where: seleIn, raw: true});
        if (signetData.length > 0) {
            return JSON.parse(signetData[0].succeed);
        }
        let body = await this.reqClient.reqFormData(params, url);
        if (JSON.parse(body).meta.code === 0) {
            seleIn.signId = JSON.parse(body).data.signId;
        }
        seleIn.succeed = body;
        seleIn.signType = 5;
        this.signetDao.create(seleIn).then(jane => {
            console.log(jane.id);
        });
        return JSON.parse(body);
    }

    async signPage(qobj) {

    }


    async addHtmlTemplate(qobj) {
        var selIn = {};
        if (!qobj.templateName) {
            return system.getResult(null, "请求参数templateName为空");
        } else {
            selIn.templateName = qobj.templateName;
        }
        if (!qobj.html) {
            return system.getResult(null, "请求参数html为空");
        } else {
            selIn.html = qobj.html;
            qobj.html = fs.readFileSync(qobj.html, 'utf-8');
        }
        if (qobj.templateNumber) {
            selIn.templateNumber = qobj.templateNumber;
        }
        if (qobj.signPosition) {
            selIn.signPosition = JSON.stringify(qobj.signPosition);
        }
        let temDta = await this.templateDao.model.findAll({where: selIn, raw: true});

        if (temDta.length > 0) {
            return system.getResult(JSON.parse(temDta[0].succeed));
        }
        qobj.signPosition = JSON.stringify(qobj.signPosition)
        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/template/addHtmlTemplate.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body);
        if ((JSON.parse(body)).meta.code === 0) {
            selIn.templateNumber = (JSON.parse(body)).data.templateNumber;
        }
        selIn.succeed = body;
        this.templateDao.create(selIn).then(jane => {
            console.log(jane.id);
        });
        return JSON.parse(body);
    }

    async createContractByTemplate(qobj) {

        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/template/createContractByTemplate.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body)
        return JSON.parse(body);
    }

    async sendSms(qobj) {
        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/contract/sendSms.jspa";
        let body = await this.reqClient.reqFormData(params, url);

        return JSON.parse(body);

    }

    async authorizeSign(qobj) {
        qobj.signerInfo = JSON.stringify(qobj.signerInfo);
        qobj.signInfo = JSON.stringify(qobj.signInfo);
        var params = await this.ecloudClient.rformat(qobj);
        console.log(params)
        var url = this.APIURL + "/ecs/contract/authorizeSign.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        console.log(body);
        return JSON.parse(body);
    }

    async downloadCont(qobj) {
        var result = {};
        var params = await this.ecloudClient.rformat(qobj);
        var url = this.APIURL + "/ecs/contract/downloadCont.jspa";
        let body = await this.reqClient.reqFormData(params, url);
        body = JSON.parse(body);
        fs.writeFile('/mnt/output-1.pdf', new Buffer(body.data.bytes, "base64"), function (response) {
            console.log('File Saved!');
        });
        console.log("程序执行完毕");
        result.code = body.meta.code;
        result.mes = body.meta.message;
        let ss = await this.ossClient.upfile("测试", "/mnt/output-1.pdf");
        result.data = ss.url;
        return result;
    }


}

module.exports = EcloudsignService;
