//云端数据同步导本地
import EventEmitter from "events";
// const EventEmitter = require("events");
import db from "./db";
// import env from "./env";
import api from "./api";

import _logger from "./logger";
const logger = _logger("sync.js");
import { send } from "./channel";

export async function queryStudentCount(store) {
  db.init();
  const results = await db.query(
    "select count(*) as count from eb_exam_student where exam_id=?",
    [store.env.exam.id]
  );
  return results[0].count;
}

export async function replaceStudents(students) {
  db.init();
  await db.batchQuery(
    "select 1 from eb_exam_student",
    []
    // "replace into eb_exam_student(id, exam_id, school_id\
    //           , exam_number, secret_number, name, student_code, subject_code, subject_name, campus_name\
    //           , package_code, batch_code, sheet_count, slice_count, answers, is_upload\
    //           , is_absent, is_manual_absent, is_breach, is_exception\
    //           , objective_score, subjective_score, objective_score_list, subjective_score_list, subjective_status\
    //           , exam_site, exam_room, remark, college, class_name, teacher, paper_type) \
    //           values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,?)",
    // students
  );
}

export async function replacePackage(packageData) {
  db.init();
  await db.batchQuery(
    "select 1 from eb_exam_student",
    []
    // "replace into eb_exam_package(exam_id, code, pic_count) values (?,?,?)",
    // packageData
  );
}

class executor extends EventEmitter {
  async start(env) {
    try {
      console.log(env);
      send("db on");
      db.init();
      send("db oned");

      const totalCount = await api.countStudents(env.examId);
      // logger.info("student count: " + totalCount);
      send({ totalCount });
      this.emit("total", totalCount);

      const promises = [];
      let count = 0;
      let pageNumber = 0;
      send({ student: 0 });
      this.emit("student", 0);
      while (true) {
        pageNumber++;
        logger.info("student page=" + pageNumber);
        const array = await api.getStudents(env.examId, pageNumber, 100, {
          withScoreDetail: true,
        });
        if (array == undefined || array.length == 0) {
          break;
        }
        const datas = [];
        for (let i = 0; i < array.length; i++) {
          const obj = array[i];
          var objList = [];
          var subList = [];
          if (obj.objectiveScoreDetail) {
            obj.objectiveScoreDetail.forEach((detail) => {
              const score = Math.round((detail.score * 10) / 10);
              objList.push(detail.answer + ":" + score);
            });
          }
          if (obj.subjectiveScoreDetail) {
            obj.subjectiveScoreDetail.forEach((detail) => {
              const score = Math.round((detail.score * 10) / 10);
              subList.push(score);
            });
          }
          datas.push([
            obj["id"],
            env.examId,
            obj["schoolId"],
            obj["examNumber"],
            obj["examNumber"],
            obj["name"],
            obj["studentCode"],
            obj["subjectCode"],
            obj["subjectName"],
            obj["campusName"],
            obj["packageCode"],
            obj["batchCode"],
            obj["sheetCount"],
            obj["sliceCount"],
            obj["answers"],
            obj["upload"] ? 1 : 0,
            obj["absent"] ? 1 : 0,
            obj["breach"] ? 1 : 0,
            obj["manualAbsent"] ? 1 : 0,
            obj["objectiveScore"].length > 0 ? obj["objectiveScore"] : 0,
            obj["subjectiveScore"].length > 0 ? obj["subjectiveScore"] : 0,
            objList.join(";"),
            subList.join(";"),
            obj["subjectiveStatus"] || "UNMARK",
            obj["examSite"],
            obj["examRoom"],
            obj["remark"],
            obj["college"] || "",
            obj["className"] || "",
            obj["teacher"] || "",
            obj["paperType"] || "",
          ]);
        }
        //console.log('get:' + array.length)
        promises.push(
          new Promise((resolve, reject) => {
            db.batchQuery(
              "select 1 from eb_exam_student"
              // "replace into eb_exam_student(id, exam_id, school_id\
              //           , exam_number, secret_number, name, student_code, subject_code, subject_name, campus_name\
              //           , package_code, batch_code, sheet_count, slice_count, answers, is_upload\
              //           , is_absent, is_manual_absent, is_breach, is_exception\
              //           , objective_score, subjective_score, objective_score_list, subjective_score_list, subjective_status\
              //           , exam_site, exam_room, remark, college, class_name, teacher, paper_type) \
              //           values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,?,?,?,?,?,?,?,?,?,?,?,?)",
              // datas
            )
              .then(() => {
                count += datas.length;
                send({ student: count });
                this.emit("student", count);
                resolve();
              })
              .catch((err) => {
                reject(err);
              });
          })
        );
      }

      //get and save package
      send({ package: 0 });
      this.emit("package", 0);
      const packages = await api.getPackages(env.examId);
      const packageData = [];
      for (let i = 0; i < packages.length; i++) {
        const obj = packages[i];
        packageData.push([env.examId, obj["code"], obj["picCount"]]);
      }
      logger.info("package count:" + packageData.length);
      promises.push(
        new Promise((resolve, reject) => {
          db.batchQuery(
            "replace into eb_exam_package(exam_id, code, pic_count) values (?,?,?)",
            packageData
          )
            .then(() => {
              send({ package: packageData.length });
              this.emit("package", packageData.length);
              resolve();
            })
            .catch((err) => {
              reject(err);
            });
        })
      );

      await Promise.all(promises);
      send({ finish: true });
      this.emit("finish");
    } catch (err) {
      this.emit("error", err);
      logger.error(err);
    } finally {
      //console.log(moment().format('YYYY-MM-DD HH:mm:ss'))
    }
  }
}

// export const syncer = new executor();

export default function (store) {
  console.log("objechat");
  return new executor().start(store.env);
}
