const system = require("../../../system");
const ServiceBase = require("../../svems.base")

class AuthService extends ServiceBase {
    constructor() {
        super();
        this.feeSve = system.getObject("service.fee.feeSve");
        this.orderSve = system.getObject("service.order.orderSve");
        this.ordersignlogSve = system.getObject("service.order.ordersignlogSve");
        this.enginesignSve = system.getObject("service.engine.enginesignSve");
        this.tradelogDao = system.getObject("db.common.tradelogDao");
    }

    async createAccount(params) {
        try {
            params.apiName = "sign@";
            params.isFee = false;

            // 验证参数
            let idName = this.trim(params.idName);
            let idNo = this.trim(params.idNo).toUpperCase();
            let mobile = this.trim(params.mobile);
            if (!idName) {
                return system.getResultFail(1000000, "姓名错误");
            }
            if (!idNo) {
                return system.getResultFail(1000000, "身份证错误");
            }
            return this.operatorSign(params, async (p) => {
                // 调用创建账户API
                let validRes = await this.enginesignSve.createAccount({
                    id_name: idName,
                    id_no: idNo,
                    mobile: mobile,
                    channel: p.orderProduct.channel,
                });
                return validRes;
            });
        } catch (error) {
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }

    async createTemplate(params) {
        try {
            params.apiName = "sign@";
            params.isFee = false;
            // 验证参数
            let filePath = this.trim(params.filePath);
            let sealEnt = this.trim(params.sealEnt);
            let sealPer = this.trim(params.sealPer);
            let templateName = this.trim(params.templateName);
            if (!filePath) {
                return system.getResultFail(1000000, "模板地址不能为空");
            }
            if (!sealEnt) {
                return system.getResultFail(1000000, "企业印章位置Key不能为空");
            }
            if (!sealPer) {
                return system.getResultFail(1000000, "个人印章位置Key不能为空");
            }
            if (!templateName) {
                return system.getResultFail(1000000, "模板名称不能为空");
            }
            return this.operatorSign(params, async (p) => {
                let validRes = await this.enginesignSve.createTemplate({
                    filePath: filePath,
                    sealEnt: sealEnt,
                    sealPer: sealPer,
                    templateName: templateName,
                    channel: p.orderProduct.channel,
                });
                return validRes;
            });

        } catch (error) {
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }


    async createEntSeal(params) {
        try {
            params.apiName = "sign@";
            params.isFee = false;
            // 验证参数
            let accountId = this.trim(params.accountId);
            let sealAlias = this.trim(params.sealAlias);
            if (!accountId) {
                return system.getResultFail(1000000, "账户ID不能为空");
            }
            if (!sealAlias) {
                return system.getResultFail(1000000, "印章名称不能为空");
            }
            return this.operatorSign(params, async (p) => {
                let validRes = await this.enginesignSve.organize({
                    accountId: accountId,
                    channel: p.orderProduct.channel,
                    color: 1,
                    sealAlias: sealAlias,
                    templateType: 1,
                    text: sealAlias,
                });
                return validRes;
            });
        } catch (error) {
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }


    async handSign(params) {
        try {
            params.apiName = "sign@hand";
            params.isFee = true;

        } catch (error) {
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }

    async contentByDocIds(params) {
        try {
            if (!params.contentIds && params.contentIds == 0) {
                return system.getResultFail(1000000, "请提供合同ID");
            }
            let validRes = await this.enginesignSve.contentByDocIds({
                    "channel": 1,
                    "docIds": params.contentIds
                });
            return validRes;

        } catch (error) {
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }

    /**
     *
     * {
    "action_process": "test",
    "action_type": "autoSign",
    "action_body": {
        "appId":"12167897412000190",
        "nonceStr":"12312312312312",
        "sign":"EE63140753238BB2E4D79ABCDFB07732",
        "accountId": "c4a5a57bad9b4d4ab5dbbe2362d86f77",
        "channel": 1,
        "contractName": "测试",
        "entSealId": 63,
        "noticeUrl": "",
        "perSealId": "",
        "redirectUrl": "",
        "sealType": null,
        "signPlatform": null,
        "simpleFormFields": {
            "nameA":"甲方",
            "nameB":"个人",
            "unit":"测试测试测试",
            "signDateA":"2020-07-04",
            "signDateB":"2020-07-04"
        },
        "templateId": "10512"
    }
}
     */
    async autoSign(params) {
        params.apiName = "sign@auto";
        params.isFee = true;

        // 验证参数
        let accountId = this.trim(params.accountId);
        let entSealId = this.trim(params.entSealId);
        let contractName = this.trim(params.contractName);
        let templateId = this.trim(params.templateId);
        let simpleFormFields = params.simpleFormFields;

        if (!accountId) {
            return system.getResultFail(1000000, "账户ID不能为空");
        }
        if (!entSealId) {
            return system.getResultFail(1000000, "印章ID不能为空");
        }
        if (!contractName) {
            return system.getResultFail(1000000, "合同名称不能为空");
        }
        if (!templateId) {
            return system.getResultFail(1000000, "模板ID不能为空");
        }
        if (!simpleFormFields) {
            return system.getResultFail(1000000, "模板关联参数错误");
        }
        return this.operatorSign(params, async (p) => {
            // 调用创建账户API
            let validRes = await this.enginesignSve.autoSign({
                accountId: accountId,
                entSealId: entSealId,
                contractName: contractName,
                templateId: templateId,
                simpleFormFields: simpleFormFields,
                channel: p.orderProduct.channel,
            });
            return system.getResultSuccess(validRes.contract);
        });
        try {
        } catch (error) {
            console.log(error)
            return system.getResult(null, `系统错误 错误信息 ${error}`);
        }
    }

    async operatorSign(params, operatorMethod) {
        let app = params.app;
        let merchantId = app.merchant_id;
        let isFee = params.isFee;

        // 获取订单产品
        let orderProduct = await this.orderSve.getMerchantOrderProduct(merchantId, params.apiName);
        if (orderProduct.status !== 0) {
            return orderProduct;
        }
        orderProduct = orderProduct.data;
        params.orderProduct = orderProduct;
        // 扣费
        let tradeLog;
        let trade;
        if (isFee) {
            let tres = await this.trade(params);
            if (tres.status !== 0) {
                return tres;
            }
            trade = tres.data.trade;
        }
        // 2. 调用签约引擎接口
        let res = await operatorMethod(params);
        let contract = res.data || {};
        if (isFee) {
            // 生成订单
            let logres = await this.ordersignlogSve.saveEorderSignLog({
                order_id: orderProduct.id,
                product_id: orderProduct.product_id,
                platform_name: app.name,
                platform_id: app.id,
                user_name: contract.idName,         // 使用方
                spended_num: trade.trade_amt,
                actual_spend_name: app.merchant_name,// 实际使用方
                engine_contract_name: contract.name,
                engine_contract_id: contract.docid,
                engine_trade_id: trade.id,
            });
            console.log(logres);
        }
        // 4. 返回认证结果
        return system.getResultSuccess(res.data, res.msg);
    }

    // 交易
    async trade(params) {
        let orderProduct = params.orderProduct;

        let trade_amt = 1;
        if (orderProduct == 2) {
            trade_amt = Number(orderProduct.price);
        }

        let tradeLog = await this.tradelogDao.create({
            requestid: params.requestid,
            merchant_id: orderProduct.merchant_id,
            product_id: orderProduct.product_id,
            trade_amt: trade_amt,
            result: 0,
        });


        let tradeRes = await this.feeSve.trade({
            account_id: orderProduct.engine_account_id,
            trade_amt: trade_amt,
            trade_no: tradeLog.id,
            trade_desc: params.desc || "",
        });
        if (tradeRes.status !== 0) {
            tradeLog.result = 2;
            tradeLog.fee = 0;
            tradeLog.fee_remark = "扣费失败，" + tradeRes.msg;
            await tradeLog.save();
            return system.getResultFail(1002001, "扣费失败，" + tradeRes.msg);
        } else {
            tradeLog.result = 1;
            tradeLog.fee = 1;
            tradeLog.fee_remark = "扣费成功";
            await tradeLog.save();
        }
        return system.getResultSuccess({
            tradeLog: tradeLog,
            trade: tradeRes.data
        })
    }
}

module.exports = AuthService;
