import { genCode } from 'app/pubUtils/util';
import { MsgEncrypt } from "app/pubUtils/sysUtil";
import { Context } from 'egg';

module.exports = options => {
  return async function parmsDecode(ctx: Context, next) {
    let url = ctx.request.url;
    ctx.logcode = genCode(10);
    if(url.indexOf("/dev") == 0 || url.indexOf("/web") == 0 || url.indexOf("/cb") == 0) {
      ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`);
      await next();
      ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(ctx.body)}`)
      return;
    } 
    if (options.threshold && ctx.length < options.threshold) return;
    const reqBody = ctx.request.body;
    const reqHeader = ctx.request.header;

    console.log(ctx.app.config.decodeParm)
    if(ctx.app.config.decodeParm == false) {
      await next();
      return;
    }

    if (!reqBody.data) return;

    let msgEncrypt = new MsgEncrypt({ encodeK: reqHeader['k'], encodeV: reqHeader['v'] });
    const { aesKey, aesIV } = msgEncrypt.getKv();

    console.log(`encode str ${msgEncrypt.encryptMsg(reqBody)}`);

    try {
      let decryptResult = msgEncrypt.decryptMsg(reqBody.data);
      if(!decryptResult) throw new Error('params parse err');

      ctx.request.body = decryptResult;
      console.log('req body', ctx.request.body);
      ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] request: ${JSON.stringify(ctx.request.body)}`)
    } catch (e) {
      console.error('parms parse err');
      ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] request: parms parse err`)

    }

    try{
      await next();
    } catch(e) {
      ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] err: ${(<Error>e).stack}`);
      throw e;
    }
    const resBody = ctx.body;
    console.log('return value:', JSON.stringify(resBody));
    let resBodyWithEncrypt = msgEncrypt.encryptMsg(resBody);
    if (resBodyWithEncrypt) {
      ctx.body = { result: resBodyWithEncrypt, aesKey, aesIV };
      ctx.service.utils.log('INFO', `[${ctx.request.url}] [${ctx.logcode}] res: ${JSON.stringify(resBody)}`)
    } else {
      ctx.body = { result: msgEncrypt.encryptMsg({ status: 3, data: 'internal err' }), aesKey, aesIV };
      ctx.service.utils.log('ERROR', `[${ctx.request.url}] [${ctx.logcode}] res: ${resBody}`)
    }
  };
};

