const cloud = require('wx-server-sdk')
const fs = require('fs')
const path = require('path')
const md5 = require('md5')
const https = require('http')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

exports.main = async (event) => {
  const {
    name,
    type,
    files,
    username
  } = event.data
  try {
    const db = cloud.database();

    // const fileids = await Promise.all(files.map(async v => {
    //   const buffer = await downloadFile(v)
    //   return await cloud.uploadFile({
    //     cloudPath: `contract/${OPENID}/${md5(buffer)}.${path.extname(v)}`,
    //     fileContent: fileStream,
    //   })
    // }))

    await db.collection('contract').add({
      data: {
        username,
        name,
        type,
        createDate: new Date(),
        fileIds: files,
      }
    })
    return {
      success: true
    }
  } catch (err) {
    return {
      success: false,
      msg: err.message
    }
  }

}

function downloadFile(url) {
  return new Promise((resolve, reject) => {
    https.get(url, (res) => {
      let data = [];

      // 分段接收数据
      res.on('data', (chunk) => {
        data.push(chunk);
      });

      // 下载完成后处理数据
      res.on('end', () => {
        const buffer = Buffer.concat(data);
        resolve(buffer);
      });

      res.on('error', (err) => {
        reject(err);
      });
    });
  });
}