var APIBase = require("../../api.base");
var system = require("../../../system");
var settings = require("../../../../config/settings");

const crypto = require('crypto');
const xlsx = require('node-xlsx');
const moment = require("moment");


class LaoActionApi extends APIBase {
    constructor() {
        super();
        this.signUrl = "https://bpohhr.gongsibao.com/ec3rd?appId=lwb";
        this.usersSve = system.getObject("service.operator.usersSve");
        this.logSve = system.getObject("service.operator.logSve");
        this.recruitSve = system.getObject("service.operator.recruitSve");
        this.labourSve = system.getObject("service.operator.labourSve");
        this.workloadSve = system.getObject("service.common.workloadSve");
        this.userlabourSve = system.getObject("service.operator.userlabourSve");
        //this.uploadCtl = system.getObject("controller.common.uploadCtl");
        this.redisClient = system.getObject("util.redisClient");
        // this.restClient = system.getObject("util.restClient");
        this.smsClient = system.getObject("util.smsClient");
        this.vcodePrev = "lwb_vcode_";
        this.testPhones = ['13691046554', '13333333333'];
        this.restClient = system.getObject("util.restClient");
        this.taxinfoSve = system.getObject("service.operator.taxinfoSve");
        this.transactioninfoSve = system.getObject("service.operator.transactioninfoSve");

        this.msSve = system.getObject("service.common.msSve");
        this.userconfSve = system.getObject("service.operator.userconfSve");

        this.applyStatusMap = {
            10: "已申请",
            20: "待面试",
            30: "面试成功",
            40: "面试失败",
            50: "待签约",
            60: "签约成功",
        }

        // this.companyConfig = {
        //     yd: {
        //         signCompanyIds: [10173, 492],
        //         payCompanyIds: ['1152185172836229121', '1152186076306087937', '1165922409285480450', '1169516233595670529', '1174219506669584386', '1197064800073707522', '1199605424102690818'],
        //         companyInfo: {
        //             companyName: "上海韵达货运有限公司",
        //             taxType: "一般纳税人",
        //             contactName: "陈梁",
        //             contactEmail: "chenliang8725@yundasys.com",
        //             contactAddr: "上海市青浦区赵巷镇盈港东路6679号",
        //             bankAccount: "上海韵达货运有限公司",
        //             openBank: "邮政储蓄银行青浦支行",
        //             bankno: "100360752790012735",
        //             sign_body: "舟山兰和科技有限公司",
        //             signBeginTime: "2019-08-26",
        //             signEndTime: "2020-08-26",
        //             contract_url: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_247111576475725735201916135525735contract_yd.pdf",
        //             business_license: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_2671115777007820212019301813221yd_b.jpg",
        //         }
        //     },
        //     tfb: {
        //         signCompanyIds: [11410, 492],
        //         payCompanyIds: ['1187270470698082306', '1187272600083308546', '1187274198010056705', '1202100969987661826'],
        //         companyInfo: {
        //             companyName: "杭州淘粉吧网络技术股份有限公司",
        //             taxType: "一般纳税人",
        //             contactName: "王萍",
        //             contactEmail: "wangping@taofen8.com",
        //             contactAddr: "浙江省杭州市西湖区西斗门路9号福地创业园1号楼2楼",
        //             bankAccount: "杭州淘粉吧网络技术股份有限公司",
        //             openBank: "杭州银行学院路支行",
        //             bankno: "3301040160000822687",
        //             sign_body: "舟山兰和科技有限公司",
        //             signBeginTime: "2019-10-24",
        //             signEndTime: "2020-10-24",
        //             contract_url: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_59111576475747388201916135547388contract_tfb.pdf",
        //             business_license: "https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_142111576475271657201916134751657bl_tfb.jpg",
        //         }
        //     }
        // }

        // this.userConfig = {
        //     26: this.companyConfig.yd,
        //     29: this.companyConfig.yd,
        //     30: this.companyConfig.tfb
        // }
    }

    async testAES(pobj) {
        let str = "{a:1,b2:'2', c:333, d:\"北京公司宝\"}";
        console.log("str: " + str);
        let encry = this.encryption(str);
        console.log("encry: " + encry);
        let decry = this.decryption(encry);
        console.log("decry: " + decry);
        return 1;
    }

    async SmartLogin(obj) {
        let data = obj.data || "";
        if(!data) {
            return system.getResult(-1, `参数错误`);
        }
        data = this.decryption(data);
        try {
            data = JSON.parse(data);
            if(!data.userName) {
                return system.getResult(-1, `登录名称为空`);
            }
            if(!data.companyName) {
                return system.getResult(-1, `商户名称为空`);
            }
            if(!data.mchtId) {
                return system.getResult(-1, `商户号为空`);
            }
            var loginUser = await this.usersSve.findOne({mtchId: data.mchtId});
            if (loginUser) {
                loginUser.com_name = data.companyName;
                loginUser.mtchId = data.mchtId;
                await loginUser.save();
            } else {
                loginUser = await this.usersSve.create({
                    phone_no: data.userName,
                    user_type: "招人方",
                    status_type: 1,
                    status_name: "正常",
                    reg_time: (new Date()).Format("yyyy-MM-dd"),
                    com_type: 2,
                    com_name: data.companyName,
                    mtchId: data.mchtId,
                });
            }
            //var user_id = 1;
            await this.logSve.SaveLogInfo({
                user_id: loginUser.id,
                oper_type: 0,
                oper_name: "发薪系统自动登录",
                oper_date: (new Date()).Format("yyyy-MM-dd hh:mm:ss")
            });
            return system.getResultSuccess(loginUser);
        } catch (error) {
            console.log(error);
            return system.getResult(-1, `a${data}解析错误`);
        }
    }

    encryption(data) {
        if(!data) {
            return "";
        }
        let AES_conf = settings.apiconfig.AES;
        let key = AES_conf.key;
        let iv = AES_conf.iv;
        // let padding = AES_conf.padding;

        var cipherChunks = [];
        var cipher = crypto.createCipheriv('aes-128-cbc', key, iv);
        cipher.setAutoPadding(true);
        cipherChunks.push(cipher.update(data, 'utf8', 'base64'));
        cipherChunks.push(cipher.final('base64'));
        return cipherChunks.join('');
    }

    decryption(data){
        if(!data) {
            return "";
        }
        let AES_conf = settings.apiconfig.AES;
        let key = AES_conf.key;
        let iv = AES_conf.iv;
        // let padding = AES_conf.padding;

        var cipherChunks = [];
        var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
        decipher.setAutoPadding(true);
        cipherChunks.push(decipher.update(data, 'base64', 'utf8'));
        cipherChunks.push(decipher.final('utf8'));
        return cipherChunks.join('');
    }

    async test(pobj, query) {
        return system.getResultSuccess({
            hello: "ok"
        });
    }

    getVCode() {
        var randomNum = "" + Math.round(Math.random() * 1000000);
        while (randomNum.length < 6) {
            randomNum = "0" + randomNum;
        }
        console.info("randomNum is ========", randomNum);
        return randomNum;
    }

    /**
     * 删除招聘或者是供招的信息
     * @param {*} obj
     * @userId    用户信息
     * @id        删除记录的id
     * @type      删除类型
     */
    async RemRecOrLob(obj) {
        if (!obj.type) {
            return system.getResult(-1, `参数错误 删除类型不能为空`);
        }
        if (!obj.userId) {
            return system.getResult(-1, `参数错误 用户ID不能为空`);
        }
        if (!obj.id) {
            return system.getResult(-1, `参数错误 删除记录ID不能为空`);
        }
        let params = {};
        params.type = this.trim(obj.type);
        params.userId = Number(this.trim(obj.userId));
        params.id = Number(this.trim(obj.id));
        try {
            if (params.type == "10") {   //招聘的
                return await this.recruitSve.RemRecOrLob(params);
            } else if (params.type == "20") {  //供人的
                return await this.labourSve.RemRecOrLob(params);
            } else {
                return system.getResult(-1, `参数错误 删除类型不存在`);
            }
        } catch (error) {
            return system.getResult(-1, `系统错误 错误信息 ${error}`);
        }
    }

    // async SendSms(obj) { //用户登录,返回用户信息
    //   if (!obj.phone_no) {
    //     return system.getResult(null, "电话号码不能为空");
    //   }
    //   var phone_no = this.trim(obj.phone_no);
    //
    //   try {
    //     if (!/^1[23456789]\d{9}$/.test(phone_no)) {
    //       return system.getResult(null, "手机号码格式不正确");
    //     }
    //     let data=null,_result={data:"发送成功"};
    //     //如果是短信模板则直接发送短信
    //     if(obj.templateName=="smsTemplate"){
    //       data= {
    //         "templateName": "smsTemplate",               // 模板类型 loginTemplate（登陆） authenticationTemplate（验证） smsTemplate(短信通知)
    //         "phoneNumbers": phone_no,                    // 手机号
    //         "name":this.trim(obj.name),                             // 模板参数 默认字段 如果是短信通知模板，则请勿传值
    //       }
    //       _result = await this.msSve.SendSms(data);
    //     }else{
    //       var isTest = this.testPhones.indexOf(phone_no) != -1;
    //       // 生成验证码
    //       var key = this.vcodePrev + phone_no;
    //       var vcode = await this.redisClient.get(key + "t");
    //       if (!vcode) {
    //         vcode = isTest ? "123123" : await this.getVCode();
    //         await this.redisClient.setWithEx(key, vcode, 5 * 60);
    //         await this.redisClient.setWithEx(key + "t", vcode, 60);
    //         var msg = "您的验证码为" + vcode + ", (切勿将验证码告知别人, 请在5分钟内输入完成验证, 如有问题请联系客服。)";
    //         if (!isTest) {
    //           // var rs = await this.smsClient.sendMsg(phone_no, msg);
    //           data = {
    //             "templateName": obj.templateName,            // 模板类型 loginTemplate（登陆） authenticationTemplate（验证） smsTemplate(短信通知)
    //             "phoneNumbers": phone_no,                    // 手机号
    //             "code":vcode,                                // 模板参数 默认字段 如果是短信通知模板，则请勿传值
    //           }
    //           _result = await this.msSve.SendSms(data);
    //         }
    //       }
    //     }
    //     return _result;
    //   } catch (error) {
    //     return system.getResultFail(500, "接口异常：" + error.message);
    //   }
    // }

    async SendSms(obj) { //用户登录,返回用户信息
        if (!obj.phone_no) {
            return system.getResult(null, "电话号码不能为空");
        }
        var phone_no = this.trim(obj.phone_no);

        try {
            if (!/^1[23456789]\d{9}$/.test(phone_no)) {
                return system.getResult(null, "手机号码格式不正确");
            }

            var isTest = this.testPhones.indexOf(phone_no) != -1;
            // 生成验证码
            var key = this.vcodePrev + phone_no;
            var vcode = await this.redisClient.get(key + "t");
            if (!vcode) {
                vcode = isTest ? "123123" : await this.getVCode();
                await this.redisClient.setWithEx(key, vcode, 5 * 60);
                await this.redisClient.setWithEx(key + "t", vcode, 60);
                var msg = "您的验证码为" + vcode + ", (切勿将验证码告知别人, 请在5分钟内输入完成验证, 如有问题请联系客服。)";
                if (!isTest) {
                    var rs = await this.smsClient.sendMsg(phone_no, msg);
                    console.log(rs);
                }
            }
            return system.getResultSuccess("发送成功");
        } catch (error) {
            return system.getResultFail(500, "接口异常：" + error.message);
        }
    }

    async UserLogOut(obj) { //用户登出
        if (!obj.user_id) {
            return system.getResult(null, "用户id不能为空");
        }
        try {
            var parm = {
                user_id: obj.user_id,
                oper_type: 1,
                oper_name: "登出",
                oper_date: (new Date()).Format("yyyy-MM-dd hh:mm:ss")
            };
            await this.logSve.SaveLogInfo(parm);
            return system.getResult("退出登录成功！");
        } catch (error)  {
            console.log(error);
            return system.getResult(null, "退出登录失败！");
        }
    }

    async UserLogIn(obj) { //用户登录,返回用户信息
        if (!obj.phone_no) {
            return system.getResult(null, "电话号码不能为空");
        }
        try {
            var phone_no = this.trim(obj.phone_no);
            var vcode = this.trim(obj.vcode);

            var key = this.vcodePrev + phone_no;
            var code = await this.redisClient.get(key) || "";
            if (!code) {
                return system.getResult(null, "验证码已失效，请再1分钟之内输入");
            }
            if (vcode != code) {
                return system.getResult(null, "验证码错误，请重新输入");
            }



            var parm = {
                phone_no: phone_no
            }
            var result = await this.usersSve.findUserInfoByPhone(parm);
            if (result.status == -1) {
                parm = {
                    phone_no: phone_no,
                    user_type: "招人方",
                    status_type: 1,
                    status_name: "正常",
                    reg_time: (new Date()).Format("yyyy-MM-dd")
                };
                result = await this.usersSve.SaveUserInfo(parm);
            }
            var user_id = result.data.id;
            //var user_id = 1;
            parm = {
                user_id: user_id,
                oper_type: 0,
                oper_name: "登录",
                oper_date: (new Date()).Format("yyyy-MM-dd hh:mm:ss")
            };
            await this.logSve.SaveLogInfo(parm);
            return result;
        } catch (e) {
            console.log(e);
            return system.getResult(null, "登录失败！");
        }

    }

    async SaveRecruitInfo(obj) { //添加或更新招聘信息,返回添加或更新后的信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }
        var parm = {};
        parm.id = obj.id;
        parm.recruit_name = obj.recruit_name;
        parm.recruit_type = obj.recruit_type;
        parm.recruit_count = obj.recruit_count;
        parm.pay_name = obj.pay_name;
        if (obj.pay_name == "月薪") {
            parm.pay_type = 1;

        } else if (obj.pay_name == "日薪") {
            parm.pay_type = 2;
        } else if (obj.pay_name == "时薪") {
            parm.pay_type = 3;
        }
        if (obj.pay_unit) {
            parm.pay_unit = obj.pay_unit * 100; //按分存储
        }
        parm.work_duration = Number(obj.work_duration || 0);
        if (obj.basic_salary) {
            parm.basic_salary = obj.basic_salary * 100;
        }
        if (obj.compre_salary) {
            parm.compre_salary = obj.compre_salary * 100;
        }
        if (obj.rfee_type == "月返") {
            parm.rfee_type = 1;
        } else if (obj.rfee_type == "日返") {
            parm.rfee_type = 2;
        } else if (obj.rfee_type == "时返") {
            parm.rfee_type = 3;
        } else if (obj.rfee_type == "一次返") {
            parm.rfee_type = 4;
        } else if (obj.rfee_type == "面议") {
            parm.rfee_type = 0;
        }
        if (obj.rfee_unit) {
            parm.rfee_unit = obj.rfee_unit * 100; //按分存储
        }
        parm.rfee_duration = obj.rfee_duration;
        parm.rfee_time = obj.rfee_time;
        parm.age_range = obj.age_range;
        parm.work_address = obj.work_address;
        parm.publish_date = (new Date()).Format("yyyy-MM-dd");
        parm.end_date = obj.end_date;
        parm.pic_path = obj.pic_path;
        parm.recrui_require = obj.recrui_require;
        parm.phone_no = obj.phone_no;
        parm.counter_mark = obj.counter_mark;
        parm.user_id = obj.user_id;
        parm.cur_type = obj.cur_type;
        if (obj.cur_type == 1) {
            parm.cur_status = "展示中";
        } else if (obj.cur_type == 2) {
            parm.cur_status = "已下架";
        } else if (obj.cur_type == 3) {
            parm.cur_status = "已过期";
        } else if (obj.cur_type == 4) {
            parm.cur_status = "审核未通过";
        }
        var result = await this.recruitSve.SaveRecruitInfo(parm);
        return system.getResult(result.data.dataValues);
    }

    async SaveLabourInfo(obj) { //添加或更新招工信息，返回添加或更新后的招工信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }

        var parm = {};
        parm.id = obj.id;
        parm.labour_type = obj.labour_type;
        parm.labour_count = obj.labour_count;
        parm.age_range = obj.age_range;
        parm.sex_ratio = obj.sex_ratio;
        parm.labour_address = obj.labour_address;
        parm.report_date = obj.report_date;
        parm.work_address = obj.work_address;
        parm.situation_memo = obj.situation_memo;
        parm.phone_no = obj.phone_no;
        parm.user_id = Number(obj.user_id || 0);
        parm.cur_type = obj.cur_type;
        if (obj.cur_type == 1) {
            parm.cur_status = "展示中";
        } else if (obj.cur_type == 2) {
            parm.cur_status = "已下架";
        } else if (obj.cur_type == 3) {
            parm.cur_status = "已过期";
        } else if (obj.cur_type == 4) {
            parm.cur_status = "审核未通过";
        }
        parm.publish_date = (new Date()).Format("yyyy-MM-dd");
        parm.pic_path = obj.pic_path;
        var result = await this.labourSve.SaveLabourInfo(parm);
        return system.getResult(result.data.dataValues);

    }

    async SaveUserLabourInfo(obj) { //添加或更新应聘信息,返回添加或更新后的信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }
        var parm = {};
        parm.id = obj.id;
        parm.user_id = obj.user_id;
        if (obj.labour_id) {
            parm.labour_id = obj.labour_id;
        }
        parm.recruit_id = obj.recruit_id;
        parm.labour_user_id = obj.labour_user_id;
        if (obj.ecid) {
            parm.ecid = obj.ecid;
        }

        if (obj.apply_stauts == "已申请") {
            parm.apply_stauts = 10;
        } else if (obj.apply_stauts == "邀请面试") {
            parm.apply_stauts = 20;
        } else if (obj.apply_stauts == "面试成功") {
            parm.apply_stauts = 30;
        } else if (obj.apply_stauts == "面试失败") {
            parm.apply_stauts = 40;
        } else if (obj.apply_stauts == "待签约") {
            parm.apply_stauts = 50;
        } else if (obj.apply_stauts == "签约成功") {
            parm.apply_stauts = 60;
        }

        if (obj.interview_time) {
            parm.interview_time = obj.interview_time;
        }

        if (obj.sign_at) {
            parm.sign_at = obj.sign_at;
        }

        if (obj.contract_url) {
            parm.contract_url = obj.contract_url;
        }

        var result = await this.userlabourSve.SaveUserLabourInfo(parm);
        return system.getResult(result.data.dataValues);
    }

    async FindUserLabourInfo(obj) {//获取应聘信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }
        var temp_info = {};
        var parm = {};
        var isAdmin = obj.isAdmin;
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }

        if (obj.id) {
            parm.id = obj.id;
        }
        if (obj.user_id) {
            parm.user_id = obj.user_id;
        }
        if (obj.labour_id) {
            parm.labour_id = obj.labour_id;
        }
        if (obj.recruit_id) {
            parm.recruit_id = obj.recruit_id;
        }
        if (obj.labour_user_id) {
            parm.labour_user_id = obj.labour_user_id;
        }
        if (obj.ecid) {
            parm.ecid = obj.ecid;
        }
        if (obj.apply_stauts) {
            if (obj.apply_stauts == "已申请") {
                parm.apply_stauts = 10;
            } else if (obj.apply_stauts == "邀请面试") {
                parm.apply_stauts = 20;
            } else if (obj.apply_stauts == "面试成功") {
                parm.apply_stauts = 30;
            } else if (obj.apply_stauts == "面试失败") {
                parm.apply_stauts = 40;
            } else if (obj.apply_stauts == "待签约") {
                parm.apply_stauts = 50;
            } else if (obj.apply_stauts == "签约成功") {
                parm.apply_stauts = 60;
            }
        }
        temp_info = await this.userlabourSve.finduserlabourByWhere(parm);
        if (temp_info && temp_info.status == 0 && temp_info.data.rows.length > 0) {
            try {
                for (var i = 0; i < temp_info.data.rows.length; i++) {
                    let cominfo = await this.usersSve.findUserInfoByid(temp_info.data.rows[i].user_id);
                    if (cominfo) {
                        temp_info.data.rows[i].com_name = cominfo.com_name;
                        temp_info.data.rows[i].information = cominfo.information;
                    } else {
                        temp_info.data.rows[i].com_name = "";
                        temp_info.data.rows[i].information = "";
                    }

                    temp_info.data.rows[i].apply_stauts_name = this.applyStatusMap[temp_info.data.rows[i].apply_stauts];

                    var recruiinfo = await this.recruitSve.findById(temp_info.data.rows[i].recruit_id);
                    if (recruiinfo) {
                        temp_info.data.rows[i].recruit_name = recruiinfo.recruit_name;
                        temp_info.data.rows[i].work_address = recruiinfo.work_address;
                    } else {
                        temp_info.data.rows[i].recruit_name = "";
                        temp_info.data.rows[i].work_address = "";
                    }

                    var userinfo = await this.usersSve.findUserInfoByid(temp_info.data.rows[i].labour_user_id);
                    if (userinfo) {
                        temp_info.data.rows[i].phone_no = userinfo.phone_no;
                        temp_info.data.rows[i].user_name = userinfo.user_name;
                        temp_info.data.rows[i].id_card = userinfo.id_card;
                    } else {
                        temp_info.data.rows[i].phone_no = "";
                        temp_info.data.rows[i].user_name = "";
                        temp_info.data.rows[i].id_card = "";
                    }

                    // userId=5&ecid=495
                    if (userinfo && temp_info.data.rows[i].ecid && temp_info.data.rows[i].apply_stauts == 50) {
                        temp_info.data.rows[i].signUrl = this.signUrl + `&userId=${userinfo.id}&&ecid=${temp_info.data.rows[i].ecid}`;
                    }
                }

                return temp_info;
            } catch (e) {
                console.log(e);
                return system.getResult(null, "获取数据失败");
            }
        } else {
            //console.log(e);
            if (isAdmin) {
                return system.getResultSuccess({count: 0, rows: []});
            } else {
                return system.getResult(null, "获取数据为空");
            }
        }
    }

    // 我的应聘-邀请面试
    async inviteInterview(obj) {
        let id = Number(obj.id || 0);
        let interviewTime = moment(obj.interviewTime);

        let userlabour = await this.userlabourSve.findById(id);
        if (!userlabour) {
            return system.getResult(null, "应聘信息不存在");
        }

        if (userlabour.apply_stauts != 10) {
            return system.getResult(null, "已邀请");
        }

        userlabour.apply_stauts = 20;
        userlabour.interview_time = interviewTime;

        await userlabour.save();
        return system.getResultSuccess();
    }

    // 我的应聘-面试 成功or失败
    async interviewResult(obj) {
        let id = Number(obj.id || 0);
        let userlabour = await this.userlabourSve.findById(id);
        if (!userlabour) {
            return system.getResult(null, "应聘信息不存在");
        }

        if (userlabour.apply_stauts != 20) {
            return system.getResult(null, "面试结果已处理");
        }

        if (obj.success) {
            userlabour.apply_stauts = 30;
        } else {
            userlabour.apply_stauts = 40;
        }

        await userlabour.save();
        return system.getResultSuccess();
    }

    // 我的应聘-发起签约
    async inviteSign(obj) {
        let id = Number(obj.id || 0);
        let ecid = Number(obj.ecid || 0);
        let userlabour = await this.userlabourSve.findById(id);
        if (!userlabour) {
            return system.getResult(null, "应聘信息不存在");
        }

        if (userlabour.apply_stauts != 30) {
            return system.getResult(null, "已发起签约");
        }
        userlabour.apply_stauts = 50;
        // var userInfo = await this.usersSve.findById(userlabour.user_id);
        // if(userInfo.information){
        //     userlabour.apply_stauts = 45;
        // }
        userlabour.ecid = ecid;
        await userlabour.save();
        return system.getResultSuccess();
    }


    //添加信息
    async addComplete(obj){
        if(!obj){
            return system.getResult(null, "参数不能为空");
        }
        if(!obj){
            return system.getResult(null, "招聘id不能为空");
        }
        var userlabour = await this.userlabourSve.findById(obj.id);

        if(userlabour){
            userlabour.nation= obj.nation;
            userlabour.marital_status= obj.marital_status;
            userlabour.is_children = obj.is_children;
            userlabour.opening_bank= obj.opening_bank;
            userlabour.education_back= obj.education_back;
            userlabour.graduate_ins= obj.graduate_ins;
            userlabour.place_domicile = obj.place_domicile;
            userlabour.current_residence= obj.current_residence;
            userlabour.urgency_person= obj.urgency_person;
            userlabour.contact_way= obj.contact_way;
            userlabour.name = obj.name;
            userlabour.id_no = obj.id_no;
            userlabour.card_no = obj.card_no;
            userlabour.sex = obj.sex;
            userlabour.age = obj.age;
            userlabour.birthday = obj.birthday;
            userlabour.save();
        }
        return system.getResult(userlabour);
    }


    async FindRecruitInfo(obj) { //获取招聘信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }
        var find_type = obj.find_type;
        var temp_info = {};
        var parm = {};
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }
        // if(obj.curStatus){
        //     parm.curStatus=this.trim(obj.curStatus);
        // }
        if (obj.curType) {
            parm.curType = this.trim(obj.curType);
        }
        if (find_type == 0) {
            temp_info = await this.recruitSve.findAllList(parm);
        } else if (find_type == 1) {
            parm.user_id = obj.find_info;
            temp_info = await this.recruitSve.findListByUserid(parm);
        } else if (find_type == 2) {
            parm.recruit_name = obj.find_info;
            temp_info = await this.recruitSve.findListByName(parm);
        } else if (find_type == 3) {
            parm.counter_mark = obj.find_info;
            temp_info = await this.recruitSve.findListByMark(parm);
        } else if (find_type == 4) {
            parm.work_address = obj.find_info;
            temp_info = await this.recruitSve.findListByAddress(parm);
        }

        if (temp_info.status == 0) {
            var list = [];
            var total_count = temp_info.data.count;
            for (var data of temp_info.data.rows) {
                var user_info = await this.usersSve.findUserInfoByid(data.user_id);
                list.push({
                    user_info: user_info,
                    data_info: data
                });
            }
            var res = {
                count: total_count,
                rows: list
            }
            return system.getResult(res);
        } else {
            console.log(e);
            return system.getResult(null, "获取数据失败");
        }
    }

    /**
     * 上架or下架
     * @param {*} obj
     */
    async UpdateCurStatus(obj) {
        //当前状态代码-1:展示中、2:已下架、3:已过期、4:审核未通过   cur_type
        // if(!this.trim(obj.curStatus)){
        //     return system.getResult(-1,`参数错误 状态不能为空`);
        // }
        if (!Number(this.trim(obj.curType))) {
            return system.getResult(-1, `参数错误 状态码不能为空`);
        }
        if (!Number(this.trim(obj.id))) {
            return system.getResult(-1, `参数错误 ID不能为空`);
        }
        try {
            return await this.recruitSve.UpdateCurStatus(obj);
        } catch (error) {
            return system.getResult(-1, `系统错误 错误信息 ${error}`);
        }
    }

    async FindLabourInfo(obj) { //获取供人信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }

        var find_type = obj.find_type;
        var temp_info = {};
        var parm = {};
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }

        if (find_type == 0) {
            temp_info = await this.labourSve.findAllList(parm);
        } else if (find_type == 1) {
            parm.user_id = obj.find_info;
            temp_info = await this.labourSve.findListByUserid(parm);
        }

        if (temp_info.status == 0) {
            var list = [];
            var total_count = temp_info.data.count;
            for (var data of temp_info.data.rows) {
                var user_info = await this.usersSve.findUserInfoByid(data.user_id);
                list.push({
                    user_info: user_info,
                    data_info: data
                });
            }
            var res = {
                count: total_count,
                rows: list
            }

            return system.getResult(res);
        } else {
            return system.getResult(null, "获取数据失败");
        }
    }

    async FindUserInfo(obj) { //无条件或者根据ID获取用户信息
        if (!obj) {
            return system.getResult(null, "参数不能为空");
        }
        var find_type = obj.find_type;
        var temp_info = {};
        var parm = {};
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }
        try {
            if (find_type == 0) {
                temp_info = await this.usersSve.findAllList(parm);
                return temp_info;
            } else if (find_type == 1) {
                parm.user_id = obj.find_info;
                temp_info = await this.usersSve.findUserInfoByid(parm.user_id);
                var list = [];
                list.push(temp_info)
                var tem_res = {
                    count: list.length,
                    rows: list
                }
                return system.getResult(tem_res);
            }
        } catch(error) {
            console.log(error);
            return system.getResult(null, "获取数据失败");
        }
    }

    async FindUserInfoByWhere(obj) { //根据条件获取用户或者企业信息
        var parm = obj;
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }
        return await this.usersSve.findUserInfo(parm);
    }

    async FindlabourByWhere(obj) { //根据条件获取招工信息
        var parm = obj;
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }
        if (obj.com_name) {
            var userobj = {};
            userobj.com_name = obj.com_name;
            var userinfo = await this.usersSve.findUserInfo(userobj);
            if (userinfo.status == 1) {
                parm.user_id = userinfo.data[0].user_id;
            }
        }
        return await this.labourSve.findlabourByWhere(parm);
    }

    async notifyInterview(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户id不存在");
        }

        if (!obj.id) {
            return system.getResult(null, "人才id不存在");
        }

        if (!obj.recruit_id) {
            return system.getResult(null, "请选择招聘信息");
        }

        try {
            let rs = await this.labourSve.notifyInterview(obj);
            return system.getResultSuccess(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    async FindTransactionByIdno(obj) { //根据身份证获取报酬信息
        var parm = obj;
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }

        if (obj.id_no) {
            parm.id_no = obj.id_no;
        }
        return await this.transactioninfoSve.findListByIdno(parm);
    }

    async taxinfoListByIdnoAndYear(obj) {
        var parm = obj;
        if (obj.id_no) {
            parm.id_no = obj.id_no;
        }
        if (obj.tax_year) {
            parm.tax_year = obj.tax_year
        }

        return await this.taxinfoSve.taxinfoListByIdnoAndYear(parm);
    }

    async FindRecruitByWhere(obj) { //根据条件获取招聘信息
        var parm = obj;
        if (obj.page_size) {
            parm.page_size = Number(obj.page_size);
        } else {
            parm.page_size = 10;
        }

        if (obj.current_page) {
            parm.current_page = Number(obj.current_page);
        } else {
            parm.current_page = 1;
        }
        parm.user_id = obj.userId;
        // if (obj.com_name) {
        //   var userobj = {};
        //   userobj.com_name = obj.com_name;
        //   var userinfo = await this.usersSve.findUserInfo(userobj);
        //   if (userinfo.status == 1) {
        //     parm.user_id = userinfo.data[0].user_id;
        //   }
        // }
        return await this.recruitSve.findRecruitByWhere(parm);
    }

    async UpdateUserLabourStatusInfo(obj) {//根据id更新应聘信息
        if (!obj.id || !obj.apply_stauts) {
            return system.getResult(null, "参数错误");
        }

        try {
            var re = await this.userlabourSve.updateStatus(obj);
            if (re == 1) {
                return system.getResult(re);
            } else {
                return system.getResult(null, "更新数据失败");
            }
        } catch(e) {
            console.log(e);
            return system.getResult(null, "更新失败！");
        }

    }

    async updateUserInfo(obj) { //根据id更新用户信息
        if (!obj.id) {
            return system.getResult(null, "参数错误");
        }

        try {
            if (obj.phone_no) {
                var phone_no = this.trim(obj.phone_no);
                if (!/^1[23456789]\d{9}$/.test(phone_no)) {
                    return system.getResult(null, "手机号码格式不正确");
                }

                if (obj.vcode) {
                    var vcode = this.trim(obj.vcode);


                    var key = this.vcodePrev + phone_no;
                    var code = await this.redisClient.get(key) || "";
                    if (!code) {
                        return system.getResult(null, "验证码已失效，请再1分钟之内输入");
                    }
                    if (vcode != code) {
                        return system.getResult(null, "验证码错误，请重新输入");
                    }
                } else {
                    return system.getResult(null, "验证码为空，请输入验证码");
                }

            }

            var result = await this.usersSve.updateUserInfo(obj);
            if (result == 1) {
                var user_info = await this.usersSve.findUserInfoByid(obj.id);
                return system.getResult(user_info);
            } else {
                return system.getResult(null, "更新失败");
            }
        } catch(e) {
            console.log(e);
            return system.getResult(null, "更新失败！");
        }

    }

    async updateUserInfo2(obj) { //根据id更新用户信息
        if (!obj.id) {
            return system.getResult(null, "参数错误");
        }

        try {
            var result = await this.usersSve.updateUserInfo(obj);
            if (result == 1) {
                var user_info = await this.usersSve.findUserInfoByid(obj.id);
                return system.getResult(user_info);
            } else {
                return system.getResult(null, "更新失败");
            }
        } catch(e) {
            console.log(e);
            return system.getResult(null, "更新失败！");
        }

    }

    async UpdateLabourStatus(obj) { //更新劳工信息审核状态
        if (!obj.id || !obj.cur_status) {
            return system.getResult(null, "参数不能为空");
        }
        var re = await this.labourSve.updatestatus(obj);
        if (re == 1) {
            return system.getResult(re);
        } else {
            return system.getResult(null, "更新数据失败");
        }
    }

    async UpdateRecruitStatus(obj) { //更新招聘信息审核状态
        if (!obj.id || !obj.cur_status) {
            return system.getResult(null, "参数不能为空");
        }
        var re = await this.recruitSve.updatestatus(obj);
        if (re == 1) {
            return system.getResult(re);
        } else {
            return system.getResult(null, "更新数据失败");
        }
    }

    async UpdateAccountStatus(obj) { //更新账户状态信息
        if (!obj.id || !obj.cur_status) {
            return system.getResult(null, "参数不能为空");
        }
        var re = await this.usersSve.updateAccountstatus(obj);
        if (re == 1) {
            return system.getResult(re);
        } else {
            return system.getResult(null, "更新数据失败");
        }
    }

    async UpdateUserStatus(obj) { //更新用户实名认证信息
        if (!obj.id || !obj.cur_status) {
            return system.getResult(null, "参数不能为空");
        }
        var re = await this.usersSve.updateUserstatus(obj);
        if (re == 1) {
            return system.getResult(re);
        } else {
            return system.getResult(null, "更新数据失败");
        }
    }

    async UpdateCompanyStatus(obj) { //更新企业实名认证信息
        if (!obj.id || !obj.cur_status) {
            return system.getResult(null, "参数不能为空");
        }
        var re = await this.usersSve.updateCompanystatus(obj);
        if (re == 1) {
            return system.getResult(re);
        } else {
            return system.getResult(null, "更新数据失败");
        }
    }

    /**
     * 定时更新招聘信息
     */
    async UpdateRecruitExpired() {
        try {
            await this.recruitSve.UpdateRecruitExpired();
        } catch (error) {
            console.log(`系统错误 错误信息${error}`);
        }
    }

    async ParamRecruitExcel(obj) {//批量导入招聘信息
        if (!obj.userId || !obj.ossUrl) {
            return system.getResult(null, "参数不能为空");
        }
        var userId = obj.userId;
        var ossurl = obj.ossUrl;
        var dataList = [];
        var filePath = "/tmp/recruit_info_" + userId + ".xlsx";
        try {
            await this.restClient.execDownload("'" + ossurl + "'", filePath);
            var sheets = xlsx.parse(filePath);
            var rows = sheets[0].data;
            for (var i = 2; i < rows.length; i++) {
                var cells = rows[i];
                var data = {};
                data.recruit_name = "" + cells[1];
                data.recruit_type = "" + cells[2];
                data.recruit_count = "" + cells[3];
                data.pay_name = "" + cells[4];
                if (data.pay_name == "月薪") {
                    data.pay_type = 1;
                } else if (data.pay_name == "日薪") {
                    data.pay_type = 2;
                } else if (data.pay_name == "时薪") {
                    data.pay_type = 3;
                } else {
                    data.pay_type = null;
                }
                data.pay_unit = null;//少一个薪资单价
                var temp = "" + cells[5];
                if (temp && temp != "—" && temp != "面议" && temp != "undefined") {
                    data.basic_salary = Number(temp) * 100;
                } else {
                    data.basic_salary = null;
                }
                temp = "" + cells[6];
                if (temp && temp != "—" && temp != "面议" && temp != "undefined") {
                    data.compre_salary = Number(temp) * 100;
                } else {
                    data.compre_salary = null;
                }
                temp = "" + cells[7];
                if (temp && temp != "—" && temp != "undefined") {
                    data.work_duration = Number(temp);
                } else {
                    data.work_duration = null;
                }
                temp = "" + cells[8];
                if (temp == "面议") {
                    data.rfee_type = 0;
                } else if (temp == "月返") {
                    data.rfee_type = 1;
                } else if (temp == "日返") {
                    data.rfee_type = 2;
                } else if (temp == "时返") {
                    data.rfee_type = 3;
                } else if (temp == "一次返") {
                    data.rfee_type = 4;
                } else {
                    data.rfee_type = null;
                }
                temp = "" + cells[9];
                if (temp && temp != "—" && temp != "undefined") {
                    var arr = temp.split("/");
                    if (arr.length == 2) {
                        data.rfee_duration = arr[0];
                        data.rfee_time = arr[1];
                    } else {
                        data.rfee_duration = null;
                        data.rfee_time = null;
                    }
                } else {
                    data.rfee_duration = null;
                    data.rfee_time = null;
                }

                temp = "" + cells[10];
                if (temp && temp != "undefined") {
                    data.age_range = temp;
                } else {
                    data.age_range = null;
                }

                temp = "" + cells[11];
                if (temp && temp != "undefined") {
                    data.work_address = temp;
                } else {
                    data.work_address = null;
                }
                data.publish_date = (new Date()).Format("yyyy-MM-dd");

                temp = "" + cells[12];
                if (temp && temp != "undefined") {
                    if (temp == "长期招聘") {
                        data.end_date = "1970-01-01";
                    } else {
                        data.end_date = new Date(1900, 0, temp - 1);;
                    }
                } else {
                    data.end_date = null;
                }

                // temp = "" + cells[14];
                // if (temp && temp != "undefined") {
                //     data.pic_path = temp;
                // } else {
                //     data.pic_path = null;
                // }

                temp = "" + cells[14];
                if (temp && temp != "undefined") {
                    data.recrui_require = temp;
                } else {
                    data.recrui_require = null;
                }

                temp = "" + cells[15];
                if (temp && temp != "undefined") {
                    data.phone_no = temp;

                } else {
                    data.phone_no = null;
                    //data.user_id = null;
                }

                temp = "" + cells[13];
                if (temp && temp != "undefined") {
                    var parm = {
                        user_name: temp,
                        find_type: 0,
                        real_status: "企业已认证"

                    }
                    var user_info = await this.usersSve.findUserInfo(parm);
                    if (user_info.status == -1) {
                        data.user_id = null;
                    } else {
                        if (user_info.data.count > 0) {
                            data.user_id = user_info.data.rows[0].id;
                        } else {
                            data.user_id = null;
                        }
                    }
                } else {
                    data.user_id = null;
                }

                data.counter_mark = null;
                data.cur_type = 1;
                data.cur_status = "展示中";
                dataList.push(data)
            }

            obj.dataList = dataList;
            var re = await this.recruitSve.ParamRecruitExcel(obj)
            if (re == 1) {
                return system.getResult(re);
            } else {
                return system.getResult(null, "插入数据失败");
            }
        } catch (e) {
            console.log(e);
            return system.getResult(null, "接口异常");
        }

    }

    // 工作量确认单
    async paramXlsx(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }
        try {
            var rs = await this.workloadSve.paramXlsx(obj.userId, obj.ossUrl);
            if (rs.code == 0) {
                return system.getErrResult2(rs.msg || "文件解析失败");
            }
            return system.getResult2(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    // 列表
    async workLoadPage(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }

        try {
            obj.status = 0;
            var rs = await this.workloadSve.pageByCondition(obj);
            return system.getResultSuccess(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    async workLoadHistoryInfo(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }

        try {
            var rs = await this.workloadSve.historyInfo(obj);
            return system.getResultSuccess(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    // 确认/全部
    async workloadConfirm(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }

        try {
            var rs = await this.workloadSve.workloadConfirm(obj);
            return system.getResultSuccess(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    async workloadTotal(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }

        try {
            obj.pageSize = 1;
            obj.status = 1;
            var rs = await this.workloadSve.pageByCondition(obj);
            if (!rs || !rs.count) {
                return system.getResultSuccess(0);
            }
            return system.getResultSuccess(rs.count);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }


    // 确认列表
    async workloadHistory(obj) {
        if (!obj.userId) {
            return system.getResult(null, "用户未登录");
        }

        try {
            obj.status = 0;
            var rs = await this.workloadSve.historyPage(obj);
            return system.getResultSuccess(rs);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    // 企业信息，家属拒
    async companyInfo(qobj) {
        try {
            let config = await this.userconfSve.findById(qobj.userId);
            // let config = this.userConfig[qobj.userId];
            if (!config) {
                return system.getResultSuccess({});
            }
            let companyInfo;
            try {
                companyInfo = JSON.parse(config.companyInfo || "{}");
            } catch (e) {
                console.log(e.stack);
                companyInfo = {};
            }
            return system.getResultSuccess(companyInfo);
        } catch (e) {
            console.log(e);
            return system.getErrResult2("您的网络不稳, 请稍后重试")
        }
    }

    async getOssConfig() {
        var policyText = {
            "expiration": "2119-12-31T16:00:00.000Z",
            "conditions": [
                ["content-length-range", 0, 1048576000],
                ["starts-with", "$key", "zc"]
            ]
        };
        var accesskey = 'DHmRtFlw2Zr3KaRwUFeiu7FWATnmla';
        var accessKeyId = 'LTAIyAUK8AD04P5S';
        var url = "https://gsb-zc.oss-cn-beijing.aliyuncs.com";
        var b = new Buffer(JSON.stringify(policyText));
        var policyBase64 = b.toString('base64');
        var signature = crypto.createHmac('sha1', accesskey).update(policyBase64).digest().toString('base64'); //base64

        var data = {
            OSSAccessKeyId: accessKeyId,
            policy: policyBase64,
            Signature: signature,
            Bucket: 'gsb-zc',
            success_action_status: 201,
            url: url
        };

        return data;
    };

    exam() {
        return "xxx";
    }

    classDesc() {
        return {
            groupName: "auth",
            groupDesc: "认证相关的包",
            name: "AccessAuthAPI",
            desc: "关于认证的类",
            exam: "",
        };
    }

    methodDescs() {
        return [{
            methodDesc: "生成访问token",
            methodName: "getAccessKey",
            paramdescs: [{
                paramDesc: "访问appkey",
                paramName: "appkey",
                paramType: "string",
                defaultValue: "x",
            },
                {
                    paramDesc: "访问secret",
                    paramName: "secret",
                    paramType: "string",
                    defaultValue: null,
                }
            ],
            rtnTypeDesc: "xxxx",
            rtnType: "xxx"
        }];
    }

    /**
     * 纳税信息
     * @param {*} obj
     */
    async taxinfoListByMonth(obj) {
        try {
            return await this.taxinfoSve.taxinfoListByMonth(obj);
        } catch (error) {
            console.log(error);
            return system.getResult(null, `系统错误 错误信息${error}`);
        }
    }

    /**
     * 纳税信息 按照人信息
     * @param {*} obj
     */
    async taxinfoListByUser(obj) {
        try {
            return await this.taxinfoSve.taxinfoListByUser(obj);
        } catch (error) {
            console.log(error);
            return system.getResult(null, `系统错误 错误信息${error}`);
        }
    }

    /**
     * 纳税信息 明细
     * @param {*} obj
     */
    async taxinfoById(obj) {
        try {
            return await this.taxinfoSve.taxinfoById(obj);
        } catch (error) {
            console.log(error);
            return system.getResult(null, `系统错误 错误信息${error}`);
        }
    }

}

module.exports = LaoActionApi;

var tesk = new LaoActionApi();
var parm = {
    id_no: "140321199307270014",
    tax_year: "2019"
    //apply_stauts:"邀请面试"
    //ossUrl:"https://gsb-zc.oss-cn-beijing.aliyuncs.com//zc_wxapplet_1576396810278.xlsx"
    //labour_user_id:2,
    //apply_stauts:"已申请"
    //cur_status:"已过期"
    //memo_text:"sssssssss"
    //user_name:"高",
    //com_name:"京东"
};
tesk.taxinfoListByIdnoAndYear(parm).then(function (result) {
    console.log(result);
    console.log(result.data.rows[0]);
}).catch(function (e) {
    console.log(e);
});
