var APIBase = require("../../api.base");
var system = require("../../../system");
const crypto = require('crypto');
class LaoActionApi extends APIBase {
    constructor() {
        super();
        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.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'];
    }

    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) {
            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, "手机号码格式不正确");
            }

            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 {
            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");
        var result = await this.labourSve.SaveLabourInfo(parm);
        return system.getResult(result.data.dataValues);

    }

    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 {
            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 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;
        }
        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 updateUserInfo(obj) { //根据id更新用户信息
        if (!obj.id) {
            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, "更新失败");
        }
    }

    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 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"
        }];
    }
}
module.exports = LaoActionApi;

// var tesk = new LaoActionApi();
// var parm = {
//     // find_type:1,
//     // find_info:3,
//     //id:2,
//     //cur_status:"已过期"
//     //memo_text:"sssssssss"
//     //user_name:"高",
//     com_name:"京东"
//  };
// tesk.FindRecruitByWhere(parm).then(function(result){
//   console.log(result);
//   console.log(result.data.rows);
// }).catch(function(e){
//   console.log(e);
// });