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 dlgapplet extends AppletBase {
    constructor() {
        super();
        this.userSve = system.getObject("service.userSve");
        this.usereaccountSve = system.getObject("service.usereaccountSve");
        this.ejobSve = system.getObject("service.ejobSve");
        this.ecompanySve = system.getObject("service.ecompanySve");
        this.econtractSve = system.getObject("service.econtractSve");
        this.ejobcollectSve = system.getObject("service.ejobcollectSve");
        this.ejobapplySve = system.getObject("service.ejobapplySve");
        this.ossClient = system.getObject("util.ossClient");
        this.emessageSve = system.getObject("service.emessageSve");
        this.esettleSve = system.getObject("service.esettleSve");
        this.ejobrosterSve = system.getObject("service.ejobrosterSve");
        
        this.smsClient = system.getObject("util.smsClient");
    }

    //************************************************************公共参数处理********************开始***************************************
    //验证公共参数信息
    async getLoginUser(param, reload) {
        var openId = this.trim(param.openId);
        if (!openId) {
            return;
        }
        
        var userInfo = await this.cacheManager["AppletUserinfoCache"].get(openId, "wx32bfeb4bde101eb0");
        if (!userInfo) {
            var user = await this.userSve.getDLGUserByOpenId(openId, "wx32bfeb4bde101eb0");
            if(user) {
                this.cacheManager["AppletUserinfoCache"].set(openId, JSON.stringify(user), "wx32bfeb4bde101eb0");
                return user;
            } else {
                return null;
            }
        }
        return JSON.parse(userInfo);
    }

    //************************************************************公共参数处理********************结束***************************************

    //************************************************************职位********************开始***************************************
    //职位详情=post
    async jobInfo(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };
        console.log(this.configDLG);
        var loginUser = await this.getLoginUser(req);
        var userId;
        if (loginUser) {
            userId = loginUser.id;
        }

        try {
            result.data = await this.ejobSve.jobInfo(req.jobId, userId);
            return result;
        } catch (e) {
            console.log("职位详情异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "职位详情异常, params = " + req.jobId + ", " + userId,
                op: "wxapplet/impl/dlgApplet/jobInfo",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    //职位列表=post
    async jobList(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var currentPage = Number(req.currentPage || 1);
            var pageSize = Number(req.pageSize || 10);
            req.jobStatus = '1';

            result.data = await this.ejobSve.jobList(currentPage, pageSize, req);
            return result;
        } catch (e) {
            console.log("职位列表异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "职位列表异常, currentPage = " + currentPage + ", pageSize=" + pageSize,
                op: "wxapplet/impl/dlgApplet/jobList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {}
            };
        }
    }

    //职位收藏/取消=post
    async jobCollect(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        var loginUser = await this.getLoginUser(req);
        try {
            var jobId = Number(req.jobId || 0);
            var isCollect = Number(req.isCollect);

            result.data = await this.ejobcollectSve.opCollect(loginUser.id, jobId, isCollect);
            return result;
        } catch (e) {
            console.log("职位收藏/取消:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "职位收藏/取消, params [" + loginUser.id + ", " + jobId + ", " + isCollect + "]",
                op: "wxapplet/impl/dlgApplet/jobList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async jobApply(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        var loginUser = await this.getLoginUser(req);
        try {
            var jobId = Number(req.jobId || 0);
            var rs = await this.ejobSve.jobApply(jobId, loginUser.id, loginUser.info.id);
            if (rs == -1) {
                result.code = 0;
                result.msg = "您已经申请过该职位";
                return result;
            }

            if (rs == -2) {
                result.code = 0;
                result.msg = "职位已下线";
                return result;
            }
            result.data = rs;
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录  
            logCtl.error({
                optitle: "申请接单, params [" + loginUser.id + ", " + jobId + "]",
                op: "wxapplet/impl/dlgApplet/jobApply",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async setLoginUser(openId, appkey) {
        var user = await this.userSve.getDLGUserByOpenId(openId, appkey);
        await this.cacheManager["AppletUserinfoCache"].set(openId, JSON.stringify(user), appkey);
        return user;
    }

    async autoApply(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        var loginUser = await this.getLoginUser(req);
        try {
            var rs = await this.ejobSve.autoApply(loginUser.id, loginUser.info.id, loginUser.mobile);
            if(rs) {
                var account = await this.usereaccountSve.findById(loginUser.info.id);
                account.userName = rs.userName;
                account.personsSign = rs.personsSign;
                account.bankno = rs.bankno;
                await account.save();
                
                result.data = await this.setLoginUser(loginUser.openId, loginUser.appkey);
            }
            return result;
        } catch (e) {
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "申请接单, params [" + loginUser.id + ", " + jobId + "]",
                op: "wxapplet/impl/dlgApplet/jobApply",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    //************************************************************职位********************结束***************************************

    //************************************************************用户********************结束***************************************

    // 绑定手机  post
    async bindMobile(obj, req) {
        var loginUser = await this.getLoginUser(req);

        var session_key = await this.redisClient.get("session_key_" + loginUser.openId);
        if(!session_key) {
            return {
                code : 0,
                msg: "session_key过期"
            }
        }   
        try {
            var decryptObj = {
                encryptedData: req.encryptedData,
                iv: req.iv,
                sessionKey: session_key
            };
            var decryptData = await this.decryptData(decryptObj);
            if(decryptData && decryptData.phoneNumber) {
                var user = await this.userSve.findById(loginUser.id);
                var account = await this.usereaccountSve.findById(loginUser.info.id);

                if(!user.mobile) {
                    user.mobile = decryptData.phoneNumber;  
                    await user.save();
                }
                account.mobile = decryptData.phoneNumber;
                await account.save();
                var result = {code : 1};
                result.data = await this.setLoginUser(loginUser.openId, loginUser.appkey);
                return result;
            } else {
                return {
                    code : 0,
                    msg: "绑定手机失败"
                }
            }
        } catch (e) {
            console.log(e.stack);
            //日志记录  
            logCtl.error({
                optitle: "绑定手机, params [" + session_key + ", " + req.iv + + ", " + req.encryptedData + " ]",
                op: "wxapplet/impl/dlgApplet/bindMobile",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }

        console.log(decryptData);
    }

    // 登录 post
    async checkAndLogin(o, obj, req) {
        try {
            var user;
            var wxSession = await this.code2Session(obj, req);
            console.log(obj);
            var apptype = obj.apptype || "dlg";
            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);
            if (decryptData && decryptData.openId) {
                this.redisClient.set("session_key_" + decryptData.openId, wxSession.session_key);
                console.log("wx ------------------------------------ login");
                var appkey = "";
                if (apptype == 'dlg') {
                    appkey = this.configDLG.appid;
                    user = await this.userSve.getDLGUserByOpenId(decryptData.openId, appkey);
                } else {
                    user = await this.userSve.getUserByOpenId(decryptData.openId, appkey);
                }
                if (!user) {
                    var wxUserInfo = {
                        openId: decryptData.openId,
                        unionId: decryptData.openId,
                        appkey: appkey,
                        userName: "",
                        password: "",
                        nickName: decryptData.nickName,
                        headUrl: decryptData.avatarUrl,
                        isAdmin: false,
                        isEnabled: true,
                        sex: decryptData.gender == 1 ? "male" : "female",
                        onlyCode: decryptData.openId,
                        mobile: "",
                        email: "",
                        companyName: "",
                        companyAddr: "",
                        isPartner: false,
                    };

                    if (apptype == 'dlg') {
                        var sexName = "";
                        if (wxUserInfo.sex) {
                            sexName = wxUserInfo.sex == "male" ? "男" : "女"
                        }
                        wxUserInfo.eaccount = {
                            mobile: "",
                            userName: wxUserInfo.nickName,
                            personsSign: "",
                            bankno: "",
                            eaccountid: "",
                            email: "",
                            headUrl: wxUserInfo.headUrl,
                            sex: wxUserInfo.sex,
                            sexName: sexName,
                            adv: "",
                            experience: "",
                        }
                    }
                    console.log("wxUserInfo-----------------------------------------------------");
                    console.log(wxUserInfo);
                    //创建用户信息
                    await this.userSve.register(wxUserInfo);
                    if (apptype == 'dlg') {
                        user = await this.userSve.getDLGUserByOpenId(decryptData.openId, appkey);
                        this.emessageSve.create({
                            user_id: user.id,
                            type:'0',
                            title: '系统消息',
                            content : "欢迎您来到薪必果零工平台"
                        });
                    } else {
                        user = await this.userSve.getUserByOpenId(decryptData.openId, appkey);
                    }
                }
                this.cacheManager["AppletUserinfoCache"].set(decryptData.openId, JSON.stringify(user), appkey);
            }
            return {
                code: 1,
                msg: "success",
                data: user
            };
        } catch (e) {
            console.log("打零工登录错误 error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "打零工登录错误 ",
                op: "wxapplet/impl/dlgApplet/checkAndLogin",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    // 修改我的资料
    async editUserInfo(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };
        try {
            var loginUser = await this.getLoginUser(req);

            await this.userSve.editDLGInfo(loginUser.id, req);
            result.data = await this.userSve.getDLGUserByOpenId(loginUser.openId, loginUser.appkey);
            return result;
        } catch (e) {
            console.log("修改个人资料:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "修改个人资料, params [" + loginUser.id + "]",
                op: "wxapplet/impl/dlgApplet/editUserInfo",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
        return result;
    }

    async uploadCard(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);
            var frontRs = await this.getIdCardInfo(req.front);

            if(frontRs && frontRs.id) {
                var account = await this.usereaccountSve.findById(loginUser.info.id);
                account.personsSign = frontRs.id;
                account.userName = frontRs.name;
                account.idCardFront = req.front;
                account.idCardBack = req.back;
                await account.save();   
                console.log(account);
            } else {
                return {code : 0, msg:"身份证照片识别失败, 请重新上传"};
            }
            
            result.data = await this.userSve.getDLGUserByOpenId(loginUser.openId, loginUser.appkey);
            this.emessageSve.create({
                user_id: loginUser.id,
                type:'0',
                title: '系统消息',
                content : "您的身份认证成功"
            });

            return result;
        } catch (e) {
            console.log("身份认证:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "身份认证",
                op: "wxapplet/impl/dlgApplet/uploadCard",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
        return result;
    }

    // 我的收藏
    async myCollectList(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);

            var currentPage = Number(req.currentPage || 1);
            var pageSize = Number(req.pageSize || 10);

            result.data = await this.ejobSve.collectList(loginUser.id, currentPage, pageSize);
            return result;
        } catch (e) {
            console.log("我的收藏异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "我的收藏异常",
                op: "wxapplet/impl/dlgApplet/jobList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {}
            };
        }
    }
    
    async sendSms(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };
        try {
            var loginUser = await this.getLoginUser(req);

            var mobile = req.mobile;
            //生成一个验证码，发送
            
            var key = "dlg_phone_vcode_" + mobile;
            var vcode = await this.redisClient.get(key);
            if (!vcode) {
                vcode = await this.getUidStr(6, 10);
                await this.redisClient.setWithEx("dlg_phone_vcode_" + mobile, vcode, 60);
                var msg = "验证码为" + vcode + ", (切勿将验证码告知别人, 请在页面中输入完成验证, 如有问题请联系客服。)";
                var rs = await this.smsClient.sendMsg(mobile, msg);
                console.log(rs);
            }
            return result;  
        } catch (e) {
            console.log("发送短信验证码:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "发送短信验证码",
                op: "wxapplet/impl/dlgApplet/sendSms",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }
    async updateMobile(obj, req) {
        var result = {
            code: 1,
            msg: "success"
        };
        try {
            var loginUser = await this.getLoginUser(req);
            var mobile = req.mobile;
            var key = "dlg_phone_vcode_" + mobile;
            var cacheCode = await this.redisClient.get(key) || "";
            if(cacheCode != req.vcode) {
                return {code : 0, msg:"短信验证码错误"};
            }

            this.redisClient.delete(key);

            var user = await this.userSve.findById(loginUser.id);
            var account = await this.usereaccountSve.findById(loginUser.info.id);
            user.mobile = mobile
            account.mobile = mobile
            await user.save();
            await account.save();
            result.data = await this.userSve.getDLGUserByOpenId(loginUser.openId, loginUser.appkey);
            return result;
        } catch (e) {
            console.log("修改手机号:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "修改手机号",
                op: "wxapplet/impl/dlgApplet/updateMobile",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }


    //************************************************************用户********************结束***************************************


    //************************************************************订单********************开始***************************************
    async orderList(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);

            var currentPage = Number(req.currentPage || 1);
            var pageSize = Number(req.pageSize || 10);
            var params = {
                user_id : loginUser.id,
            }

            var status = (req.status || "").toString();

            if(status) {
                params.status = status;
            }

            result.data = await this.ejobSve.applyList(params, currentPage, pageSize);
            return result;
        } catch (e) {
            console.log("我的订单异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "我的订单异常" ,
                op: "wxapplet/impl/dlgApplet/orderList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async orderCancel(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);
            var jobapply = await this.ejobapplySve.findById(req.id);
            if(!jobapply) {
                return {
                    code: 0,
                    msg: "接单信息不存在"
                }
            }
            jobapply.status = '5';
            jobapply.statusName = '已撤销';

            await jobapply.save();
            result.data = jobapply;
            return result;
        } catch (e) {
            console.log("订单取消异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "订单取消异常" ,
                op: "wxapplet/impl/dlgApplet/orderCancel",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async reapply(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);
            var rs = await this.ejobSve.reapply(req.id);
            if(rs == -1) {
                return {code: 0, msg: "接单信息不存在"};
            }
            return result;
        } catch (e) {
            console.log("订单重新申请异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "订单重新申请异常",
                op: "wxapplet/impl/dlgApplet/reapply",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    // 获取合同地址
    async getContractPDF(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);
            var jobapply = await this.ejobapplySve.findById(req.id);
    

            result.data = await this.econtractSve.getContractUrl(jobapply.econtract_id);
            return result;
        } catch (e) {
            console.log("订单重新申请异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "订单重新申请异常",
                op: "wxapplet/impl/dlgApplet/reapply",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    //************************************************************订单********************结束***************************************

    //************************************************************消息开始***********************************************************
    async messageList(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var currentPage = Number(req.currentPage || 1);
            var pageSize = Number(req.pageSize || 10);

            var loginUser = await this.getLoginUser(req);
            var params = {
                user_id: loginUser.id,
                types:[0, 1, 2, 3],
            }

            result.data = await this.emessageSve.getList(params, currentPage, pageSize);
            result.unreadCount = await this.emessageSve.findCount({where: {user_id: loginUser.id, read : false}});;
            return result;
        } catch (e) {
            console.log("消息列表异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "消息列表异常",
                op: "wxapplet/impl/dlgApplet/messageList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    async messageRead(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var id = Number(req.id || 0);
            var loginUser = await this.getLoginUser(req);
            if(id) {
                var message = await this.emessageSve.findById(id);
                message.read = true;
                await message.save();
            } else {
                await this.emessageSve.readAll(loginUser.id);
            }
            result.unreadCount = await this.emessageSve.findCount({where: {user_id: loginUser.id, read : false}});;
            return result;
        } catch (e) {
            console.log("消息读取异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "消息读取异常",
                op: "wxapplet/impl/dlgApplet/messageRead",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    //************************************************************消息结束***********************************************************

    //************************************************************报酬开始***********************************************************
    async statIncome(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var loginUser = await this.getLoginUser(req);
            var params = {
                user_id: loginUser.id
            }

            var countAll = await this.esettleSve.countAmtByCard(loginUser.info.personsSign);

            let begin = moment().add('month', 0).format('YYYY-MM') + '-01 00:00:00';
            let end = moment(begin).add('month', 1).add('days', -1).format('YYYY-MM-DD') + ' 23:59:59';
            
            var countMonth = await this.esettleSve.countAmtByCard(loginUser.info.personsSign, begin, end);

            result.data = {
                all: countAll,
                month: countMonth
            };
            return result;
        } catch (e) {
            console.log("消息列表异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "消息列表异常",
                op: "wxapplet/impl/dlgApplet/messageList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    // 结算列表
    async settleList(obj, req) {
        // ejobapplySve
        var result = {
            code: 1,
            msg: "success"
        };

        try {
            var currentPage = Number(req.currentPage || 1);
            var pageSize = Number(req.pageSize || 10);

            var loginUser = await this.getLoginUser(req);
            result.data = await this.esettleSve.findOrderItemsByCard(loginUser.info.personsSign, currentPage, pageSize);
            return result;
        } catch (e) {
            console.log("结算列表异常:error*****************************************************************************");
            console.log(e.stack);
            //日志记录
            logCtl.error({
                optitle: "结算列表异常",
                op: "wxapplet/impl/dlgApplet/messageList",
                content: e.stack,
                clientIp: req.clientIp
            });
            return {
                code: -200,
                msg: "error",
                data: {},
                stack : e.stack
            };
        }
    }

    //************************************************************报酬结束***********************************************************
}
module.exports = dlgapplet;