var system = require("../../system")
const http = require("http")
const querystring = require('querystring');
var settings = require("../../../config/settings");
const AppletBase = require("../applet.base");
const logCtl = system.getObject("web.oplogCtl");
const fs = require("fs");
const moment = require("moment");

class xggApplet extends AppletBase {
    constructor() {
        super({
            appid: "wx427b4e988444908f",
            secret: "3d092eb22c3451618a9c0656b1861ac6"
        });
        this.bmuserSve = system.getObject("service.bmuserSve");
        this.bmuserbizSve = system.getObject("service.bmuserbizSve");
        this.bmmerchantSve = system.getObject("service.bmmerchantSve");
        this.bmorderSve = system.getObject("service.bmorderSve");

        this.dictUtils = system.getObject("util.dictUtils");
        this.uploadCtl=system.getObject("web.uploadCtl");

        this.idcardClient = system.getObject("util.idcardClient");
        this.merchantId = 1;
    }

    // 设置登录缓存
    async setLoginUser(id) {
        var user = await this.bmuserSve.findById(id);
        await this.cacheManager["BMUserCache"].set(user.openId, JSON.stringify(user));
        return user;
    }

    // 登录接口 post
    async login(o, obj, req) {
        try {
            var user;
            var wxSession = await this.code2Session(obj, req);
            console.log(obj);
            var iv = obj.iv;
            var encryptedData = obj.encryptedData;
            console.log(wxSession);
            var decryptObj = {
                encryptedData: encryptedData,
                iv: iv,
                sessionKey: wxSession.session_key
            };
            console.log(decryptObj);
            var decryptData = await this.decryptData(decryptObj);
            console.log(decryptData);
            var appkey = this.wxConfig.appid;
            if (decryptData && decryptData.openId) {
                // TODO 找文档，看失效时间
                this.redisClient.set("session_key_" + decryptData.openId, wxSession.session_key);
                console.log("wx ------------------------------------ login");
                user = await this.bmuserSve.findOne({openId: decryptData.openId});
                if (!user) {
                    user = {
                        openId: decryptData.openId,
                        mobile: "",
                        passwd: "",
                        nickname: decryptData.nickName,
                        realname: "",
                        headurl: decryptData.avatarUrl,
                        balance: 0,
                        income: 0,
                        isAuditor:0
                    };
                    //创建用户信息
                    user = await this.bmuserSve.create(user);
                }
                this.cacheManager["BMUserCache"].set(decryptData.openId, JSON.stringify(user));
            }
            return {
                code: 1,
                msg: "success",
                data: user
            };
        } catch (e) {
            console.log("新果果登录错误 [" + JSON.stringify(wxSession) + ", " + obj.iv + + ", " + obj.encryptedData + " ]");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "新果果登录错误 ",
                op: "wxapplet/impl/xggApplet/login",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async loginUser(gobj, pobj, req, loginUser) {
        return {code : 1, data: loginUser};
    }

    async commonInfo(gobj, pobj, req, loginUser) {
        var user = await this.bmuserSve.findById(loginUser.id);
        return {
            code : 1,
            data: {
                telphone: "15210210265",
                isAuditor: user.isAuditor
            }
        };
    }

    // 查询商户信息
    async merchantInfo(gobj, pobj, req, loginUser) {
        try {
            var info = await this.bmmerchantSve.getMerchantInfo(pobj.id);
            var result = {code : 1, data: info};
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "查询商户信息错误, params [id = " + pobj.id + " ]",
                op: "wxapplet/impl/xggApplet/merchantInfo",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    // 保存订单信息
    async saveOrder(gobj, pobj, req, loginUser) {
        try {
            var rs = await this.buildOrder(pobj, loginUser);
            if(rs.code === 0) {
                return rs;
            }

            var info = await this.bmorderSve.saveOrderBiz(rs.data);
            var result = {code : 1};
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "查询商户信息错误, params [id = " + pobj.id + " ]",
                op: "wxapplet/impl/xggApplet/merchantInfo",
                content: e.stack,
                clientIp: req.clientIp
            });
            if(e.name == 'SequelizeUniqueConstraintError') {
                return {code: 2, msg:"您的信息已经提交成功，请到我的订单中查看"};
            }
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async buildOrder(obj, loginUser) {
        var rs = {code: 0};
        if(!loginUser) {
            rs.msg = "登录超时，请重新登录";
            return rs;
        }

        if(!obj.idcard_front) {
            rs.msg = "请上传身份证正面图";
            return rs;
        }
        if(!obj.idcard_back) {
            rs.msg = "请上传身份证反面图";
            return rs;
        }
        if(!obj.idcard) {
            rs.msg = "请填写身份证号码";
            return rs;
        }
        if(!await this.idcardClient.checkIDCard(obj.idcard)) {

        }
        if(!obj.legal_name) {
            rs.msg = "请填写法人姓名";
            return rs;
        }
        if(!obj.legal_mobile) {
            rs.msg = "请填写手机号码";
            return rs;
        }

        if(!obj.companyNames) {
            rs.msg = "请填写公司名称";
            return rs;
        }

        if(!obj.bank_front) {
            rs.msg = "请上传银行卡正面图";
            return rs;
        }
        if(!obj.bank_back) {
            rs.msg = "请上传银行卡反面图";
            return rs;
        }

        if(!obj.bankMobile) {
            rs.msg = "请填写银行预留手机号";
            return rs;
        }

        var orderNo = loginUser.id + "" + moment().format("YYYYMMDDHHmmss");
        var order = {
            merchantId : obj.merchantId || this.merchantId,
            companyId : obj.companyId,
            orderNo : orderNo,
            userId : loginUser.id,
            ownerId: 0,
            status: 0,
            auditStatus:0
        };

        var userbiz = {
            merchantId : obj.merchantId || this.merchantId,
            companyId : obj.companyId,
            orderNo: orderNo,
            user_id: loginUser.id,
            idcard_front: obj.idcard_front,
            idcard_back: obj.idcard_back,
            idcard: obj.idcard,
            legal_name: obj.legal_name,
            legal_mobile: obj.legal_mobile,
            person_img: obj.person_img || "",
            companyNames: obj.companyNames,
            bank_front: obj.bank_front,
            bank_back: obj.bank_back,
            bank: obj.bank,
            bankno: obj.bankno,
            bankMobile: obj.bankMobile || "",
        };

        rs.code = 1;
        rs.data = {
            order : order,
            userbiz: userbiz,
        };
        return rs;
    }


    async myOrders(gobj, pobj, req, loginUser) {
        if(!loginUser) {
            return {code: 1, data:{count:0, rows:[]}};
        }
        try {
            var params = {
                pageSize: pobj.pageSize || 10,
                currentPage: pobj.currentPage || 1,
                userId: loginUser.id,
            }

            var page = await this.bmorderSve.pageByCondition(params);
            var result = {code : 1, data: page};
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "绑定手机, params [" + JSON.stringify(params) + " ]",
                op: "wxapplet/impl/xggApplet/myReqList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }

        console.log(decryptData);
    }

    /**
     * 查询为审核订单
     * @param {*} gobj 
     * @param {*} pobj 
     * @param {*} req 
     * @param {*} loginUser 
     */
    async unauditOrders(gobj, pobj, req, loginUser) {
        if(!loginUser) {
            return {code: 1, data:{count:0, rows:[]}};
        }
        try {
            var params = {
                pageSize: pobj.pageSize || 10,
                currentPage: pobj.currentPage || 1,
                auditStatus: pobj.auditStatus,
                merchantId:this.merchantId,
            }
            //0待审核 1审核通过
            var page = await this.bmorderSve.unauditOrders(params);
            var result = {code : 1, data: page};
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "绑定手机, params [" + JSON.stringify(params) + " ]",
                op: "wxapplet/impl/xggApplet/myReqList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    /**
     * 审核
     * @param {*} gobj 
     * @param {*} pobj 
     * @param {*} req 
     * @param {*} loginUser 
     */
    async audit(gobj, pobj, req, loginUser){
        try {
            let param = {
                auditId:loginUser.id,
                rejectReason:this.trim(pobj.rejectReason) || "",
                auditStatus:parseInt(pobj.auditStatus),
                id:this.trim(pobj.id)
            }
            return await this.bmorderSve.audit(param);
        } catch (error) {
            console.log(error);
            return system.getResult(null,error);
        }
    }

    /**
     * 更新订单
     * @param {*} gobj 
     * @param {*} pobj 
     * @param {*} req 
     * @param {*} loginUser 
     */
    async updateOrder(gobj, pobj, req, loginUser){
        if(!loginUser){
            return system.getResult(null, `请先登陆`);
        }
        try {
            //构建参数
            var order = {
                auditStatus:0,
                id:this.trim(pobj.id)
            };
            let obj = pobj;
            var userbiz = {
                idcard_front: this.trim(obj.idcard_front),
                idcard_back: this.trim(obj.idcard_back),
                idcard: this.trim(obj.idcard),
                legal_name: this.trim(obj.legal_name),
                legal_mobile: this.trim(obj.legal_mobile),
                person_img: this.trim(obj.person_img),
                companyNames: this.trim(obj.companyNames),
                bank_front: this.trim(obj.bank_front),
                bank_back: this.trim(obj.bank_back),
                bank: this.trim(obj.bank),
                bankno: this.trim(obj.bankno),
                bankMobile: this.trim(obj.bankMobile)
            };

            let params ={
                order,userbiz,loginUser
            }
            return await this.bmorderSve.updateOrder(params);
        } catch (error) {
            console.log(error);
            return system.getResult(null,error);
        }
    }

    /**
     * 查询订单明细
     * @param {*} gobj 
     * @param {*} pobj 
     * @param {*} req 
     * @param {*} loginUser 
     */
    async queryOrderInfo(gobj, pobj, req, loginUser){
        if(!loginUser){
            return system.getResult(null, `请先登陆`);
        }
        try {
            return await this.bmorderSve.queryOrderInfo(pobj);
        } catch (error) {
            console.log(error);
            return system.getResult(null,error);
        }
    }

    async idcardValid(gobj, pobj, req, loginUser){
        try {
            var idcard = (pobj.idcard || "").trim();
            if(!idcard) {
                return {code: 0, msg: "请填写身份证号码"};
            }

            var isIdcard = await this.idcardClient.checkIDCard(idcard);
            if(isIdcard) {
                return {code: 1};
            }
            return {code: 0, msg: "身份证号码错误"};
        } catch (error) {
            console.log(error);
            return {code: 500, msg: "服务忙，请稍后重试"};
        }
    }

    async uploadConfig(gobj, pobj, req, loginUser){
        try {
            if(!loginUser){
                return {code: 0};
            }
            var openid = loginUser.openId;
            var data = await this.uploadCtl.getOssConfig();
            return {code:1, data:data};
        } catch (error) {
            console.log(error);
            return {code: 500};
        }
    }
}
module.exports = xggApplet;