'use strict';

const Subscription = require('egg').Subscription;
const moment = require('moment');

//促申请活动给用户添加奖品
class HuaYunPaas extends Subscription {
    // 通过 schedule 属性来设置定时任务的执行间隔等配置
    static get schedule() {
        return {
            cron: '0 0 0 * * *',//每天00:00点执行
            // cron: '*/1 * * * *',//每1分钟执行一次脚本
            type: 'worker',
            env: ['prod'],
            immediate: false
        };
    }

    // subscribe 是真正定时任务执行时被运行的函数
    async subscribe() {

        const { ctx, app } = this;
        if (['https://pro-nginx.jianbing.com', 'https://lan-nginx.jianbing.com', 'https://p.jianbing.com'].includes(this.config.NODE_BASE_URL)) {
            //用redis的setnx来实现锁机制
            let lock = 'huayun:pass:cron:' + moment().format('MMDD');
            ctx.logger.info(lock);
            ctx.logger.info(JSON.stringify(await app.redis.get(lock)));
            let redRes = await app.redis.setnx(lock, 1);
            ctx.logger.info('in cron');
            if (Number(redRes) === 1) {
                await app.redis.expire(lock, 2);
                ctx.logger.info('in redis');
                await this.logic();
            }
        }
    }

    async logic() {

        const { ctx } = this;
        this.callIn();
        this.callOut();

        return true;
    }

    async callIn() {

        const { ctx } = this;
        ctx.logger.info('in logic callIn');
        const accessToken = await this.getAccessToken('callIn');
        const url = `http://221.194.132.83:7780/paas/Interface/${accessToken}/CallIn`;
        const lastOne = await ctx.prometheusModel.HuayunPaasCallin.findOne({ order: [['end_time', 'desc']] });
        const start = 0;
        const limit = 10000;
        let start_time = moment().add(-1, 'days').format('YYYY-MM-DD HH:mm:ss');
        const now_time = moment().format('YYYY-MM-DD HH:mm:ss');
        if (lastOne && lastOne.end_time) {
            start_time = lastOne.end_time;
        }
        ctx.logger.info(JSON.stringify({ start_time, now_time, start, limit }));
        const result = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 500000, data: { start_time, end_time: now_time, start, limit } });
        const ret = result.data;
        // ctx.logger.info(JSON.stringify({ ret }));
        ctx.logger.info('get result callIn');
        if (ret.status != 0 || !ret.message || ret.count == 0) {
            return;
        }
        ctx.logger.info('in add callIn');
        const message = ret.message;
        const list = message.data;
        ctx.logger.info(message.count);
        const insert_data = await this.format(list);
        await ctx.prometheusModel.HuayunPaasCallin.bulkCreate(insert_data, { ignoreDuplicates: true });

    }

    async callOut() {

        const { ctx } = this;
        ctx.logger.info('in logic callOut');
        const accessToken = await this.getAccessToken('callOut');
        const url = `http://221.194.132.83:7780/paas/Interface/${accessToken}/CallOut`;
        const lastOne = await ctx.prometheusModel.HuayunPaasCallOut.findOne({ order: [['end_time', 'desc']] });
        const start = 0;
        const limit = 10000;
        let start_time = moment().add(-1, 'days').format('YYYY-MM-DD HH:mm:ss');
        const now_time = moment().format('YYYY-MM-DD HH:mm:ss');
        if (lastOne && lastOne.end_time) {
            start_time = lastOne.end_time;
        }
        ctx.logger.info(JSON.stringify({ start_time, now_time, start, limit }));
        const result = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 500000, data: { start_time, end_time: now_time, start, limit } });
        const ret = result.data;
        // ctx.logger.info(JSON.stringify({ ret }));
        ctx.logger.info('get result callOut');
        if (ret.status != 0 || !ret.message || ret.count == 0) {
            return;
        }
        ctx.logger.info('in add callOut');
        const message = ret.message;
        const list = message.data;
        ctx.logger.info(message.count);
        const insert_data = await this.format(list);
        await ctx.prometheusModel.HuayunPaasCallOut.bulkCreate(insert_data, { ignoreDuplicates: true });

    }

    async getAccessToken(type = 'callIn') {

        const { ctx } = this;

        let clientId = '961a170e-f939-4189-9163-c4c39051b586';
        let clientScr = '53ed566c-72b8-4ebf-b0bb-78147623be71';
        if (type === 'callOut') {
            clientId = 'c5e1bb68-207d-4164-852d-c206711dd431';
            clientScr = '6c9836c1-38ec-44db-8ef5-0f55b7825276';
        }

        const url = 'http://221.194.132.83:7780/paas/accreditation';
        const result = await ctx.helper.send_request(url, { clientId, clientScr });
        const ret = result.data;
        if (!ret || ret.status === 1 || !ret.message) {
            ctx.faild('get accessToken failed!');
        }
        // ctx.logger.info(JSON.stringify({ ret }));
        return ret.message;
    }

    async format(data) {

        if (!Array.isArray(data) || data.length === 0) {
            return [];
        }
        const ret = [];
        for (let i in data) {

            const item = data[i];
            ret.push({
                session_id: item.sessionId,
                start_time: item.startTime,
                end_time: item.endTime,
                remote_url: item.remoteUrl,
                local_url: item.localUrl,
                skill_name: item.skillName,
                listtime: item.listtime,
                duretion: item.duretion,
                keysser: item.keysser,
                end_type: item.end_type,
                agent_id: item.agentId,
                call_type: item.call_Type,
                r_start_time: item.r_startTime,
                r_end_time: item.r_endTime,
                path: item.path,
                c_ivr_key: item.cIvrKey,
                record_nama: item.record_Nama,
                created_at: moment().format('YYYY-MM-DD HH:mm:ss'),
            });
        }

        return ret;

    }
}

module.exports = HuaYunPaas;