'use strict';

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

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

  async callbackAction() {
    const { ctx, service } = this;
    const ret = await service.course.v5.wechat.callbackAction();
    // if (ctx.isEmpty(ret)) {
    //   ctx.success('success');
    // } else {
    //   ctx.set('content-type', 'text/xml');
    //   ctx.body = ret;
    // }

    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);
  }


  // 支付回调
  async payNotify() {
    const { ctx } = this;
    ctx.set('Content-Type', 'text/xml');
    ctx.logger.info('pay_no');
    // 组装xml数据
    let xmlData = '<xml>';
    xmlData += '<return_code><![CDATA[SUCCESS]]></return_code>';
    xmlData += '<return_msg><![CDATA[OK]]></return_msg>';
    xmlData += '</xml>';
    ctx.body = xmlData;

    let data = '';
    ctx.req.setEncoding('utf8');
    ctx.req.on('data', function(chunk) {
      data += chunk;
    });
    const getxml = await new Promise(function(resolve) {
      ctx.req.on('end', function() {
        resolve(data);
      });
    });

    ctx.logger.info('getxml: ' + getxml);

    const parseObj = await new Promise(function(resolve) {
      xml2js(getxml, {
        explicitArray: false,
      }, function(err, json) {
        resolve(json);
      });
    });

    if (!ctx.isEmpty(parseObj)) {
      ctx.logger.info('wechat_pay_callback: ' + JSON.stringify(parseObj));
      if (parseObj.xml.return_code === 'SUCCESS') {
        await ctx.classModel.V5.CourseUserOrder.update({ pay_result: JSON.stringify(parseObj), status: 1, pay_time: moment().format('YYYY-MM-DD HH:mm:ss') }, { where: { order_no: parseObj.xml.out_trade_no } });
      }
    }

    return ctx.body;
  }
}

module.exports = WechatController;
