'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.wechat.sendMsg(data);
    ctx.success();
  }

  async callbackAction() {
    const { ctx, service } = this;
    await service.course.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();
    }
  }
}

module.exports = WechatController;
