// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require("tcb-router")
const got = require('got')
const md5 = require("md5")
const APPID = "wxf22759845920b6f3"
const SECRET = "149873f78958781cd1693c1238deaebc"
const WXBizDataCrypt = require('./WXBizDataCrypt')

cloud.init()

const db = cloud.database()
const errorLogs = db.collection("huihenduo_error_log")

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const _openid = wxContext.OPENID

  const app = new TcbRouter({
    event
  });

  console.log('Event', event)

  app.use(async (ctx, next) => {
    ctx.data = {};
    await next();
  });


  app.router("getWxPhoneNumber", async (ctx, next) => {
    let {
      cloudID,
      encryptedData,
      errMsg,
      iv,
      session_key
    } = event
    console.log(event)

    let pc = new WXBizDataCrypt(APPID, session_key)

    let data = pc.decryptData(encryptedData, iv)

    ctx.body = {
      phone: data.phoneNumber,
      _openid
    }
    await next()
  })

  app.router("getOpenId", async (ctx, next) => {
    ctx.body = {
      openId: _openid
    }
    await next()
  })
  app.router("sendError", async (ctx, next) => {
    delete event.$url
    delete event.userInfo
    let res = await errorLogs.add({
      data: {
        createTime: db.serverDate(),
        ...event,
        _openid,
      }
    })
    await next()
  })

  app.router("base", async (ctx, next) => {

    await next()
  })

  app.router("code2Session", async (ctx, next) => {
    let JSCODE = event.JSCODE
    let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${JSCODE}&grant_type=authorization_code`

    let res = await got(url)
    let result = JSON.parse(res.body)
    ctx.body = {
      ...result,
      _openid
    }

    await next()
  })



  app.router("getAccessToken", async (ctx, next) => {
    let tokenUrl = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${APPID}&secret=${SECRET}`


    let res = await got(tokenUrl)
    let {
      access_token
    } = JSON.parse(res.body)
    console.log(access_token)
    ctx.data = {
      access_token
    }
    await next();
  });

  return app.serve();
}