'use strict';

const Controller = require('egg').Controller;
const moment = require('moment');
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }

  async setCookie() {

    const { ctx } = this;
    const expire = 7200 * 1000;
    const date = new Date();
    // ctx.cookies.set('auth_token', '0f42a68d19ef161a7c7665488e625ba8', { httpOnly: false, signed: false, maxAge: expire, expires: date, path: '/' });
    // ctx.cookies.set('jianbing_customer_id', '815209', { httpOnly: false, signed: false, maxAge: expire, expires: date, path: '/' });
    ctx.success(ctx.header.cookie);

  }

  async getAccessToken() {

    const { ctx } = this;

    // const clientId = '961a170e-f939-4189-9163-c4c39051b586';
    // const clientScr = '53ed566c-72b8-4ebf-b0bb-78147623be71';

    const clientId = 'c5e1bb68-207d-4164-852d-c206711dd431';
    const 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;
    // console.info(result);
    if (!ret || ret.status === 1 || !ret.message) {
      ctx.faild('get accessToken failed!');
    }

    return ret.message;
  }

  async format(data) {

    if (!Array.isArray(data) || data.length === 0) {
      return [];
    }
    // console.info(data);
    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;

  }

  format_callout(data) {

    if (!Array.isArray(data) || data.length === 0) {
      return [];
    }
    // console.info(data);
    const ret = [];
    const time = moment().format('YYYY-MM-DD HH:mm:ss');
    data.forEach(item => {
      ret.push({
        session_id: item.sessionId,
        start_time: item.startTime,
        end_time: item.endTime,
        remote_url: item.remoteUrl,
        local_url: item.localUrl,
        duretion: item.duretion,
        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: time,
      });
    });
    for (let i in data) {

      // const item = data[i];

    }

    return ret;

  }

  async callIn(accessToken) {

    const { ctx } = this;
    const url = `http://221.194.132.83:7780/paas/Interface/${accessToken}/CallIn`;
    let start_time = '2019-04-01 00:00:00';
    let end_time = '2019-04-30 23:59:59';

    const start = 0;
    const limit = 10000;
    const now_time = moment().format('YYYY-MM-DD HH:mm:ss');

    for (let i = 0; i < 15; i++) {

      const step_day = i === 0 ? 0 : 30;
      start_time = moment(start_time).add(step_day, 'days').format('YYYY-MM-DD HH:mm:ss');
      end_time = moment(end_time).add(step_day, 'days').format('YYYY-MM-DD HH:mm:ss');
      console.info(start_time, end_time);
      if (start_time >= now_time) {
        break;
      }

      const result = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 300000, data: { start_time, end_time, start, limit } });
      const ret = result.data;
      if (ret.status != 0 || !ret.message || ret.count == 0) {
        continue;
      }
      const message = ret.message;
      const list = message.data;
      const count = message.count;
      console.info(count);
      const insert_data = await this.format(list);
      await ctx.prometheusModel.HuayunPaasCallin.bulkCreate(insert_data, { ignoreDuplicates: true });
      if (count <= limit) {
        continue;
      }

      //分页查询
      const page = Math.ceil(count / limit);
      for (let j = 1; j <= page - 1; j++) {
        let start2 = j * limit;
        console.info(j, start_time, end_time, start2, limit);
        const result2 = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 300000, data: { start_time, end_time, start2, limit } });
        const ret2 = result2.data;
        if (ret2.status != 0 || !ret2.message || ret2.count == 0) {
          continue;
        }
        const message2 = ret2.message;
        const list2 = message2.data;
        const insert_data2 = await this.format(list2);
        await ctx.prometheusModel.HuayunPaasCallin.bulkCreate(insert_data2, { ignoreDuplicates: true });

      }

    }
  }

  async callOut(accessToken) {

    const { ctx } = this;

    const url = `http://221.194.132.83:7780/paas/Interface/${accessToken}/CallOut`;
    let start_time = '2019-01-01 00:00:00';
    let end_time = '2019-01-30 23:59:59';

    let start = 0;
    const limit = 10000;
    const now_time = moment().format('YYYY-MM-DD HH:mm:ss');

    for (let i = 0; i < 15; i++) {

      const step_day = i === 0 ? 0 : 30;
      start_time = moment(start_time).add(step_day, 'days').format('YYYY-MM-DD HH:mm:ss');
      end_time = moment(end_time).add(step_day, 'days').format('YYYY-MM-DD HH:mm:ss');
      console.info(start_time, end_time);
      if (start_time >= now_time) {
        break;
      }

      for (let j = 0; j <= 20; j++) {

        start = j * limit;
        console.info(j, start_time, end_time, start, limit);
        const result = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 900000, data: { start_time, end_time, start, limit } });
        const ret = result.data;
        if (ret.status != 0 || !ret.message || ret.count == 0) {
          continue;
        }
        const message = ret.message;
        const list = message.data;
        const count = message.count;
        console.info(count);
        if (!list || list.length === 0) break;
        const insert_data = this.format_callout(list);
        await ctx.prometheusModel.HuayunPaasCallOut.bulkCreate(insert_data, { ignoreDuplicates: true });
      }

      // if (count <= limit) {
      //   continue;
      // }

      continue;
      //分页查询
      const page = Math.ceil(count / limit);
      const p_result2 = [];
      for (let j = 1; j <= page - 1; j++) {
        // let start2 = j * limit;
        // console.info(j, start_time, end_time, start2, limit);
        // const result2 = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 900000, data: { start_time, end_time, start2, limit } });
        // const ret2 = result2.data;
        // if (ret2.status != 0 || !ret2.message || ret2.count == 0) {
        //   continue;
        // }
        // const message2 = ret2.message;
        // const list2 = message2.data;
        // console.info(message2.count);
        // const insert_data2 = await this.format_callout(list2);
        // await ctx.prometheusModel.HuayunPaasCallOut.bulkCreate(insert_data2, { ignoreDuplicates: true });

        let start2 = j * limit;
        console.info(j, start_time, end_time, start2, limit);
        p_result2[j] = ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 1000000, data: { start_time, end_time, start2, limit } });
      }

      const result2 = await Promise.all(p_result2).then(result => {//等待所有异步内容获取完成
        return result;
      }).catch(error => {
        ctx.failed(error);
      });

      // console.info(result2);
      let insert_data2 = [];
      for (let k in result2) {
        // console.info(result2[k]);
        if (!result2[k]) continue;
        const ret2 = result2[k].data;
        if (ret2.status != 0 || !ret2.message || ret2.count == 0) {
          continue;
        }
        const message2 = ret2.message;
        const list2 = message2.data;
        console.info(message2.count);
        let insert_data_temp = this.format_callout(list2);
        console.info(insert_data_temp.length);
        insert_data2 = insert_data2.concat(insert_data_temp);

      }
      // console.info(insert_data2.length);
      // await ctx.prometheusModel.HuayunPaasCallOut.bulkCreate(insert_data2, { ignoreDuplicates: true });
      console.info(insert_data2.length);

    }
  }

  async huayunCall() {

    const { ctx } = this;
    // const accessToken = await this.getAccessToken();
    const accessToken = 'b762900b54e633ce70c2111172c1df78';
    // this.callIn(accessToken);
    // this.callOut(accessToken);
    ctx.success({ status: true });
  }

  async huayunCallTest() {

    const { ctx } = this;
    let start_time = '2019-08-01 00:00:00';
    // let end_time = moment(start_time).add(30, 'days').format('YYYY-MM-DD HH:mm:ss');
    let end_time = '2019-08-30 23:40:00';
    // const accessToken = '8df0df02d9417a85bbadb3c3df1f6a03';
    const accessToken = await this.getAccessToken();
    console.info(accessToken);
    const start = 100;
    const limit = 100;
    // const session_id = '4421788439580105110';
    const url = `http://221.194.132.83:7780/paas/Interface/${accessToken}/CallOut`;
    // const result2 = await ctx.curl(url, { method: 'POST', contentType: 'json', dataType: 'json', timing: true, timeout: 50000, data: { start_time, end_time, start, limit } });
    // const last_one = await ctx.prometheusModel.HuayunPaasCallin.findOne({ order: [['id', 'desc']] });
    // const cpus = require('os').cpus();
    ctx.success({ status: accessToken });
    // ctx.success({ status: await this.getAccessToken() });
  }
}

module.exports = HomeController;
