const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const xlsx = require('node-xlsx');
const fs = require("fs");

class WorkloadService extends ServiceBase {
  constructor() {
    super("common", ServiceBase.getDaoName(WorkloadService));
    this.restClient = system.getObject("util.restClient");
  }

  async pageByCondition(params) {
    var currentPage = Number(params.currentPage || 1);
    var pageSize = Number(params.pageSize || 10);

    var user_id = Number(params.userId);
    var username = this.trim(params.username);
    var iphone = this.trim(params.iphone);
    var id_nu = this.trim(params.id_nu);

    var where = {user_id: user_id};

    var orderby = [
      ["id", 'desc']
    ];

    if (username) {
      where.username = username;
    }
    if (iphone) {
      where.iphone = iphone;
    }
    if (id_nu) {
      where.id_nu = id_nu
    }
    if (params.status === 0 || params.status === 1) {
      where.status = params.status;
    }

    var page = await this.getPageList(currentPage, pageSize, where, orderby, null);
    if (page && page.rows) {
      for (var item of page.rows) {
        this.handleDate(item, ['created_time', 'updated_time'], 'YYYY-MM-DD');
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
      }
    }
    return page;
  }

  async workloadConfirm(params) {
    var sql = [];
    sql.push("UPDATE");
    sql.push("workload_info");
    sql.push("SET `status` = 1, updated_at = :updated_at");
    sql.push("WHERE `status` = 0 AND user_id = :userId");

    if (params.id) {
      sql.push("AND id = :id ");
    }
    await this.customUpdate(sql.join(" "), params);
    return 1;
  }

  async historyPage(params) {
    params.currentPage = Number(params.currentPage || 1);
    params.pageSize = Number(params.pageSize || 10);

    params.user_id = Number(params.userId);
    params.username = this.trim(params.username);
    params.iphone = this.trim(params.iphone);
    params.id_nu = this.trim(params.id_nu);
    params.status = this.trim(params.status);
    let total = await this.dao.countHistory(params);
    if (total == 0) {
      return {count: 1, rows: []};
    }

    params.startRow = (params.currentPage - 1) * params.pageSize;
    let list = await this.dao.pageHistory(params);
    if (list) {
      for (var item of list) {
        item.send_amount = parseFloat(Number(item.send_amount || 0).toFixed(2)).toString();
        this.handleDate(item, ['created_time', 'updated_time'], 'YYYY-MM-DD');
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
      }
    }
    return {count: total, rows: list};
  }

  async historyInfo(params) {
    params.user_id = Number(params.userId);
    let wl = await this.findById(params.id);
    if (!wl) {
      return [];
    }
    let list = await this.dao.findByIdNo({id_nu: wl.id_nu, user_id: params.user_id});
    if (list) {
      for (var item of list) {
        this.handleDate(item, ['created_time', 'updated_time'], 'YYYY-MM-DD');
        this.handleDate(item, ['updated_at', 'created_at'], 'YYYY-MM-DD HH:mm:ss');
      }
    }
    return list;
  }

  async paramXlsx(userId, ossurl) {
    var result = {
      code: 0,
      msg: "",
      list: [],
    };
    var filePath = "/tmp/esettle_offline_" + userId + ".xlsx";
    try {
      await this.restClient.execDownload("'" + ossurl + "'", filePath);
      var sheets = xlsx.parse(filePath);
      var rows = sheets[0].data;
      var resu = [];
      for (let i = 0; i < rows.length; i++) {
        if (2 > i) {
          continue;
        }
        var heads = rows[0];
        var cells = rows[i];
        if (cells.length < 9) {
          result.msg = "excel第" + i + "行，数据不全";
          return result;
        }
        for (let j = 0; j < cells.length; j++) {
          if (!cells[j]) {
            result.msg = "excel序号为" + cells[0] + "的" + heads[j] + "不能为空";
            return result;
          }
        }

        var data = {};
        data.user_id = userId;
        data.username = this.trim(cells[1]);
        data.iphone = this.trim(cells[2]);
        data.id_nu = this.trim(cells[3]);
        data.card_nu = this.trim(cells[4]);
        data.send_amount = this.trim(cells[5]);
        data.created_time = new Date(1900, 0, cells[6]);
        data.updated_time = new Date(1900, 0, cells[7]);
        data.workload = this.trim(cells[8]);
        data.status = 0;
        resu.push(data)
      }
      await this.dao.model.bulkCreate(resu, {fields: ["user_id", "username", "iphone", "id_nu", "card_nu", "send_amount", "created_time", "updated_time", "workload", "status"]});
      result.code = 1;
      result.msg = "上传成功";
      return result;
    } catch (e) {
      console.log(e);
      result.msg = "接口异常";
      return result;
    }
  }
}

module.exports = WorkloadService;