var express = require('express');
var router = express.Router();
const { spawn } = require('child_process');
const fs = require("fs");

const method = require("../config/method")
const config = require("../config/config")

const { GETCLASSURL, GETCLASSURLPARAMETER, PROJECTCATALOG, PROJECTWINCATALOG, BACKMEDIACONFIG } = config
const { YesterdayTime, getRequestClassIds } = method

const { startTime, endTime, ymd } = YesterdayTime()
let siteIds = GETCLASSURLPARAMETER.siteId

let classid = []
let parentData = {}
var classobj = {};
let className = ""
/**
 * 
 * @param {*} id 课堂id
 */
class MediaCreat {
  constructor() { }
  // 取出所有数据
  async allData() {
    let page = 1
    className = siteIds.shift()
    if (className) {
      let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime, page)
      parentData[result.data.data.siteId] = []

      for (let j = 0; j < result.data.data.list.length; j++) {
        classid.push(result.data.data.list[j])
      }
      const { siteId, list, totalPage } = result.data.data
      for (let i = page += 1; i <= totalPage; i++) {
        let result = await getRequestClassIds(GETCLASSURL, className, GETCLASSURLPARAMETER.key, startTime, endTime, i)
        for (let j = 0; j < result.data.data.list.length; j++) {
          classid.push(result.data.data.list[j])
        }
      }

      classid = classid.reduce(function (item, next) {
        classobj[next.classId] ? '' : classobj[next.classId] = true && item.push(next);
        return item;
      }, []);
      for (let i = 0; i < classid.length; i++) {
        parentData[result.data.data.siteId].push(classid[i].classId)
      }
      return true
    } else {
      return false
    }
  }
  async mediaCreat(id, siteId) {
    let mediaDir = PROJECTCATALOG + "/media/"
    let classDir = PROJECTCATALOG + "/media/" + siteId
    let ymdDir = PROJECTCATALOG + "/media/" + siteId + "/" + ymd
    if (!fs.existsSync(mediaDir)) {
      fs.mkdirSync(mediaDir);
    }
    if (!fs.existsSync(classDir)) {
      fs.mkdirSync(classDir);
    }
    if (!fs.existsSync(ymdDir)) {
      fs.mkdirSync(ymdDir);
    }
    let url = `web_capture_c -o=../media/${siteId}/${ymd}/${id}.mp4 -u="${BACKMEDIACONFIG.url}?classId=${id}&userId=${BACKMEDIACONFIG.userId}&userName=${BACKMEDIACONFIG.userName}&userRole=${BACKMEDIACONFIG.userRole}&portalIP=${BACKMEDIACONFIG.portalIP}&portalPort=${BACKMEDIACONFIG.portalPort}&channels=${BACKMEDIACONFIG.channels}&playRecord=${BACKMEDIACONFIG.playRecord}" -d=${BACKMEDIACONFIG.d} -s=${BACKMEDIACONFIG.s} -fa=${BACKMEDIACONFIG.fa} -k=${BACKMEDIACONFIG.k} -w=${BACKMEDIACONFIG.w} -h=${BACKMEDIACONFIG.h}`
    var workerProcess = spawn(url, { cwd: PROJECTWINCATALOG, shell: true })
    // workerProcess.stdout.on('data', async function (data) {

    // });

    workerProcess.on('close', async function (code) {
      let files = fs.readdirSync(ymdDir);
      if (files.indexOf(id + ".mp4") == -1) {
        //当前课堂没有写入到文件夹,进入重录
        new MediaCreat().mediaCreat(id, siteId)
        return false
      } else {
        if (parentData[siteId].indexOf(id.toString()) != -1) {
          parentData[siteId].splice(parentData[siteId].indexOf(id.toString()), 1)
        }
        if (parentData[siteId].length == 0) {
          //   //全部录制完毕
          fs.writeFile(ymdDir + "/download.json", `{ "code": "0", "success": "ok"}`, function (err) {
            if (err) {
              console.log(err);
            }
          });
        }
        if (classid.length) {
          let shiftData = classid.shift()
          new MediaCreat().mediaCreat(shiftData['classId'], shiftData['siteId'])
        } else {
          if (siteIds.length) {
            // 如果有多家需要录制,继续录制下一家
            let isAppend = await new MediaCreat().allData()
            if (isAppend) {
              let shiftData = classid.shift()
              new MediaCreat().mediaCreat(shiftData['classId'], shiftData['siteId'])
            }
          }
        }
      }
    });
  }
}


router.get('/', async function (req, res, next) {
  let isAppend = await new MediaCreat().allData()
  if (isAppend) {
    if (classid.length) {
      for (let i = 0; i < GETCLASSURLPARAMETER.maxMedia; i++) {
        let shiftData = classid.shift()
        if (shiftData) {
          new MediaCreat().mediaCreat(shiftData['classId'], shiftData['siteId'])
        } else {
          return false
        }
      }
    }
  }

  res.render('index', { title: 'Express' });
});

module.exports = router;