// 云函数入口文件
const cloud = require('wx-server-sdk')

const TcbRouter = require('tcb-router')

cloud.init()

//初始化数据库
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const app = new TcbRouter({
    event
  })

  //获取all总条数
  //const total = await db.collection('category_all').count().total

  // 获取税收分类编码
  app.router('getCategoryTop', async (ctx, next) => {
    ctx.body = await db.collection('category_top').skip(event.start).limit(event.count).get().then(res => {
      return res
    })
  })

  //获取产品信息
  app.router('getCategoryAll', async (ctx, next) => {
    let params = {
      search_code: event.search_code
    }
    if (event.keyword) {
      params.keyword = {
        $regex: '.*' + event.keyword,
        $options: 'i'
      }
      /* ctx.body = await db.collection('category_all').where(_.or([{
        keyword: db.RegExp({
          $regex: '.*' + event.keyword,
          $options: 'i'
        })
      }])).and([{
        search_code: event.search_code
      }]).skip(event.start).limit(event.count).get().then(res => {
        return res
      }) */
    }
    ctx.body = await db.collection('category_all').where(params).skip(event.start).limit(event.count).get().then(res => {
      return res
    })
  })

  return app.serve()
}