'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');
const fs = require('fs');
const request = require('request');

class WechatController extends Controller {
  async test() {
    const { ctx, service } = this;
    const data = { MsgType: 'miniprogrampage' };
    await service.course.v4.wechat.sendMsg(data);
    ctx.success();
  }

  async callbackAction() {
    const { ctx, service } = this;
    await service.course.v4.wechat.callbackAction();
    ctx.success('success');
  }

  async check() {
    const { ctx } = this;
    const params = ctx.request.query;
    const {
      signature,
      timestamp,
      nonce,
      echostr,
    } = params;

    const array = [ '51gjj', timestamp, nonce ];
    array.sort();

    // 3.将三个参数字符串拼接成一个字符串进行sha1加密
    const tempStr = array.join('');
    const hashCode = crypto.createHash('sha1'); // 创建加密类型
    const resultCode = hashCode.update(tempStr, 'utf8').digest('hex');

    console.log(resultCode);
    // 4.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
    if (resultCode === signature) {
      ctx.success(echostr);
    } else {
      ctx.success();
    }
  }

  // 获取二维码
  async getQRCode() {
    const { ctx, service } = this;
    const params = ctx.request.body;

    if (ctx.isEmpty(params) || ctx.isEmpty(params.path)) {
      ctx.failed('path is empty');
    }
    if (ctx.isEmpty(params) || ctx.isEmpty(params.width)) {
      ctx.failed('width is empty');
    }

    const ret = await service.course.v5.wechat.getQRCode(params);
    ctx.success(ret);
  }

  // 获取小程序码
  async getUnlimitedCode() {
    const { ctx, service } = this;
    const params = ctx.request.body;

    if (ctx.isEmpty(params) || ctx.isEmpty(params.scene)) {
      ctx.failed('scene is empty');
    }

    const ret = await service.course.v5.wechat.getUnlimitedCode(params);
    ctx.success(ret);
  }
}

module.exports = WechatController;
